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 /*
   24857 ** There are various methods for file locking used for concurrency
   24858 ** control:
   24859 **
   24860 **   1. POSIX locking (the default),
   24861 **   2. No locking,
   24862 **   3. Dot-file locking,
   24863 **   4. flock() locking,
   24864 **   5. AFP locking (OSX only),
   24865 **   6. Named POSIX semaphores (VXWorks only),
   24866 **   7. proxy locking. (OSX only)
   24867 **
   24868 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   24869 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   24870 ** selection of the appropriate locking style based on the filesystem
   24871 ** where the database is located.
   24872 */
   24873 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   24874 #  if defined(__APPLE__)
   24875 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   24876 #  else
   24877 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   24878 #  endif
   24879 #endif
   24880 
   24881 /*
   24882 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   24883 ** vxworks, or 0 otherwise.
   24884 */
   24885 #ifndef OS_VXWORKS
   24886 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   24887 #    define OS_VXWORKS 1
   24888 #  else
   24889 #    define OS_VXWORKS 0
   24890 #  endif
   24891 #endif
   24892 
   24893 /*
   24894 ** These #defines should enable >2GB file support on Posix if the
   24895 ** underlying operating system supports it.  If the OS lacks
   24896 ** large file support, these should be no-ops.
   24897 **
   24898 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   24899 ** on the compiler command line.  This is necessary if you are compiling
   24900 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
   24901 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
   24902 ** without this option, LFS is enable.  But LFS does not exist in the kernel
   24903 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
   24904 ** portability you should omit LFS.
   24905 **
   24906 ** The previous paragraph was written in 2005.  (This paragraph is written
   24907 ** on 2008-11-28.) These days, all Linux kernels support large files, so
   24908 ** you should probably leave LFS enabled.  But some embedded platforms might
   24909 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   24910 */
   24911 #ifndef SQLITE_DISABLE_LFS
   24912 # define _LARGE_FILE       1
   24913 # ifndef _FILE_OFFSET_BITS
   24914 #   define _FILE_OFFSET_BITS 64
   24915 # endif
   24916 # define _LARGEFILE_SOURCE 1
   24917 #endif
   24918 
   24919 /*
   24920 ** standard include files.
   24921 */
   24922 #include <sys/types.h>
   24923 #include <sys/stat.h>
   24924 #include <fcntl.h>
   24925 #include <unistd.h>
   24926 /* #include <time.h> */
   24927 #include <sys/time.h>
   24928 #include <errno.h>
   24929 #ifndef SQLITE_OMIT_WAL
   24930 #include <sys/mman.h>
   24931 #endif
   24932 
   24933 
   24934 #if SQLITE_ENABLE_LOCKING_STYLE
   24935 # include <sys/ioctl.h>
   24936 # if OS_VXWORKS
   24937 #  include <semaphore.h>
   24938 #  include <limits.h>
   24939 # else
   24940 #  include <sys/file.h>
   24941 #  include <sys/param.h>
   24942 # endif
   24943 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   24944 
   24945 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   24946 # include <sys/mount.h>
   24947 #endif
   24948 
   24949 #ifdef HAVE_UTIME
   24950 # include <utime.h>
   24951 #endif
   24952 
   24953 /*
   24954 ** Allowed values of unixFile.fsFlags
   24955 */
   24956 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   24957 
   24958 /*
   24959 ** If we are to be thread-safe, include the pthreads header and define
   24960 ** the SQLITE_UNIX_THREADS macro.
   24961 */
   24962 #if SQLITE_THREADSAFE
   24963 /* # include <pthread.h> */
   24964 # define SQLITE_UNIX_THREADS 1
   24965 #endif
   24966 
   24967 /*
   24968 ** Default permissions when creating a new file
   24969 */
   24970 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   24971 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   24972 #endif
   24973 
   24974 /*
   24975  ** Default permissions when creating auto proxy dir
   24976  */
   24977 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   24978 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   24979 #endif
   24980 
   24981 /*
   24982 ** Maximum supported path-length.
   24983 */
   24984 #define MAX_PATHNAME 512
   24985 
   24986 /*
   24987 ** Only set the lastErrno if the error code is a real error and not
   24988 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   24989 */
   24990 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   24991 
   24992 /* Forward references */
   24993 typedef struct unixShm unixShm;               /* Connection shared memory */
   24994 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   24995 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   24996 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   24997 
   24998 /*
   24999 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   25000 ** cannot be closed immediately. In these cases, instances of the following
   25001 ** structure are used to store the file descriptor while waiting for an
   25002 ** opportunity to either close or reuse it.
   25003 */
   25004 struct UnixUnusedFd {
   25005   int fd;                   /* File descriptor to close */
   25006   int flags;                /* Flags this file descriptor was opened with */
   25007   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   25008 };
   25009 
   25010 /*
   25011 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   25012 ** VFS implementations.
   25013 */
   25014 typedef struct unixFile unixFile;
   25015 struct unixFile {
   25016   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   25017   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   25018   unixInodeInfo *pInode;              /* Info about locks on this inode */
   25019   int h;                              /* The file descriptor */
   25020   unsigned char eFileLock;            /* The type of lock held on this fd */
   25021   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
   25022   int lastErrno;                      /* The unix errno from last I/O error */
   25023   void *lockingContext;               /* Locking style specific state */
   25024   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
   25025   const char *zPath;                  /* Name of the file */
   25026   unixShm *pShm;                      /* Shared memory segment information */
   25027   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   25028 #if SQLITE_ENABLE_LOCKING_STYLE
   25029   int openFlags;                      /* The flags specified at open() */
   25030 #endif
   25031 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   25032   unsigned fsFlags;                   /* cached details from statfs() */
   25033 #endif
   25034 #if OS_VXWORKS
   25035   struct vxworksFileId *pId;          /* Unique file ID */
   25036 #endif
   25037 #ifndef NDEBUG
   25038   /* The next group of variables are used to track whether or not the
   25039   ** transaction counter in bytes 24-27 of database files are updated
   25040   ** whenever any part of the database changes.  An assertion fault will
   25041   ** occur if a file is updated without also updating the transaction
   25042   ** counter.  This test is made to avoid new problems similar to the
   25043   ** one described by ticket #3584.
   25044   */
   25045   unsigned char transCntrChng;   /* True if the transaction counter changed */
   25046   unsigned char dbUpdate;        /* True if any part of database file changed */
   25047   unsigned char inNormalWrite;   /* True if in a normal write operation */
   25048 #endif
   25049 #ifdef SQLITE_TEST
   25050   /* In test mode, increase the size of this structure a bit so that
   25051   ** it is larger than the struct CrashFile defined in test6.c.
   25052   */
   25053   char aPadding[32];
   25054 #endif
   25055 };
   25056 
   25057 /*
   25058 ** Allowed values for the unixFile.ctrlFlags bitmask:
   25059 */
   25060 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
   25061 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   25062 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   25063 #ifndef SQLITE_DISABLE_DIRSYNC
   25064 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   25065 #else
   25066 # define UNIXFILE_DIRSYNC    0x00
   25067 #endif
   25068 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   25069 #define UNIXFILE_DELETE      0x20     /* Delete on close */
   25070 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
   25071 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
   25072 #define UNIXFILE_CHOWN      0x100     /* File ownership was changed */
   25073 
   25074 /*
   25075 ** Include code that is common to all os_*.c files
   25076 */
   25077 /************** Include os_common.h in the middle of os_unix.c ***************/
   25078 /************** Begin file os_common.h ***************************************/
   25079 /*
   25080 ** 2004 May 22
   25081 **
   25082 ** The author disclaims copyright to this source code.  In place of
   25083 ** a legal notice, here is a blessing:
   25084 **
   25085 **    May you do good and not evil.
   25086 **    May you find forgiveness for yourself and forgive others.
   25087 **    May you share freely, never taking more than you give.
   25088 **
   25089 ******************************************************************************
   25090 **
   25091 ** This file contains macros and a little bit of code that is common to
   25092 ** all of the platform-specific files (os_*.c) and is #included into those
   25093 ** files.
   25094 **
   25095 ** This file should be #included by the os_*.c files only.  It is not a
   25096 ** general purpose header file.
   25097 */
   25098 #ifndef _OS_COMMON_H_
   25099 #define _OS_COMMON_H_
   25100 
   25101 /*
   25102 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   25103 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   25104 ** switch.  The following code should catch this problem at compile-time.
   25105 */
   25106 #ifdef MEMORY_DEBUG
   25107 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   25108 #endif
   25109 
   25110 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   25111 # ifndef SQLITE_DEBUG_OS_TRACE
   25112 #   define SQLITE_DEBUG_OS_TRACE 0
   25113 # endif
   25114   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   25115 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   25116 #else
   25117 # define OSTRACE(X)
   25118 #endif
   25119 
   25120 /*
   25121 ** Macros for performance tracing.  Normally turned off.  Only works
   25122 ** on i486 hardware.
   25123 */
   25124 #ifdef SQLITE_PERFORMANCE_TRACE
   25125 
   25126 /*
   25127 ** hwtime.h contains inline assembler code for implementing
   25128 ** high-performance timing routines.
   25129 */
   25130 /************** Include hwtime.h in the middle of os_common.h ****************/
   25131 /************** Begin file hwtime.h ******************************************/
   25132 /*
   25133 ** 2008 May 27
   25134 **
   25135 ** The author disclaims copyright to this source code.  In place of
   25136 ** a legal notice, here is a blessing:
   25137 **
   25138 **    May you do good and not evil.
   25139 **    May you find forgiveness for yourself and forgive others.
   25140 **    May you share freely, never taking more than you give.
   25141 **
   25142 ******************************************************************************
   25143 **
   25144 ** This file contains inline asm code for retrieving "high-performance"
   25145 ** counters for x86 class CPUs.
   25146 */
   25147 #ifndef _HWTIME_H_
   25148 #define _HWTIME_H_
   25149 
   25150 /*
   25151 ** The following routine only works on pentium-class (or newer) processors.
   25152 ** It uses the RDTSC opcode to read the cycle count value out of the
   25153 ** processor and returns that value.  This can be used for high-res
   25154 ** profiling.
   25155 */
   25156 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   25157       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   25158 
   25159   #if defined(__GNUC__)
   25160 
   25161   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25162      unsigned int lo, hi;
   25163      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   25164      return (sqlite_uint64)hi << 32 | lo;
   25165   }
   25166 
   25167   #elif defined(_MSC_VER)
   25168 
   25169   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   25170      __asm {
   25171         rdtsc
   25172         ret       ; return value at EDX:EAX
   25173      }
   25174   }
   25175 
   25176   #endif
   25177 
   25178 #elif (defined(__GNUC__) && defined(__x86_64__))
   25179 
   25180   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25181       unsigned long val;
   25182       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   25183       return val;
   25184   }
   25185 
   25186 #elif (defined(__GNUC__) && defined(__ppc__))
   25187 
   25188   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   25189       unsigned long long retval;
   25190       unsigned long junk;
   25191       __asm__ __volatile__ ("\n\
   25192           1:      mftbu   %1\n\
   25193                   mftb    %L0\n\
   25194                   mftbu   %0\n\
   25195                   cmpw    %0,%1\n\
   25196                   bne     1b"
   25197                   : "=r" (retval), "=r" (junk));
   25198       return retval;
   25199   }
   25200 
   25201 #else
   25202 
   25203   #error Need implementation of sqlite3Hwtime() for your platform.
   25204 
   25205   /*
   25206   ** To compile without implementing sqlite3Hwtime() for your platform,
   25207   ** you can remove the above #error and use the following
   25208   ** stub function.  You will lose timing support for many
   25209   ** of the debugging and testing utilities, but it should at
   25210   ** least compile and run.
   25211   */
   25212 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   25213 
   25214 #endif
   25215 
   25216 #endif /* !defined(_HWTIME_H_) */
   25217 
   25218 /************** End of hwtime.h **********************************************/
   25219 /************** Continuing where we left off in os_common.h ******************/
   25220 
   25221 static sqlite_uint64 g_start;
   25222 static sqlite_uint64 g_elapsed;
   25223 #define TIMER_START       g_start=sqlite3Hwtime()
   25224 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   25225 #define TIMER_ELAPSED     g_elapsed
   25226 #else
   25227 #define TIMER_START
   25228 #define TIMER_END
   25229 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   25230 #endif
   25231 
   25232 /*
   25233 ** If we compile with the SQLITE_TEST macro set, then the following block
   25234 ** of code will give us the ability to simulate a disk I/O error.  This
   25235 ** is used for testing the I/O recovery logic.
   25236 */
   25237 #ifdef SQLITE_TEST
   25238 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   25239 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   25240 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   25241 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   25242 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   25243 SQLITE_API int sqlite3_diskfull_pending = 0;
   25244 SQLITE_API int sqlite3_diskfull = 0;
   25245 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   25246 #define SimulateIOError(CODE)  \
   25247   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   25248        || sqlite3_io_error_pending-- == 1 )  \
   25249               { local_ioerr(); CODE; }
   25250 static void local_ioerr(){
   25251   IOTRACE(("IOERR\n"));
   25252   sqlite3_io_error_hit++;
   25253   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   25254 }
   25255 #define SimulateDiskfullError(CODE) \
   25256    if( sqlite3_diskfull_pending ){ \
   25257      if( sqlite3_diskfull_pending == 1 ){ \
   25258        local_ioerr(); \
   25259        sqlite3_diskfull = 1; \
   25260        sqlite3_io_error_hit = 1; \
   25261        CODE; \
   25262      }else{ \
   25263        sqlite3_diskfull_pending--; \
   25264      } \
   25265    }
   25266 #else
   25267 #define SimulateIOErrorBenign(X)
   25268 #define SimulateIOError(A)
   25269 #define SimulateDiskfullError(A)
   25270 #endif
   25271 
   25272 /*
   25273 ** When testing, keep a count of the number of open files.
   25274 */
   25275 #ifdef SQLITE_TEST
   25276 SQLITE_API int sqlite3_open_file_count = 0;
   25277 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   25278 #else
   25279 #define OpenCounter(X)
   25280 #endif
   25281 
   25282 #endif /* !defined(_OS_COMMON_H_) */
   25283 
   25284 /************** End of os_common.h *******************************************/
   25285 /************** Continuing where we left off in os_unix.c ********************/
   25286 
   25287 /*
   25288 ** Define various macros that are missing from some systems.
   25289 */
   25290 #ifndef O_LARGEFILE
   25291 # define O_LARGEFILE 0
   25292 #endif
   25293 #ifdef SQLITE_DISABLE_LFS
   25294 # undef O_LARGEFILE
   25295 # define O_LARGEFILE 0
   25296 #endif
   25297 #ifndef O_NOFOLLOW
   25298 # define O_NOFOLLOW 0
   25299 #endif
   25300 #ifndef O_BINARY
   25301 # define O_BINARY 0
   25302 #endif
   25303 
   25304 /*
   25305 ** The threadid macro resolves to the thread-id or to 0.  Used for
   25306 ** testing and debugging only.
   25307 */
   25308 #if SQLITE_THREADSAFE
   25309 #define threadid pthread_self()
   25310 #else
   25311 #define threadid 0
   25312 #endif
   25313 
   25314 /*
   25315 ** Different Unix systems declare open() in different ways.  Same use
   25316 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
   25317 ** The difference is important when using a pointer to the function.
   25318 **
   25319 ** The safest way to deal with the problem is to always use this wrapper
   25320 ** which always has the same well-defined interface.
   25321 */
   25322 static int posixOpen(const char *zFile, int flags, int mode){
   25323   return open(zFile, flags, mode);
   25324 }
   25325 
   25326 /* Forward reference */
   25327 static int openDirectory(const char*, int*);
   25328 
   25329 /*
   25330 ** Many system calls are accessed through pointer-to-functions so that
   25331 ** they may be overridden at runtime to facilitate fault injection during
   25332 ** testing and sandboxing.  The following array holds the names and pointers
   25333 ** to all overrideable system calls.
   25334 */
   25335 static struct unix_syscall {
   25336   const char *zName;            /* Name of the sytem call */
   25337   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   25338   sqlite3_syscall_ptr pDefault; /* Default value */
   25339 } aSyscall[] = {
   25340   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
   25341 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
   25342 
   25343   { "close",        (sqlite3_syscall_ptr)close,      0  },
   25344 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
   25345 
   25346   { "access",       (sqlite3_syscall_ptr)access,     0  },
   25347 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
   25348 
   25349   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
   25350 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
   25351 
   25352   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
   25353 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
   25354 
   25355 /*
   25356 ** The DJGPP compiler environment looks mostly like Unix, but it
   25357 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   25358 ** that always succeeds.  This means that locking does not occur under
   25359 ** DJGPP.  But it is DOS - what did you expect?
   25360 */
   25361 #ifdef __DJGPP__
   25362   { "fstat",        0,                 0  },
   25363 #define osFstat(a,b,c)    0
   25364 #else
   25365   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
   25366 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
   25367 #endif
   25368 
   25369   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
   25370 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
   25371 
   25372   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
   25373 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
   25374 
   25375   { "read",         (sqlite3_syscall_ptr)read,       0  },
   25376 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
   25377 
   25378 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   25379   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
   25380 #else
   25381   { "pread",        (sqlite3_syscall_ptr)0,          0  },
   25382 #endif
   25383 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
   25384 
   25385 #if defined(USE_PREAD64)
   25386   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
   25387 #else
   25388   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
   25389 #endif
   25390 #ifdef ANDROID
   25391 // Bionic defines pread64 using off64_t rather than off_t.
   25392 #define osPread64   ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
   25393 #else
   25394 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
   25395 #endif
   25396 
   25397   { "write",        (sqlite3_syscall_ptr)write,      0  },
   25398 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
   25399 
   25400 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
   25401   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
   25402 #else
   25403   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
   25404 #endif
   25405 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
   25406                     aSyscall[12].pCurrent)
   25407 
   25408 #if defined(USE_PREAD64)
   25409   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
   25410 #else
   25411   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
   25412 #endif
   25413 #ifdef ANDROID
   25414 // Bionic defines pwrite64 using off64_t rather than off_t.
   25415 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
   25416                     aSyscall[13].pCurrent)
   25417 #else
   25418 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
   25419                     aSyscall[13].pCurrent)
   25420 #endif
   25421 
   25422 #if SQLITE_ENABLE_LOCKING_STYLE
   25423   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
   25424 #else
   25425   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
   25426 #endif
   25427 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
   25428 
   25429 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   25430   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
   25431 #else
   25432   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
   25433 #endif
   25434 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
   25435 
   25436   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   25437 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   25438 
   25439   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   25440 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   25441 
   25442   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
   25443 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
   25444 
   25445   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
   25446 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
   25447 
   25448   { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
   25449 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
   25450 
   25451   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
   25452 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
   25453 
   25454 }; /* End of the overrideable system calls */
   25455 
   25456 /*
   25457 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   25458 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   25459 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   25460 ** system call named zName.
   25461 */
   25462 static int unixSetSystemCall(
   25463   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   25464   const char *zName,            /* Name of system call to override */
   25465   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   25466 ){
   25467   unsigned int i;
   25468   int rc = SQLITE_NOTFOUND;
   25469 
   25470   UNUSED_PARAMETER(pNotUsed);
   25471   if( zName==0 ){
   25472     /* If no zName is given, restore all system calls to their default
   25473     ** settings and return NULL
   25474     */
   25475     rc = SQLITE_OK;
   25476     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25477       if( aSyscall[i].pDefault ){
   25478         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   25479       }
   25480     }
   25481   }else{
   25482     /* If zName is specified, operate on only the one system call
   25483     ** specified.
   25484     */
   25485     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25486       if( strcmp(zName, aSyscall[i].zName)==0 ){
   25487         if( aSyscall[i].pDefault==0 ){
   25488           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   25489         }
   25490         rc = SQLITE_OK;
   25491         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   25492         aSyscall[i].pCurrent = pNewFunc;
   25493         break;
   25494       }
   25495     }
   25496   }
   25497   return rc;
   25498 }
   25499 
   25500 /*
   25501 ** Return the value of a system call.  Return NULL if zName is not a
   25502 ** recognized system call name.  NULL is also returned if the system call
   25503 ** is currently undefined.
   25504 */
   25505 static sqlite3_syscall_ptr unixGetSystemCall(
   25506   sqlite3_vfs *pNotUsed,
   25507   const char *zName
   25508 ){
   25509   unsigned int i;
   25510 
   25511   UNUSED_PARAMETER(pNotUsed);
   25512   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   25513     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   25514   }
   25515   return 0;
   25516 }
   25517 
   25518 /*
   25519 ** Return the name of the first system call after zName.  If zName==NULL
   25520 ** then return the name of the first system call.  Return NULL if zName
   25521 ** is the last system call or if zName is not the name of a valid
   25522 ** system call.
   25523 */
   25524 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
   25525   int i = -1;
   25526 
   25527   UNUSED_PARAMETER(p);
   25528   if( zName ){
   25529     for(i=0; i<ArraySize(aSyscall)-1; i++){
   25530       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   25531     }
   25532   }
   25533   for(i++; i<ArraySize(aSyscall); i++){
   25534     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   25535   }
   25536   return 0;
   25537 }
   25538 
   25539 /*
   25540 ** Invoke open().  Do so multiple times, until it either succeeds or
   25541 ** files for some reason other than EINTR.
   25542 **
   25543 ** If the file creation mode "m" is 0 then set it to the default for
   25544 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
   25545 ** 0644) as modified by the system umask.  If m is not 0, then
   25546 ** make the file creation mode be exactly m ignoring the umask.
   25547 **
   25548 ** The m parameter will be non-zero only when creating -wal, -journal,
   25549 ** and -shm files.  We want those files to have *exactly* the same
   25550 ** permissions as their original database, unadulterated by the umask.
   25551 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
   25552 ** transaction crashes and leaves behind hot journals, then any
   25553 ** process that is able to write to the database will also be able to
   25554 ** recover the hot journals.
   25555 */
   25556 static int robust_open(const char *z, int f, mode_t m){
   25557   int rc;
   25558   mode_t m2;
   25559   mode_t origM = 0;
   25560   if( m==0 ){
   25561     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
   25562   }else{
   25563     m2 = m;
   25564     origM = osUmask(0);
   25565   }
   25566   do{ rc = osOpen(z,f,m2); }while( rc<0 && errno==EINTR );
   25567   if( m ){
   25568     osUmask(origM);
   25569   }
   25570   return rc;
   25571 }
   25572 
   25573 /*
   25574 ** Helper functions to obtain and relinquish the global mutex. The
   25575 ** global mutex is used to protect the unixInodeInfo and
   25576 ** vxworksFileId objects used by this file, all of which may be
   25577 ** shared by multiple threads.
   25578 **
   25579 ** Function unixMutexHeld() is used to assert() that the global mutex
   25580 ** is held when required. This function is only used as part of assert()
   25581 ** statements. e.g.
   25582 **
   25583 **   unixEnterMutex()
   25584 **     assert( unixMutexHeld() );
   25585 **   unixEnterLeave()
   25586 */
   25587 static void unixEnterMutex(void){
   25588   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25589 }
   25590 static void unixLeaveMutex(void){
   25591   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25592 }
   25593 #ifdef SQLITE_DEBUG
   25594 static int unixMutexHeld(void) {
   25595   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   25596 }
   25597 #endif
   25598 
   25599 
   25600 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   25601 /*
   25602 ** Helper function for printing out trace information from debugging
   25603 ** binaries. This returns the string represetation of the supplied
   25604 ** integer lock-type.
   25605 */
   25606 static const char *azFileLock(int eFileLock){
   25607   switch( eFileLock ){
   25608     case NO_LOCK: return "NONE";
   25609     case SHARED_LOCK: return "SHARED";
   25610     case RESERVED_LOCK: return "RESERVED";
   25611     case PENDING_LOCK: return "PENDING";
   25612     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   25613   }
   25614   return "ERROR";
   25615 }
   25616 #endif
   25617 
   25618 #ifdef SQLITE_LOCK_TRACE
   25619 /*
   25620 ** Print out information about all locking operations.
   25621 **
   25622 ** This routine is used for troubleshooting locks on multithreaded
   25623 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   25624 ** command-line option on the compiler.  This code is normally
   25625 ** turned off.
   25626 */
   25627 static int lockTrace(int fd, int op, struct flock *p){
   25628   char *zOpName, *zType;
   25629   int s;
   25630   int savedErrno;
   25631   if( op==F_GETLK ){
   25632     zOpName = "GETLK";
   25633   }else if( op==F_SETLK ){
   25634     zOpName = "SETLK";
   25635   }else{
   25636     s = osFcntl(fd, op, p);
   25637     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   25638     return s;
   25639   }
   25640   if( p->l_type==F_RDLCK ){
   25641     zType = "RDLCK";
   25642   }else if( p->l_type==F_WRLCK ){
   25643     zType = "WRLCK";
   25644   }else if( p->l_type==F_UNLCK ){
   25645     zType = "UNLCK";
   25646   }else{
   25647     assert( 0 );
   25648   }
   25649   assert( p->l_whence==SEEK_SET );
   25650   s = osFcntl(fd, op, p);
   25651   savedErrno = errno;
   25652   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   25653      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   25654      (int)p->l_pid, s);
   25655   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   25656     struct flock l2;
   25657     l2 = *p;
   25658     osFcntl(fd, F_GETLK, &l2);
   25659     if( l2.l_type==F_RDLCK ){
   25660       zType = "RDLCK";
   25661     }else if( l2.l_type==F_WRLCK ){
   25662       zType = "WRLCK";
   25663     }else if( l2.l_type==F_UNLCK ){
   25664       zType = "UNLCK";
   25665     }else{
   25666       assert( 0 );
   25667     }
   25668     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   25669        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   25670   }
   25671   errno = savedErrno;
   25672   return s;
   25673 }
   25674 #undef osFcntl
   25675 #define osFcntl lockTrace
   25676 #endif /* SQLITE_LOCK_TRACE */
   25677 
   25678 /*
   25679 ** Retry ftruncate() calls that fail due to EINTR
   25680 */
   25681 static int robust_ftruncate(int h, sqlite3_int64 sz){
   25682   int rc;
   25683   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
   25684   return rc;
   25685 }
   25686 
   25687 /*
   25688 ** This routine translates a standard POSIX errno code into something
   25689 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   25690 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   25691 ** and a variety of "please close the file descriptor NOW" errors into
   25692 ** SQLITE_IOERR
   25693 **
   25694 ** Errors during initialization of locks, or file system support for locks,
   25695 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   25696 */
   25697 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   25698   switch (posixError) {
   25699 #if 0
   25700   /* At one point this code was not commented out. In theory, this branch
   25701   ** should never be hit, as this function should only be called after
   25702   ** a locking-related function (i.e. fcntl()) has returned non-zero with
   25703   ** the value of errno as the first argument. Since a system call has failed,
   25704   ** errno should be non-zero.
   25705   **
   25706   ** Despite this, if errno really is zero, we still don't want to return
   25707   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
   25708   ** propagated back to the caller. Commenting this branch out means errno==0
   25709   ** will be handled by the "default:" case below.
   25710   */
   25711   case 0:
   25712     return SQLITE_OK;
   25713 #endif
   25714 
   25715   case EAGAIN:
   25716   case ETIMEDOUT:
   25717   case EBUSY:
   25718   case EINTR:
   25719   case ENOLCK:
   25720     /* random NFS retry error, unless during file system support
   25721      * introspection, in which it actually means what it says */
   25722     return SQLITE_BUSY;
   25723 
   25724   case EACCES:
   25725     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   25726     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   25727 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   25728 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   25729 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   25730       return SQLITE_BUSY;
   25731     }
   25732     /* else fall through */
   25733   case EPERM:
   25734     return SQLITE_PERM;
   25735 
   25736   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
   25737   ** this module never makes such a call. And the code in SQLite itself
   25738   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
   25739   ** this case is also commented out. If the system does set errno to EDEADLK,
   25740   ** the default SQLITE_IOERR_XXX code will be returned. */
   25741 #if 0
   25742   case EDEADLK:
   25743     return SQLITE_IOERR_BLOCKED;
   25744 #endif
   25745 
   25746 #if EOPNOTSUPP!=ENOTSUP
   25747   case EOPNOTSUPP:
   25748     /* something went terribly awry, unless during file system support
   25749      * introspection, in which it actually means what it says */
   25750 #endif
   25751 #ifdef ENOTSUP
   25752   case ENOTSUP:
   25753     /* invalid fd, unless during file system support introspection, in which
   25754      * it actually means what it says */
   25755 #endif
   25756   case EIO:
   25757   case EBADF:
   25758   case EINVAL:
   25759   case ENOTCONN:
   25760   case ENODEV:
   25761   case ENXIO:
   25762   case ENOENT:
   25763 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
   25764   case ESTALE:
   25765 #endif
   25766   case ENOSYS:
   25767     /* these should force the client to close the file and reconnect */
   25768 
   25769   default:
   25770     return sqliteIOErr;
   25771   }
   25772 }
   25773 
   25774 
   25775 
   25776 /******************************************************************************
   25777 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   25778 **
   25779 ** On most versions of unix, we can get a unique ID for a file by concatenating
   25780 ** the device number and the inode number.  But this does not work on VxWorks.
   25781 ** On VxWorks, a unique file id must be based on the canonical filename.
   25782 **
   25783 ** A pointer to an instance of the following structure can be used as a
   25784 ** unique file ID in VxWorks.  Each instance of this structure contains
   25785 ** a copy of the canonical filename.  There is also a reference count.
   25786 ** The structure is reclaimed when the number of pointers to it drops to
   25787 ** zero.
   25788 **
   25789 ** There are never very many files open at one time and lookups are not
   25790 ** a performance-critical path, so it is sufficient to put these
   25791 ** structures on a linked list.
   25792 */
   25793 struct vxworksFileId {
   25794   struct vxworksFileId *pNext;  /* Next in a list of them all */
   25795   int nRef;                     /* Number of references to this one */
   25796   int nName;                    /* Length of the zCanonicalName[] string */
   25797   char *zCanonicalName;         /* Canonical filename */
   25798 };
   25799 
   25800 #if OS_VXWORKS
   25801 /*
   25802 ** All unique filenames are held on a linked list headed by this
   25803 ** variable:
   25804 */
   25805 static struct vxworksFileId *vxworksFileList = 0;
   25806 
   25807 /*
   25808 ** Simplify a filename into its canonical form
   25809 ** by making the following changes:
   25810 **
   25811 **  * removing any trailing and duplicate /
   25812 **  * convert /./ into just /
   25813 **  * convert /A/../ where A is any simple name into just /
   25814 **
   25815 ** Changes are made in-place.  Return the new name length.
   25816 **
   25817 ** The original filename is in z[0..n-1].  Return the number of
   25818 ** characters in the simplified name.
   25819 */
   25820 static int vxworksSimplifyName(char *z, int n){
   25821   int i, j;
   25822   while( n>1 && z[n-1]=='/' ){ n--; }
   25823   for(i=j=0; i<n; i++){
   25824     if( z[i]=='/' ){
   25825       if( z[i+1]=='/' ) continue;
   25826       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   25827         i += 1;
   25828         continue;
   25829       }
   25830       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   25831         while( j>0 && z[j-1]!='/' ){ j--; }
   25832         if( j>0 ){ j--; }
   25833         i += 2;
   25834         continue;
   25835       }
   25836     }
   25837     z[j++] = z[i];
   25838   }
   25839   z[j] = 0;
   25840   return j;
   25841 }
   25842 
   25843 /*
   25844 ** Find a unique file ID for the given absolute pathname.  Return
   25845 ** a pointer to the vxworksFileId object.  This pointer is the unique
   25846 ** file ID.
   25847 **
   25848 ** The nRef field of the vxworksFileId object is incremented before
   25849 ** the object is returned.  A new vxworksFileId object is created
   25850 ** and added to the global list if necessary.
   25851 **
   25852 ** If a memory allocation error occurs, return NULL.
   25853 */
   25854 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   25855   struct vxworksFileId *pNew;         /* search key and new file ID */
   25856   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   25857   int n;                              /* Length of zAbsoluteName string */
   25858 
   25859   assert( zAbsoluteName[0]=='/' );
   25860   n = (int)strlen(zAbsoluteName);
   25861   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   25862   if( pNew==0 ) return 0;
   25863   pNew->zCanonicalName = (char*)&pNew[1];
   25864   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   25865   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   25866 
   25867   /* Search for an existing entry that matching the canonical name.
   25868   ** If found, increment the reference count and return a pointer to
   25869   ** the existing file ID.
   25870   */
   25871   unixEnterMutex();
   25872   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   25873     if( pCandidate->nName==n
   25874      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   25875     ){
   25876        sqlite3_free(pNew);
   25877        pCandidate->nRef++;
   25878        unixLeaveMutex();
   25879        return pCandidate;
   25880     }
   25881   }
   25882 
   25883   /* No match was found.  We will make a new file ID */
   25884   pNew->nRef = 1;
   25885   pNew->nName = n;
   25886   pNew->pNext = vxworksFileList;
   25887   vxworksFileList = pNew;
   25888   unixLeaveMutex();
   25889   return pNew;
   25890 }
   25891 
   25892 /*
   25893 ** Decrement the reference count on a vxworksFileId object.  Free
   25894 ** the object when the reference count reaches zero.
   25895 */
   25896 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   25897   unixEnterMutex();
   25898   assert( pId->nRef>0 );
   25899   pId->nRef--;
   25900   if( pId->nRef==0 ){
   25901     struct vxworksFileId **pp;
   25902     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   25903     assert( *pp==pId );
   25904     *pp = pId->pNext;
   25905     sqlite3_free(pId);
   25906   }
   25907   unixLeaveMutex();
   25908 }
   25909 #endif /* OS_VXWORKS */
   25910 /*************** End of Unique File ID Utility Used By VxWorks ****************
   25911 ******************************************************************************/
   25912 
   25913 
   25914 /******************************************************************************
   25915 *************************** Posix Advisory Locking ****************************
   25916 **
   25917 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   25918 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   25919 ** sets or clears a lock, that operation overrides any prior locks set
   25920 ** by the same process.  It does not explicitly say so, but this implies
   25921 ** that it overrides locks set by the same process using a different
   25922 ** file descriptor.  Consider this test case:
   25923 **
   25924 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   25925 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   25926 **
   25927 ** Suppose ./file1 and ./file2 are really the same file (because
   25928 ** one is a hard or symbolic link to the other) then if you set
   25929 ** an exclusive lock on fd1, then try to get an exclusive lock
   25930 ** on fd2, it works.  I would have expected the second lock to
   25931 ** fail since there was already a lock on the file due to fd1.
   25932 ** But not so.  Since both locks came from the same process, the
   25933 ** second overrides the first, even though they were on different
   25934 ** file descriptors opened on different file names.
   25935 **
   25936 ** This means that we cannot use POSIX locks to synchronize file access
   25937 ** among competing threads of the same process.  POSIX locks will work fine
   25938 ** to synchronize access for threads in separate processes, but not
   25939 ** threads within the same process.
   25940 **
   25941 ** To work around the problem, SQLite has to manage file locks internally
   25942 ** on its own.  Whenever a new database is opened, we have to find the
   25943 ** specific inode of the database file (the inode is determined by the
   25944 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   25945 ** and check for locks already existing on that inode.  When locks are
   25946 ** created or removed, we have to look at our own internal record of the
   25947 ** locks to see if another thread has previously set a lock on that same
   25948 ** inode.
   25949 **
   25950 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   25951 ** For VxWorks, we have to use the alternative unique ID system based on
   25952 ** canonical filename and implemented in the previous division.)
   25953 **
   25954 ** The sqlite3_file structure for POSIX is no longer just an integer file
   25955 ** descriptor.  It is now a structure that holds the integer file
   25956 ** descriptor and a pointer to a structure that describes the internal
   25957 ** locks on the corresponding inode.  There is one locking structure
   25958 ** per inode, so if the same inode is opened twice, both unixFile structures
   25959 ** point to the same locking structure.  The locking structure keeps
   25960 ** a reference count (so we will know when to delete it) and a "cnt"
   25961 ** field that tells us its internal lock status.  cnt==0 means the
   25962 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   25963 ** cnt>0 means there are cnt shared locks on the file.
   25964 **
   25965 ** Any attempt to lock or unlock a file first checks the locking
   25966 ** structure.  The fcntl() system call is only invoked to set a
   25967 ** POSIX lock if the internal lock structure transitions between
   25968 ** a locked and an unlocked state.
   25969 **
   25970 ** But wait:  there are yet more problems with POSIX advisory locks.
   25971 **
   25972 ** If you close a file descriptor that points to a file that has locks,
   25973 ** all locks on that file that are owned by the current process are
   25974 ** released.  To work around this problem, each unixInodeInfo object
   25975 ** maintains a count of the number of pending locks on tha inode.
   25976 ** When an attempt is made to close an unixFile, if there are
   25977 ** other unixFile open on the same inode that are holding locks, the call
   25978 ** to close() the file descriptor is deferred until all of the locks clear.
   25979 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   25980 ** be closed and that list is walked (and cleared) when the last lock
   25981 ** clears.
   25982 **
   25983 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   25984 **
   25985 ** Many older versions of linux use the LinuxThreads library which is
   25986 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   25987 ** A cannot be modified or overridden by a different thread B.
   25988 ** Only thread A can modify the lock.  Locking behavior is correct
   25989 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   25990 ** on linux - with NPTL a lock created by thread A can override locks
   25991 ** in thread B.  But there is no way to know at compile-time which
   25992 ** threading library is being used.  So there is no way to know at
   25993 ** compile-time whether or not thread A can override locks on thread B.
   25994 ** One has to do a run-time check to discover the behavior of the
   25995 ** current process.
   25996 **
   25997 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   25998 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   25999 ** LinuxThreads provided that (1) there is no more than one connection
   26000 ** per database file in the same process and (2) database connections
   26001 ** do not move across threads.
   26002 */
   26003 
   26004 /*
   26005 ** An instance of the following structure serves as the key used
   26006 ** to locate a particular unixInodeInfo object.
   26007 */
   26008 struct unixFileId {
   26009   dev_t dev;                  /* Device number */
   26010 #if OS_VXWORKS
   26011   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   26012 #else
   26013   ino_t ino;                  /* Inode number */
   26014 #endif
   26015 };
   26016 
   26017 /*
   26018 ** An instance of the following structure is allocated for each open
   26019 ** inode.  Or, on LinuxThreads, there is one of these structures for
   26020 ** each inode opened by each thread.
   26021 **
   26022 ** A single inode can have multiple file descriptors, so each unixFile
   26023 ** structure contains a pointer to an instance of this object and this
   26024 ** object keeps a count of the number of unixFile pointing to it.
   26025 */
   26026 struct unixInodeInfo {
   26027   struct unixFileId fileId;       /* The lookup key */
   26028   int nShared;                    /* Number of SHARED locks held */
   26029   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   26030   unsigned char bProcessLock;     /* An exclusive process lock is held */
   26031   int nRef;                       /* Number of pointers to this structure */
   26032   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   26033   int nLock;                      /* Number of outstanding file locks */
   26034   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   26035   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   26036   unixInodeInfo *pPrev;           /*    .... doubly linked */
   26037 #if SQLITE_ENABLE_LOCKING_STYLE
   26038   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   26039 #endif
   26040 #if OS_VXWORKS
   26041   sem_t *pSem;                    /* Named POSIX semaphore */
   26042   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   26043 #endif
   26044 };
   26045 
   26046 /*
   26047 ** A lists of all unixInodeInfo objects.
   26048 */
   26049 static unixInodeInfo *inodeList = 0;
   26050 
   26051 /*
   26052 **
   26053 ** This function - unixLogError_x(), is only ever called via the macro
   26054 ** unixLogError().
   26055 **
   26056 ** It is invoked after an error occurs in an OS function and errno has been
   26057 ** set. It logs a message using sqlite3_log() containing the current value of
   26058 ** errno and, if possible, the human-readable equivalent from strerror() or
   26059 ** strerror_r().
   26060 **
   26061 ** The first argument passed to the macro should be the error code that
   26062 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   26063 ** The two subsequent arguments should be the name of the OS function that
   26064 ** failed (e.g. "unlink", "open") and the the associated file-system path,
   26065 ** if any.
   26066 */
   26067 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
   26068 static int unixLogErrorAtLine(
   26069   int errcode,                    /* SQLite error code */
   26070   const char *zFunc,              /* Name of OS function that failed */
   26071   const char *zPath,              /* File path associated with error */
   26072   int iLine                       /* Source line number where error occurred */
   26073 ){
   26074   char *zErr;                     /* Message from strerror() or equivalent */
   26075   int iErrno = errno;             /* Saved syscall error number */
   26076 
   26077   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   26078   ** the strerror() function to obtain the human-readable error message
   26079   ** equivalent to errno. Otherwise, use strerror_r().
   26080   */
   26081 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   26082   char aErr[80];
   26083   memset(aErr, 0, sizeof(aErr));
   26084   zErr = aErr;
   26085 
   26086   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   26087   ** assume that the system provides the the GNU version of strerror_r() that
   26088   ** returns a pointer to a buffer containing the error message. That pointer
   26089   ** may point to aErr[], or it may point to some static storage somewhere.
   26090   ** Otherwise, assume that the system provides the POSIX version of
   26091   ** strerror_r(), which always writes an error message into aErr[].
   26092   **
   26093   ** If the code incorrectly assumes that it is the POSIX version that is
   26094   ** available, the error message will often be an empty string. Not a
   26095   ** huge problem. Incorrectly concluding that the GNU version is available
   26096   ** could lead to a segfault though.
   26097   */
   26098 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   26099   zErr =
   26100 # endif
   26101   strerror_r(iErrno, aErr, sizeof(aErr)-1);
   26102 
   26103 #elif SQLITE_THREADSAFE
   26104   /* This is a threadsafe build, but strerror_r() is not available. */
   26105   zErr = "";
   26106 #else
   26107   /* Non-threadsafe build, use strerror(). */
   26108   zErr = strerror(iErrno);
   26109 #endif
   26110 
   26111   assert( errcode!=SQLITE_OK );
   26112   if( zPath==0 ) zPath = "";
   26113   sqlite3_log(errcode,
   26114       "os_unix.c:%d: (%d) %s(%s) - %s",
   26115       iLine, iErrno, zFunc, zPath, zErr
   26116   );
   26117 
   26118   return errcode;
   26119 }
   26120 
   26121 /*
   26122 ** Close a file descriptor.
   26123 **
   26124 ** We assume that close() almost always works, since it is only in a
   26125 ** very sick application or on a very sick platform that it might fail.
   26126 ** If it does fail, simply leak the file descriptor, but do log the
   26127 ** error.
   26128 **
   26129 ** Note that it is not safe to retry close() after EINTR since the
   26130 ** file descriptor might have already been reused by another thread.
   26131 ** So we don't even try to recover from an EINTR.  Just log the error
   26132 ** and move on.
   26133 */
   26134 static void robust_close(unixFile *pFile, int h, int lineno){
   26135   if( osClose(h) ){
   26136     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
   26137                        pFile ? pFile->zPath : 0, lineno);
   26138   }
   26139 }
   26140 
   26141 /*
   26142 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   26143 */
   26144 static void closePendingFds(unixFile *pFile){
   26145   unixInodeInfo *pInode = pFile->pInode;
   26146   UnixUnusedFd *p;
   26147   UnixUnusedFd *pNext;
   26148   for(p=pInode->pUnused; p; p=pNext){
   26149     pNext = p->pNext;
   26150     robust_close(pFile, p->fd, __LINE__);
   26151     sqlite3_free(p);
   26152   }
   26153   pInode->pUnused = 0;
   26154 }
   26155 
   26156 /*
   26157 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   26158 **
   26159 ** The mutex entered using the unixEnterMutex() function must be held
   26160 ** when this function is called.
   26161 */
   26162 static void releaseInodeInfo(unixFile *pFile){
   26163   unixInodeInfo *pInode = pFile->pInode;
   26164   assert( unixMutexHeld() );
   26165   if( ALWAYS(pInode) ){
   26166     pInode->nRef--;
   26167     if( pInode->nRef==0 ){
   26168       assert( pInode->pShmNode==0 );
   26169       closePendingFds(pFile);
   26170       if( pInode->pPrev ){
   26171         assert( pInode->pPrev->pNext==pInode );
   26172         pInode->pPrev->pNext = pInode->pNext;
   26173       }else{
   26174         assert( inodeList==pInode );
   26175         inodeList = pInode->pNext;
   26176       }
   26177       if( pInode->pNext ){
   26178         assert( pInode->pNext->pPrev==pInode );
   26179         pInode->pNext->pPrev = pInode->pPrev;
   26180       }
   26181       sqlite3_free(pInode);
   26182     }
   26183   }
   26184 }
   26185 
   26186 /*
   26187 ** Given a file descriptor, locate the unixInodeInfo object that
   26188 ** describes that file descriptor.  Create a new one if necessary.  The
   26189 ** return value might be uninitialized if an error occurs.
   26190 **
   26191 ** The mutex entered using the unixEnterMutex() function must be held
   26192 ** when this function is called.
   26193 **
   26194 ** Return an appropriate error code.
   26195 */
   26196 static int findInodeInfo(
   26197   unixFile *pFile,               /* Unix file with file desc used in the key */
   26198   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   26199 ){
   26200   int rc;                        /* System call return code */
   26201   int fd;                        /* The file descriptor for pFile */
   26202   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   26203   struct stat statbuf;           /* Low-level file information */
   26204   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   26205 
   26206   assert( unixMutexHeld() );
   26207 
   26208   /* Get low-level information about the file that we can used to
   26209   ** create a unique name for the file.
   26210   */
   26211   fd = pFile->h;
   26212   rc = osFstat(fd, &statbuf);
   26213   if( rc!=0 ){
   26214     pFile->lastErrno = errno;
   26215 #ifdef EOVERFLOW
   26216     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   26217 #endif
   26218     return SQLITE_IOERR;
   26219   }
   26220 
   26221 #ifdef __APPLE__
   26222   /* On OS X on an msdos filesystem, the inode number is reported
   26223   ** incorrectly for zero-size files.  See ticket #3260.  To work
   26224   ** around this problem (we consider it a bug in OS X, not SQLite)
   26225   ** we always increase the file size to 1 by writing a single byte
   26226   ** prior to accessing the inode number.  The one byte written is
   26227   ** an ASCII 'S' character which also happens to be the first byte
   26228   ** in the header of every SQLite database.  In this way, if there
   26229   ** is a race condition such that another thread has already populated
   26230   ** the first page of the database, no damage is done.
   26231   */
   26232   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   26233     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
   26234     if( rc!=1 ){
   26235       pFile->lastErrno = errno;
   26236       return SQLITE_IOERR;
   26237     }
   26238     rc = osFstat(fd, &statbuf);
   26239     if( rc!=0 ){
   26240       pFile->lastErrno = errno;
   26241       return SQLITE_IOERR;
   26242     }
   26243   }
   26244 #endif
   26245 
   26246   memset(&fileId, 0, sizeof(fileId));
   26247   fileId.dev = statbuf.st_dev;
   26248 #if OS_VXWORKS
   26249   fileId.pId = pFile->pId;
   26250 #else
   26251   fileId.ino = statbuf.st_ino;
   26252 #endif
   26253   pInode = inodeList;
   26254   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   26255     pInode = pInode->pNext;
   26256   }
   26257   if( pInode==0 ){
   26258     pInode = sqlite3_malloc( sizeof(*pInode) );
   26259     if( pInode==0 ){
   26260       return SQLITE_NOMEM;
   26261     }
   26262     memset(pInode, 0, sizeof(*pInode));
   26263     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   26264     pInode->nRef = 1;
   26265     pInode->pNext = inodeList;
   26266     pInode->pPrev = 0;
   26267     if( inodeList ) inodeList->pPrev = pInode;
   26268     inodeList = pInode;
   26269   }else{
   26270     pInode->nRef++;
   26271   }
   26272   *ppInode = pInode;
   26273   return SQLITE_OK;
   26274 }
   26275 
   26276 
   26277 /*
   26278 ** This routine checks if there is a RESERVED lock held on the specified
   26279 ** file by this or any other process. If such a lock is held, set *pResOut
   26280 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26281 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26282 */
   26283 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   26284   int rc = SQLITE_OK;
   26285   int reserved = 0;
   26286   unixFile *pFile = (unixFile*)id;
   26287 
   26288   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26289 
   26290   assert( pFile );
   26291   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   26292 
   26293   /* Check if a thread in this process holds such a lock */
   26294   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   26295     reserved = 1;
   26296   }
   26297 
   26298   /* Otherwise see if some other process holds it.
   26299   */
   26300 #ifndef __DJGPP__
   26301   if( !reserved && !pFile->pInode->bProcessLock ){
   26302     struct flock lock;
   26303     lock.l_whence = SEEK_SET;
   26304     lock.l_start = RESERVED_BYTE;
   26305     lock.l_len = 1;
   26306     lock.l_type = F_WRLCK;
   26307     if( osFcntl(pFile->h, F_GETLK, &lock) ){
   26308       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
   26309       pFile->lastErrno = errno;
   26310     } else if( lock.l_type!=F_UNLCK ){
   26311       reserved = 1;
   26312     }
   26313   }
   26314 #endif
   26315 
   26316   unixLeaveMutex();
   26317   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   26318 
   26319   *pResOut = reserved;
   26320   return rc;
   26321 }
   26322 
   26323 /*
   26324 ** Attempt to set a system-lock on the file pFile.  The lock is
   26325 ** described by pLock.
   26326 **
   26327 ** If the pFile was opened read/write from unix-excl, then the only lock
   26328 ** ever obtained is an exclusive lock, and it is obtained exactly once
   26329 ** the first time any lock is attempted.  All subsequent system locking
   26330 ** operations become no-ops.  Locking operations still happen internally,
   26331 ** in order to coordinate access between separate database connections
   26332 ** within this process, but all of that is handled in memory and the
   26333 ** operating system does not participate.
   26334 **
   26335 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
   26336 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
   26337 ** and is read-only.
   26338 **
   26339 ** Zero is returned if the call completes successfully, or -1 if a call
   26340 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
   26341 */
   26342 static int unixFileLock(unixFile *pFile, struct flock *pLock){
   26343   int rc;
   26344   unixInodeInfo *pInode = pFile->pInode;
   26345   assert( unixMutexHeld() );
   26346   assert( pInode!=0 );
   26347   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
   26348    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
   26349   ){
   26350     if( pInode->bProcessLock==0 ){
   26351       struct flock lock;
   26352       assert( pInode->nLock==0 );
   26353       lock.l_whence = SEEK_SET;
   26354       lock.l_start = SHARED_FIRST;
   26355       lock.l_len = SHARED_SIZE;
   26356       lock.l_type = F_WRLCK;
   26357       rc = osFcntl(pFile->h, F_SETLK, &lock);
   26358       if( rc<0 ) return rc;
   26359       pInode->bProcessLock = 1;
   26360       pInode->nLock++;
   26361     }else{
   26362       rc = 0;
   26363     }
   26364   }else{
   26365     rc = osFcntl(pFile->h, F_SETLK, pLock);
   26366   }
   26367   return rc;
   26368 }
   26369 
   26370 /*
   26371 ** Lock the file with the lock specified by parameter eFileLock - one
   26372 ** of the following:
   26373 **
   26374 **     (1) SHARED_LOCK
   26375 **     (2) RESERVED_LOCK
   26376 **     (3) PENDING_LOCK
   26377 **     (4) EXCLUSIVE_LOCK
   26378 **
   26379 ** Sometimes when requesting one lock state, additional lock states
   26380 ** are inserted in between.  The locking might fail on one of the later
   26381 ** transitions leaving the lock state different from what it started but
   26382 ** still short of its goal.  The following chart shows the allowed
   26383 ** transitions and the inserted intermediate states:
   26384 **
   26385 **    UNLOCKED -> SHARED
   26386 **    SHARED -> RESERVED
   26387 **    SHARED -> (PENDING) -> EXCLUSIVE
   26388 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26389 **    PENDING -> EXCLUSIVE
   26390 **
   26391 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26392 ** routine to lower a locking level.
   26393 */
   26394 static int unixLock(sqlite3_file *id, int eFileLock){
   26395   /* The following describes the implementation of the various locks and
   26396   ** lock transitions in terms of the POSIX advisory shared and exclusive
   26397   ** lock primitives (called read-locks and write-locks below, to avoid
   26398   ** confusion with SQLite lock names). The algorithms are complicated
   26399   ** slightly in order to be compatible with windows systems simultaneously
   26400   ** accessing the same database file, in case that is ever required.
   26401   **
   26402   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   26403   ** byte', each single bytes at well known offsets, and the 'shared byte
   26404   ** range', a range of 510 bytes at a well known offset.
   26405   **
   26406   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   26407   ** byte'.  If this is successful, a random byte from the 'shared byte
   26408   ** range' is read-locked and the lock on the 'pending byte' released.
   26409   **
   26410   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   26411   ** A RESERVED lock is implemented by grabbing a write-lock on the
   26412   ** 'reserved byte'.
   26413   **
   26414   ** A process may only obtain a PENDING lock after it has obtained a
   26415   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   26416   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   26417   ** obtained, but existing SHARED locks are allowed to persist. A process
   26418   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   26419   ** This property is used by the algorithm for rolling back a journal file
   26420   ** after a crash.
   26421   **
   26422   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   26423   ** implemented by obtaining a write-lock on the entire 'shared byte
   26424   ** range'. Since all other locks require a read-lock on one of the bytes
   26425   ** within this range, this ensures that no other locks are held on the
   26426   ** database.
   26427   **
   26428   ** The reason a single byte cannot be used instead of the 'shared byte
   26429   ** range' is that some versions of windows do not support read-locks. By
   26430   ** locking a random byte from a range, concurrent SHARED locks may exist
   26431   ** even if the locking primitive used is always a write-lock.
   26432   */
   26433   int rc = SQLITE_OK;
   26434   unixFile *pFile = (unixFile*)id;
   26435   unixInodeInfo *pInode;
   26436   struct flock lock;
   26437   int tErrno = 0;
   26438 
   26439   assert( pFile );
   26440   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   26441       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   26442       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
   26443 
   26444   /* If there is already a lock of this type or more restrictive on the
   26445   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   26446   ** unixEnterMutex() hasn't been called yet.
   26447   */
   26448   if( pFile->eFileLock>=eFileLock ){
   26449     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   26450             azFileLock(eFileLock)));
   26451     return SQLITE_OK;
   26452   }
   26453 
   26454   /* Make sure the locking sequence is correct.
   26455   **  (1) We never move from unlocked to anything higher than shared lock.
   26456   **  (2) SQLite never explicitly requests a pendig lock.
   26457   **  (3) A shared lock is always held when a reserve lock is requested.
   26458   */
   26459   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   26460   assert( eFileLock!=PENDING_LOCK );
   26461   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   26462 
   26463   /* This mutex is needed because pFile->pInode is shared across threads
   26464   */
   26465   unixEnterMutex();
   26466   pInode = pFile->pInode;
   26467 
   26468   /* If some thread using this PID has a lock via a different unixFile*
   26469   ** handle that precludes the requested lock, return BUSY.
   26470   */
   26471   if( (pFile->eFileLock!=pInode->eFileLock &&
   26472           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   26473   ){
   26474     rc = SQLITE_BUSY;
   26475     goto end_lock;
   26476   }
   26477 
   26478   /* If a SHARED lock is requested, and some thread using this PID already
   26479   ** has a SHARED or RESERVED lock, then increment reference counts and
   26480   ** return SQLITE_OK.
   26481   */
   26482   if( eFileLock==SHARED_LOCK &&
   26483       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   26484     assert( eFileLock==SHARED_LOCK );
   26485     assert( pFile->eFileLock==0 );
   26486     assert( pInode->nShared>0 );
   26487     pFile->eFileLock = SHARED_LOCK;
   26488     pInode->nShared++;
   26489     pInode->nLock++;
   26490     goto end_lock;
   26491   }
   26492 
   26493 
   26494   /* A PENDING lock is needed before acquiring a SHARED lock and before
   26495   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   26496   ** be released.
   26497   */
   26498   lock.l_len = 1L;
   26499   lock.l_whence = SEEK_SET;
   26500   if( eFileLock==SHARED_LOCK
   26501       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   26502   ){
   26503     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   26504     lock.l_start = PENDING_BYTE;
   26505     if( unixFileLock(pFile, &lock) ){
   26506       tErrno = errno;
   26507       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26508       if( rc!=SQLITE_BUSY ){
   26509         pFile->lastErrno = tErrno;
   26510       }
   26511       goto end_lock;
   26512     }
   26513   }
   26514 
   26515 
   26516   /* If control gets to this point, then actually go ahead and make
   26517   ** operating system calls for the specified lock.
   26518   */
   26519   if( eFileLock==SHARED_LOCK ){
   26520     assert( pInode->nShared==0 );
   26521     assert( pInode->eFileLock==0 );
   26522     assert( rc==SQLITE_OK );
   26523 
   26524     /* Now get the read-lock */
   26525     lock.l_start = SHARED_FIRST;
   26526     lock.l_len = SHARED_SIZE;
   26527     if( unixFileLock(pFile, &lock) ){
   26528       tErrno = errno;
   26529       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26530     }
   26531 
   26532     /* Drop the temporary PENDING lock */
   26533     lock.l_start = PENDING_BYTE;
   26534     lock.l_len = 1L;
   26535     lock.l_type = F_UNLCK;
   26536     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
   26537       /* This could happen with a network mount */
   26538       tErrno = errno;
   26539       rc = SQLITE_IOERR_UNLOCK;
   26540     }
   26541 
   26542     if( rc ){
   26543       if( rc!=SQLITE_BUSY ){
   26544         pFile->lastErrno = tErrno;
   26545       }
   26546       goto end_lock;
   26547     }else{
   26548       pFile->eFileLock = SHARED_LOCK;
   26549       pInode->nLock++;
   26550       pInode->nShared = 1;
   26551     }
   26552   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   26553     /* We are trying for an exclusive lock but another thread in this
   26554     ** same process is still holding a shared lock. */
   26555     rc = SQLITE_BUSY;
   26556   }else{
   26557     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   26558     ** assumed that there is a SHARED or greater lock on the file
   26559     ** already.
   26560     */
   26561     assert( 0!=pFile->eFileLock );
   26562     lock.l_type = F_WRLCK;
   26563 
   26564     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
   26565     if( eFileLock==RESERVED_LOCK ){
   26566       lock.l_start = RESERVED_BYTE;
   26567       lock.l_len = 1L;
   26568     }else{
   26569       lock.l_start = SHARED_FIRST;
   26570       lock.l_len = SHARED_SIZE;
   26571     }
   26572 
   26573     if( unixFileLock(pFile, &lock) ){
   26574       tErrno = errno;
   26575       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   26576       if( rc!=SQLITE_BUSY ){
   26577         pFile->lastErrno = tErrno;
   26578       }
   26579     }
   26580   }
   26581 
   26582 
   26583 #ifndef NDEBUG
   26584   /* Set up the transaction-counter change checking flags when
   26585   ** transitioning from a SHARED to a RESERVED lock.  The change
   26586   ** from SHARED to RESERVED marks the beginning of a normal
   26587   ** write operation (not a hot journal rollback).
   26588   */
   26589   if( rc==SQLITE_OK
   26590    && pFile->eFileLock<=SHARED_LOCK
   26591    && eFileLock==RESERVED_LOCK
   26592   ){
   26593     pFile->transCntrChng = 0;
   26594     pFile->dbUpdate = 0;
   26595     pFile->inNormalWrite = 1;
   26596   }
   26597 #endif
   26598 
   26599 
   26600   if( rc==SQLITE_OK ){
   26601     pFile->eFileLock = eFileLock;
   26602     pInode->eFileLock = eFileLock;
   26603   }else if( eFileLock==EXCLUSIVE_LOCK ){
   26604     pFile->eFileLock = PENDING_LOCK;
   26605     pInode->eFileLock = PENDING_LOCK;
   26606   }
   26607 
   26608 end_lock:
   26609   unixLeaveMutex();
   26610   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   26611       rc==SQLITE_OK ? "ok" : "failed"));
   26612   return rc;
   26613 }
   26614 
   26615 /*
   26616 ** Add the file descriptor used by file handle pFile to the corresponding
   26617 ** pUnused list.
   26618 */
   26619 static void setPendingFd(unixFile *pFile){
   26620   unixInodeInfo *pInode = pFile->pInode;
   26621   UnixUnusedFd *p = pFile->pUnused;
   26622   p->pNext = pInode->pUnused;
   26623   pInode->pUnused = p;
   26624   pFile->h = -1;
   26625   pFile->pUnused = 0;
   26626 }
   26627 
   26628 /*
   26629 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26630 ** must be either NO_LOCK or SHARED_LOCK.
   26631 **
   26632 ** If the locking level of the file descriptor is already at or below
   26633 ** the requested locking level, this routine is a no-op.
   26634 **
   26635 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   26636 ** the byte range is divided into 2 parts and the first part is unlocked then
   26637 ** set to a read lock, then the other part is simply unlocked.  This works
   26638 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   26639 ** remove the write lock on a region when a read lock is set.
   26640 */
   26641 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   26642   unixFile *pFile = (unixFile*)id;
   26643   unixInodeInfo *pInode;
   26644   struct flock lock;
   26645   int rc = SQLITE_OK;
   26646 
   26647   assert( pFile );
   26648   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   26649       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   26650       getpid()));
   26651 
   26652   assert( eFileLock<=SHARED_LOCK );
   26653   if( pFile->eFileLock<=eFileLock ){
   26654     return SQLITE_OK;
   26655   }
   26656   unixEnterMutex();
   26657   pInode = pFile->pInode;
   26658   assert( pInode->nShared!=0 );
   26659   if( pFile->eFileLock>SHARED_LOCK ){
   26660     assert( pInode->eFileLock==pFile->eFileLock );
   26661 
   26662 #ifndef NDEBUG
   26663     /* When reducing a lock such that other processes can start
   26664     ** reading the database file again, make sure that the
   26665     ** transaction counter was updated if any part of the database
   26666     ** file changed.  If the transaction counter is not updated,
   26667     ** other connections to the same file might not realize that
   26668     ** the file has changed and hence might not know to flush their
   26669     ** cache.  The use of a stale cache can lead to database corruption.
   26670     */
   26671     pFile->inNormalWrite = 0;
   26672 #endif
   26673 
   26674     /* downgrading to a shared lock on NFS involves clearing the write lock
   26675     ** before establishing the readlock - to avoid a race condition we downgrade
   26676     ** the lock in 2 blocks, so that part of the range will be covered by a
   26677     ** write lock until the rest is covered by a read lock:
   26678     **  1:   [WWWWW]
   26679     **  2:   [....W]
   26680     **  3:   [RRRRW]
   26681     **  4:   [RRRR.]
   26682     */
   26683     if( eFileLock==SHARED_LOCK ){
   26684 
   26685 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
   26686       (void)handleNFSUnlock;
   26687       assert( handleNFSUnlock==0 );
   26688 #endif
   26689 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26690       if( handleNFSUnlock ){
   26691         int tErrno;               /* Error code from system call errors */
   26692         off_t divSize = SHARED_SIZE - 1;
   26693 
   26694         lock.l_type = F_UNLCK;
   26695         lock.l_whence = SEEK_SET;
   26696         lock.l_start = SHARED_FIRST;
   26697         lock.l_len = divSize;
   26698         if( unixFileLock(pFile, &lock)==(-1) ){
   26699           tErrno = errno;
   26700           rc = SQLITE_IOERR_UNLOCK;
   26701           if( IS_LOCK_ERROR(rc) ){
   26702             pFile->lastErrno = tErrno;
   26703           }
   26704           goto end_unlock;
   26705         }
   26706         lock.l_type = F_RDLCK;
   26707         lock.l_whence = SEEK_SET;
   26708         lock.l_start = SHARED_FIRST;
   26709         lock.l_len = divSize;
   26710         if( unixFileLock(pFile, &lock)==(-1) ){
   26711           tErrno = errno;
   26712           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   26713           if( IS_LOCK_ERROR(rc) ){
   26714             pFile->lastErrno = tErrno;
   26715           }
   26716           goto end_unlock;
   26717         }
   26718         lock.l_type = F_UNLCK;
   26719         lock.l_whence = SEEK_SET;
   26720         lock.l_start = SHARED_FIRST+divSize;
   26721         lock.l_len = SHARED_SIZE-divSize;
   26722         if( unixFileLock(pFile, &lock)==(-1) ){
   26723           tErrno = errno;
   26724           rc = SQLITE_IOERR_UNLOCK;
   26725           if( IS_LOCK_ERROR(rc) ){
   26726             pFile->lastErrno = tErrno;
   26727           }
   26728           goto end_unlock;
   26729         }
   26730       }else
   26731 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   26732       {
   26733         lock.l_type = F_RDLCK;
   26734         lock.l_whence = SEEK_SET;
   26735         lock.l_start = SHARED_FIRST;
   26736         lock.l_len = SHARED_SIZE;
   26737         if( unixFileLock(pFile, &lock) ){
   26738           /* In theory, the call to unixFileLock() cannot fail because another
   26739           ** process is holding an incompatible lock. If it does, this
   26740           ** indicates that the other process is not following the locking
   26741           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
   26742           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
   26743           ** an assert to fail). */
   26744           rc = SQLITE_IOERR_RDLOCK;
   26745           pFile->lastErrno = errno;
   26746           goto end_unlock;
   26747         }
   26748       }
   26749     }
   26750     lock.l_type = F_UNLCK;
   26751     lock.l_whence = SEEK_SET;
   26752     lock.l_start = PENDING_BYTE;
   26753     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   26754     if( unixFileLock(pFile, &lock)==0 ){
   26755       pInode->eFileLock = SHARED_LOCK;
   26756     }else{
   26757       rc = SQLITE_IOERR_UNLOCK;
   26758       pFile->lastErrno = errno;
   26759       goto end_unlock;
   26760     }
   26761   }
   26762   if( eFileLock==NO_LOCK ){
   26763     /* Decrement the shared lock counter.  Release the lock using an
   26764     ** OS call only when all threads in this same process have released
   26765     ** the lock.
   26766     */
   26767     pInode->nShared--;
   26768     if( pInode->nShared==0 ){
   26769       lock.l_type = F_UNLCK;
   26770       lock.l_whence = SEEK_SET;
   26771       lock.l_start = lock.l_len = 0L;
   26772       if( unixFileLock(pFile, &lock)==0 ){
   26773         pInode->eFileLock = NO_LOCK;
   26774       }else{
   26775         rc = SQLITE_IOERR_UNLOCK;
   26776 	pFile->lastErrno = errno;
   26777         pInode->eFileLock = NO_LOCK;
   26778         pFile->eFileLock = NO_LOCK;
   26779       }
   26780     }
   26781 
   26782     /* Decrement the count of locks against this same file.  When the
   26783     ** count reaches zero, close any other file descriptors whose close
   26784     ** was deferred because of outstanding locks.
   26785     */
   26786     pInode->nLock--;
   26787     assert( pInode->nLock>=0 );
   26788     if( pInode->nLock==0 ){
   26789       closePendingFds(pFile);
   26790     }
   26791   }
   26792 
   26793 end_unlock:
   26794   unixLeaveMutex();
   26795   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   26796   return rc;
   26797 }
   26798 
   26799 /*
   26800 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   26801 ** must be either NO_LOCK or SHARED_LOCK.
   26802 **
   26803 ** If the locking level of the file descriptor is already at or below
   26804 ** the requested locking level, this routine is a no-op.
   26805 */
   26806 static int unixUnlock(sqlite3_file *id, int eFileLock){
   26807   return posixUnlock(id, eFileLock, 0);
   26808 }
   26809 
   26810 /*
   26811 ** This function performs the parts of the "close file" operation
   26812 ** common to all locking schemes. It closes the directory and file
   26813 ** handles, if they are valid, and sets all fields of the unixFile
   26814 ** structure to 0.
   26815 **
   26816 ** It is *not* necessary to hold the mutex when this routine is called,
   26817 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   26818 ** vxworksReleaseFileId() routine.
   26819 */
   26820 static int closeUnixFile(sqlite3_file *id){
   26821   unixFile *pFile = (unixFile*)id;
   26822   if( pFile->h>=0 ){
   26823     robust_close(pFile, pFile->h, __LINE__);
   26824     pFile->h = -1;
   26825   }
   26826 #if OS_VXWORKS
   26827   if( pFile->pId ){
   26828     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
   26829       osUnlink(pFile->pId->zCanonicalName);
   26830     }
   26831     vxworksReleaseFileId(pFile->pId);
   26832     pFile->pId = 0;
   26833   }
   26834 #endif
   26835   OSTRACE(("CLOSE   %-3d\n", pFile->h));
   26836   OpenCounter(-1);
   26837   sqlite3_free(pFile->pUnused);
   26838   memset(pFile, 0, sizeof(unixFile));
   26839   return SQLITE_OK;
   26840 }
   26841 
   26842 /*
   26843 ** Close a file.
   26844 */
   26845 static int unixClose(sqlite3_file *id){
   26846   int rc = SQLITE_OK;
   26847   unixFile *pFile = (unixFile *)id;
   26848   unixUnlock(id, NO_LOCK);
   26849   unixEnterMutex();
   26850 
   26851   /* unixFile.pInode is always valid here. Otherwise, a different close
   26852   ** routine (e.g. nolockClose()) would be called instead.
   26853   */
   26854   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
   26855   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
   26856     /* If there are outstanding locks, do not actually close the file just
   26857     ** yet because that would clear those locks.  Instead, add the file
   26858     ** descriptor to pInode->pUnused list.  It will be automatically closed
   26859     ** when the last lock is cleared.
   26860     */
   26861     setPendingFd(pFile);
   26862   }
   26863   releaseInodeInfo(pFile);
   26864   rc = closeUnixFile(id);
   26865   unixLeaveMutex();
   26866   return rc;
   26867 }
   26868 
   26869 /************** End of the posix advisory lock implementation *****************
   26870 ******************************************************************************/
   26871 
   26872 /******************************************************************************
   26873 ****************************** No-op Locking **********************************
   26874 **
   26875 ** Of the various locking implementations available, this is by far the
   26876 ** simplest:  locking is ignored.  No attempt is made to lock the database
   26877 ** file for reading or writing.
   26878 **
   26879 ** This locking mode is appropriate for use on read-only databases
   26880 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   26881 ** also be used if the application employs some external mechanism to
   26882 ** prevent simultaneous access of the same database by two or more
   26883 ** database connections.  But there is a serious risk of database
   26884 ** corruption if this locking mode is used in situations where multiple
   26885 ** database connections are accessing the same database file at the same
   26886 ** time and one or more of those connections are writing.
   26887 */
   26888 
   26889 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   26890   UNUSED_PARAMETER(NotUsed);
   26891   *pResOut = 0;
   26892   return SQLITE_OK;
   26893 }
   26894 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   26895   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26896   return SQLITE_OK;
   26897 }
   26898 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   26899   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   26900   return SQLITE_OK;
   26901 }
   26902 
   26903 /*
   26904 ** Close the file.
   26905 */
   26906 static int nolockClose(sqlite3_file *id) {
   26907   return closeUnixFile(id);
   26908 }
   26909 
   26910 /******************* End of the no-op lock implementation *********************
   26911 ******************************************************************************/
   26912 
   26913 /******************************************************************************
   26914 ************************* Begin dot-file Locking ******************************
   26915 **
   26916 ** The dotfile locking implementation uses the existance of separate lock
   26917 ** files (really a directory) to control access to the database.  This works
   26918 ** on just about every filesystem imaginable.  But there are serious downsides:
   26919 **
   26920 **    (1)  There is zero concurrency.  A single reader blocks all other
   26921 **         connections from reading or writing the database.
   26922 **
   26923 **    (2)  An application crash or power loss can leave stale lock files
   26924 **         sitting around that need to be cleared manually.
   26925 **
   26926 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   26927 ** other locking strategy is available.
   26928 **
   26929 ** Dotfile locking works by creating a subdirectory in the same directory as
   26930 ** the database and with the same name but with a ".lock" extension added.
   26931 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
   26932 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   26933 */
   26934 
   26935 /*
   26936 ** The file suffix added to the data base filename in order to create the
   26937 ** lock directory.
   26938 */
   26939 #define DOTLOCK_SUFFIX ".lock"
   26940 
   26941 /*
   26942 ** This routine checks if there is a RESERVED lock held on the specified
   26943 ** file by this or any other process. If such a lock is held, set *pResOut
   26944 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   26945 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   26946 **
   26947 ** In dotfile locking, either a lock exists or it does not.  So in this
   26948 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   26949 ** is held on the file and false if the file is unlocked.
   26950 */
   26951 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   26952   int rc = SQLITE_OK;
   26953   int reserved = 0;
   26954   unixFile *pFile = (unixFile*)id;
   26955 
   26956   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   26957 
   26958   assert( pFile );
   26959 
   26960   /* Check if a thread in this process holds such a lock */
   26961   if( pFile->eFileLock>SHARED_LOCK ){
   26962     /* Either this connection or some other connection in the same process
   26963     ** holds a lock on the file.  No need to check further. */
   26964     reserved = 1;
   26965   }else{
   26966     /* The lock is held if and only if the lockfile exists */
   26967     const char *zLockFile = (const char*)pFile->lockingContext;
   26968     reserved = osAccess(zLockFile, 0)==0;
   26969   }
   26970   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   26971   *pResOut = reserved;
   26972   return rc;
   26973 }
   26974 
   26975 /*
   26976 ** Lock the file with the lock specified by parameter eFileLock - one
   26977 ** of the following:
   26978 **
   26979 **     (1) SHARED_LOCK
   26980 **     (2) RESERVED_LOCK
   26981 **     (3) PENDING_LOCK
   26982 **     (4) EXCLUSIVE_LOCK
   26983 **
   26984 ** Sometimes when requesting one lock state, additional lock states
   26985 ** are inserted in between.  The locking might fail on one of the later
   26986 ** transitions leaving the lock state different from what it started but
   26987 ** still short of its goal.  The following chart shows the allowed
   26988 ** transitions and the inserted intermediate states:
   26989 **
   26990 **    UNLOCKED -> SHARED
   26991 **    SHARED -> RESERVED
   26992 **    SHARED -> (PENDING) -> EXCLUSIVE
   26993 **    RESERVED -> (PENDING) -> EXCLUSIVE
   26994 **    PENDING -> EXCLUSIVE
   26995 **
   26996 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   26997 ** routine to lower a locking level.
   26998 **
   26999 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   27000 ** But we track the other locking levels internally.
   27001 */
   27002 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   27003   unixFile *pFile = (unixFile*)id;
   27004   char *zLockFile = (char *)pFile->lockingContext;
   27005   int rc = SQLITE_OK;
   27006 
   27007 
   27008   /* If we have any lock, then the lock file already exists.  All we have
   27009   ** to do is adjust our internal record of the lock level.
   27010   */
   27011   if( pFile->eFileLock > NO_LOCK ){
   27012     pFile->eFileLock = eFileLock;
   27013     /* Always update the timestamp on the old file */
   27014 #ifdef HAVE_UTIME
   27015     utime(zLockFile, NULL);
   27016 #else
   27017     utimes(zLockFile, NULL);
   27018 #endif
   27019     return SQLITE_OK;
   27020   }
   27021 
   27022   /* grab an exclusive lock */
   27023   rc = osMkdir(zLockFile, 0777);
   27024   if( rc<0 ){
   27025     /* failed to open/create the lock directory */
   27026     int tErrno = errno;
   27027     if( EEXIST == tErrno ){
   27028       rc = SQLITE_BUSY;
   27029     } else {
   27030       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27031       if( IS_LOCK_ERROR(rc) ){
   27032         pFile->lastErrno = tErrno;
   27033       }
   27034     }
   27035     return rc;
   27036   }
   27037 
   27038   /* got it, set the type and return ok */
   27039   pFile->eFileLock = eFileLock;
   27040   return rc;
   27041 }
   27042 
   27043 /*
   27044 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27045 ** must be either NO_LOCK or SHARED_LOCK.
   27046 **
   27047 ** If the locking level of the file descriptor is already at or below
   27048 ** the requested locking level, this routine is a no-op.
   27049 **
   27050 ** When the locking level reaches NO_LOCK, delete the lock file.
   27051 */
   27052 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   27053   unixFile *pFile = (unixFile*)id;
   27054   char *zLockFile = (char *)pFile->lockingContext;
   27055   int rc;
   27056 
   27057   assert( pFile );
   27058   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   27059 	   pFile->eFileLock, getpid()));
   27060   assert( eFileLock<=SHARED_LOCK );
   27061 
   27062   /* no-op if possible */
   27063   if( pFile->eFileLock==eFileLock ){
   27064     return SQLITE_OK;
   27065   }
   27066 
   27067   /* To downgrade to shared, simply update our internal notion of the
   27068   ** lock state.  No need to mess with the file on disk.
   27069   */
   27070   if( eFileLock==SHARED_LOCK ){
   27071     pFile->eFileLock = SHARED_LOCK;
   27072     return SQLITE_OK;
   27073   }
   27074 
   27075   /* To fully unlock the database, delete the lock file */
   27076   assert( eFileLock==NO_LOCK );
   27077   rc = osRmdir(zLockFile);
   27078   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
   27079   if( rc<0 ){
   27080     int tErrno = errno;
   27081     rc = 0;
   27082     if( ENOENT != tErrno ){
   27083       rc = SQLITE_IOERR_UNLOCK;
   27084     }
   27085     if( IS_LOCK_ERROR(rc) ){
   27086       pFile->lastErrno = tErrno;
   27087     }
   27088     return rc;
   27089   }
   27090   pFile->eFileLock = NO_LOCK;
   27091   return SQLITE_OK;
   27092 }
   27093 
   27094 /*
   27095 ** Close a file.  Make sure the lock has been released before closing.
   27096 */
   27097 static int dotlockClose(sqlite3_file *id) {
   27098   int rc;
   27099   if( id ){
   27100     unixFile *pFile = (unixFile*)id;
   27101     dotlockUnlock(id, NO_LOCK);
   27102     sqlite3_free(pFile->lockingContext);
   27103   }
   27104   rc = closeUnixFile(id);
   27105   return rc;
   27106 }
   27107 /****************** End of the dot-file lock implementation *******************
   27108 ******************************************************************************/
   27109 
   27110 /******************************************************************************
   27111 ************************** Begin flock Locking ********************************
   27112 **
   27113 ** Use the flock() system call to do file locking.
   27114 **
   27115 ** flock() locking is like dot-file locking in that the various
   27116 ** fine-grain locking levels supported by SQLite are collapsed into
   27117 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   27118 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   27119 ** still works when you do this, but concurrency is reduced since
   27120 ** only a single process can be reading the database at a time.
   27121 **
   27122 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   27123 ** compiling for VXWORKS.
   27124 */
   27125 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   27126 
   27127 /*
   27128 ** Retry flock() calls that fail with EINTR
   27129 */
   27130 #ifdef EINTR
   27131 static int robust_flock(int fd, int op){
   27132   int rc;
   27133   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   27134   return rc;
   27135 }
   27136 #else
   27137 # define robust_flock(a,b) flock(a,b)
   27138 #endif
   27139 
   27140 
   27141 /*
   27142 ** This routine checks if there is a RESERVED lock held on the specified
   27143 ** file by this or any other process. If such a lock is held, set *pResOut
   27144 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27145 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27146 */
   27147 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   27148   int rc = SQLITE_OK;
   27149   int reserved = 0;
   27150   unixFile *pFile = (unixFile*)id;
   27151 
   27152   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27153 
   27154   assert( pFile );
   27155 
   27156   /* Check if a thread in this process holds such a lock */
   27157   if( pFile->eFileLock>SHARED_LOCK ){
   27158     reserved = 1;
   27159   }
   27160 
   27161   /* Otherwise see if some other process holds it. */
   27162   if( !reserved ){
   27163     /* attempt to get the lock */
   27164     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   27165     if( !lrc ){
   27166       /* got the lock, unlock it */
   27167       lrc = robust_flock(pFile->h, LOCK_UN);
   27168       if ( lrc ) {
   27169         int tErrno = errno;
   27170         /* unlock failed with an error */
   27171         lrc = SQLITE_IOERR_UNLOCK;
   27172         if( IS_LOCK_ERROR(lrc) ){
   27173           pFile->lastErrno = tErrno;
   27174           rc = lrc;
   27175         }
   27176       }
   27177     } else {
   27178       int tErrno = errno;
   27179       reserved = 1;
   27180       /* someone else might have it reserved */
   27181       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27182       if( IS_LOCK_ERROR(lrc) ){
   27183         pFile->lastErrno = tErrno;
   27184         rc = lrc;
   27185       }
   27186     }
   27187   }
   27188   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   27189 
   27190 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27191   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   27192     rc = SQLITE_OK;
   27193     reserved=1;
   27194   }
   27195 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27196   *pResOut = reserved;
   27197   return rc;
   27198 }
   27199 
   27200 /*
   27201 ** Lock the file with the lock specified by parameter eFileLock - one
   27202 ** of the following:
   27203 **
   27204 **     (1) SHARED_LOCK
   27205 **     (2) RESERVED_LOCK
   27206 **     (3) PENDING_LOCK
   27207 **     (4) EXCLUSIVE_LOCK
   27208 **
   27209 ** Sometimes when requesting one lock state, additional lock states
   27210 ** are inserted in between.  The locking might fail on one of the later
   27211 ** transitions leaving the lock state different from what it started but
   27212 ** still short of its goal.  The following chart shows the allowed
   27213 ** transitions and the inserted intermediate states:
   27214 **
   27215 **    UNLOCKED -> SHARED
   27216 **    SHARED -> RESERVED
   27217 **    SHARED -> (PENDING) -> EXCLUSIVE
   27218 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27219 **    PENDING -> EXCLUSIVE
   27220 **
   27221 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   27222 ** lock states in the sqlite3_file structure, but all locks SHARED or
   27223 ** above are really EXCLUSIVE locks and exclude all other processes from
   27224 ** access the file.
   27225 **
   27226 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27227 ** routine to lower a locking level.
   27228 */
   27229 static int flockLock(sqlite3_file *id, int eFileLock) {
   27230   int rc = SQLITE_OK;
   27231   unixFile *pFile = (unixFile*)id;
   27232 
   27233   assert( pFile );
   27234 
   27235   /* if we already have a lock, it is exclusive.
   27236   ** Just adjust level and punt on outta here. */
   27237   if (pFile->eFileLock > NO_LOCK) {
   27238     pFile->eFileLock = eFileLock;
   27239     return SQLITE_OK;
   27240   }
   27241 
   27242   /* grab an exclusive lock */
   27243 
   27244   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   27245     int tErrno = errno;
   27246     /* didn't get, must be busy */
   27247     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   27248     if( IS_LOCK_ERROR(rc) ){
   27249       pFile->lastErrno = tErrno;
   27250     }
   27251   } else {
   27252     /* got it, set the type and return ok */
   27253     pFile->eFileLock = eFileLock;
   27254   }
   27255   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   27256            rc==SQLITE_OK ? "ok" : "failed"));
   27257 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27258   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   27259     rc = SQLITE_BUSY;
   27260   }
   27261 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27262   return rc;
   27263 }
   27264 
   27265 
   27266 /*
   27267 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27268 ** must be either NO_LOCK or SHARED_LOCK.
   27269 **
   27270 ** If the locking level of the file descriptor is already at or below
   27271 ** the requested locking level, this routine is a no-op.
   27272 */
   27273 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   27274   unixFile *pFile = (unixFile*)id;
   27275 
   27276   assert( pFile );
   27277   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   27278            pFile->eFileLock, getpid()));
   27279   assert( eFileLock<=SHARED_LOCK );
   27280 
   27281   /* no-op if possible */
   27282   if( pFile->eFileLock==eFileLock ){
   27283     return SQLITE_OK;
   27284   }
   27285 
   27286   /* shared can just be set because we always have an exclusive */
   27287   if (eFileLock==SHARED_LOCK) {
   27288     pFile->eFileLock = eFileLock;
   27289     return SQLITE_OK;
   27290   }
   27291 
   27292   /* no, really, unlock. */
   27293   if( robust_flock(pFile->h, LOCK_UN) ){
   27294 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   27295     return SQLITE_OK;
   27296 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   27297     return SQLITE_IOERR_UNLOCK;
   27298   }else{
   27299     pFile->eFileLock = NO_LOCK;
   27300     return SQLITE_OK;
   27301   }
   27302 }
   27303 
   27304 /*
   27305 ** Close a file.
   27306 */
   27307 static int flockClose(sqlite3_file *id) {
   27308   if( id ){
   27309     flockUnlock(id, NO_LOCK);
   27310   }
   27311   return closeUnixFile(id);
   27312 }
   27313 
   27314 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   27315 
   27316 /******************* End of the flock lock implementation *********************
   27317 ******************************************************************************/
   27318 
   27319 /******************************************************************************
   27320 ************************ Begin Named Semaphore Locking ************************
   27321 **
   27322 ** Named semaphore locking is only supported on VxWorks.
   27323 **
   27324 ** Semaphore locking is like dot-lock and flock in that it really only
   27325 ** supports EXCLUSIVE locking.  Only a single process can read or write
   27326 ** the database file at a time.  This reduces potential concurrency, but
   27327 ** makes the lock implementation much easier.
   27328 */
   27329 #if OS_VXWORKS
   27330 
   27331 /*
   27332 ** This routine checks if there is a RESERVED lock held on the specified
   27333 ** file by this or any other process. If such a lock is held, set *pResOut
   27334 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27335 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27336 */
   27337 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   27338   int rc = SQLITE_OK;
   27339   int reserved = 0;
   27340   unixFile *pFile = (unixFile*)id;
   27341 
   27342   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27343 
   27344   assert( pFile );
   27345 
   27346   /* Check if a thread in this process holds such a lock */
   27347   if( pFile->eFileLock>SHARED_LOCK ){
   27348     reserved = 1;
   27349   }
   27350 
   27351   /* Otherwise see if some other process holds it. */
   27352   if( !reserved ){
   27353     sem_t *pSem = pFile->pInode->pSem;
   27354     struct stat statBuf;
   27355 
   27356     if( sem_trywait(pSem)==-1 ){
   27357       int tErrno = errno;
   27358       if( EAGAIN != tErrno ){
   27359         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   27360         pFile->lastErrno = tErrno;
   27361       } else {
   27362         /* someone else has the lock when we are in NO_LOCK */
   27363         reserved = (pFile->eFileLock < SHARED_LOCK);
   27364       }
   27365     }else{
   27366       /* we could have it if we want it */
   27367       sem_post(pSem);
   27368     }
   27369   }
   27370   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   27371 
   27372   *pResOut = reserved;
   27373   return rc;
   27374 }
   27375 
   27376 /*
   27377 ** Lock the file with the lock specified by parameter eFileLock - one
   27378 ** of the following:
   27379 **
   27380 **     (1) SHARED_LOCK
   27381 **     (2) RESERVED_LOCK
   27382 **     (3) PENDING_LOCK
   27383 **     (4) EXCLUSIVE_LOCK
   27384 **
   27385 ** Sometimes when requesting one lock state, additional lock states
   27386 ** are inserted in between.  The locking might fail on one of the later
   27387 ** transitions leaving the lock state different from what it started but
   27388 ** still short of its goal.  The following chart shows the allowed
   27389 ** transitions and the inserted intermediate states:
   27390 **
   27391 **    UNLOCKED -> SHARED
   27392 **    SHARED -> RESERVED
   27393 **    SHARED -> (PENDING) -> EXCLUSIVE
   27394 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27395 **    PENDING -> EXCLUSIVE
   27396 **
   27397 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   27398 ** lock states in the sqlite3_file structure, but all locks SHARED or
   27399 ** above are really EXCLUSIVE locks and exclude all other processes from
   27400 ** access the file.
   27401 **
   27402 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27403 ** routine to lower a locking level.
   27404 */
   27405 static int semLock(sqlite3_file *id, int eFileLock) {
   27406   unixFile *pFile = (unixFile*)id;
   27407   int fd;
   27408   sem_t *pSem = pFile->pInode->pSem;
   27409   int rc = SQLITE_OK;
   27410 
   27411   /* if we already have a lock, it is exclusive.
   27412   ** Just adjust level and punt on outta here. */
   27413   if (pFile->eFileLock > NO_LOCK) {
   27414     pFile->eFileLock = eFileLock;
   27415     rc = SQLITE_OK;
   27416     goto sem_end_lock;
   27417   }
   27418 
   27419   /* lock semaphore now but bail out when already locked. */
   27420   if( sem_trywait(pSem)==-1 ){
   27421     rc = SQLITE_BUSY;
   27422     goto sem_end_lock;
   27423   }
   27424 
   27425   /* got it, set the type and return ok */
   27426   pFile->eFileLock = eFileLock;
   27427 
   27428  sem_end_lock:
   27429   return rc;
   27430 }
   27431 
   27432 /*
   27433 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27434 ** must be either NO_LOCK or SHARED_LOCK.
   27435 **
   27436 ** If the locking level of the file descriptor is already at or below
   27437 ** the requested locking level, this routine is a no-op.
   27438 */
   27439 static int semUnlock(sqlite3_file *id, int eFileLock) {
   27440   unixFile *pFile = (unixFile*)id;
   27441   sem_t *pSem = pFile->pInode->pSem;
   27442 
   27443   assert( pFile );
   27444   assert( pSem );
   27445   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   27446 	   pFile->eFileLock, getpid()));
   27447   assert( eFileLock<=SHARED_LOCK );
   27448 
   27449   /* no-op if possible */
   27450   if( pFile->eFileLock==eFileLock ){
   27451     return SQLITE_OK;
   27452   }
   27453 
   27454   /* shared can just be set because we always have an exclusive */
   27455   if (eFileLock==SHARED_LOCK) {
   27456     pFile->eFileLock = eFileLock;
   27457     return SQLITE_OK;
   27458   }
   27459 
   27460   /* no, really unlock. */
   27461   if ( sem_post(pSem)==-1 ) {
   27462     int rc, tErrno = errno;
   27463     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   27464     if( IS_LOCK_ERROR(rc) ){
   27465       pFile->lastErrno = tErrno;
   27466     }
   27467     return rc;
   27468   }
   27469   pFile->eFileLock = NO_LOCK;
   27470   return SQLITE_OK;
   27471 }
   27472 
   27473 /*
   27474  ** Close a file.
   27475  */
   27476 static int semClose(sqlite3_file *id) {
   27477   if( id ){
   27478     unixFile *pFile = (unixFile*)id;
   27479     semUnlock(id, NO_LOCK);
   27480     assert( pFile );
   27481     unixEnterMutex();
   27482     releaseInodeInfo(pFile);
   27483     unixLeaveMutex();
   27484     closeUnixFile(id);
   27485   }
   27486   return SQLITE_OK;
   27487 }
   27488 
   27489 #endif /* OS_VXWORKS */
   27490 /*
   27491 ** Named semaphore locking is only available on VxWorks.
   27492 **
   27493 *************** End of the named semaphore lock implementation ****************
   27494 ******************************************************************************/
   27495 
   27496 
   27497 /******************************************************************************
   27498 *************************** Begin AFP Locking *********************************
   27499 **
   27500 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   27501 ** on Apple Macintosh computers - both OS9 and OSX.
   27502 **
   27503 ** Third-party implementations of AFP are available.  But this code here
   27504 ** only works on OSX.
   27505 */
   27506 
   27507 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27508 /*
   27509 ** The afpLockingContext structure contains all afp lock specific state
   27510 */
   27511 typedef struct afpLockingContext afpLockingContext;
   27512 struct afpLockingContext {
   27513   int reserved;
   27514   const char *dbPath;             /* Name of the open file */
   27515 };
   27516 
   27517 struct ByteRangeLockPB2
   27518 {
   27519   unsigned long long offset;        /* offset to first byte to lock */
   27520   unsigned long long length;        /* nbr of bytes to lock */
   27521   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   27522   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   27523   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   27524   int fd;                           /* file desc to assoc this lock with */
   27525 };
   27526 
   27527 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   27528 
   27529 /*
   27530 ** This is a utility for setting or clearing a bit-range lock on an
   27531 ** AFP filesystem.
   27532 **
   27533 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   27534 */
   27535 static int afpSetLock(
   27536   const char *path,              /* Name of the file to be locked or unlocked */
   27537   unixFile *pFile,               /* Open file descriptor on path */
   27538   unsigned long long offset,     /* First byte to be locked */
   27539   unsigned long long length,     /* Number of bytes to lock */
   27540   int setLockFlag                /* True to set lock.  False to clear lock */
   27541 ){
   27542   struct ByteRangeLockPB2 pb;
   27543   int err;
   27544 
   27545   pb.unLockFlag = setLockFlag ? 0 : 1;
   27546   pb.startEndFlag = 0;
   27547   pb.offset = offset;
   27548   pb.length = length;
   27549   pb.fd = pFile->h;
   27550 
   27551   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   27552     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   27553     offset, length));
   27554   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   27555   if ( err==-1 ) {
   27556     int rc;
   27557     int tErrno = errno;
   27558     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   27559              path, tErrno, strerror(tErrno)));
   27560 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   27561     rc = SQLITE_BUSY;
   27562 #else
   27563     rc = sqliteErrorFromPosixError(tErrno,
   27564                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   27565 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   27566     if( IS_LOCK_ERROR(rc) ){
   27567       pFile->lastErrno = tErrno;
   27568     }
   27569     return rc;
   27570   } else {
   27571     return SQLITE_OK;
   27572   }
   27573 }
   27574 
   27575 /*
   27576 ** This routine checks if there is a RESERVED lock held on the specified
   27577 ** file by this or any other process. If such a lock is held, set *pResOut
   27578 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   27579 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   27580 */
   27581 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   27582   int rc = SQLITE_OK;
   27583   int reserved = 0;
   27584   unixFile *pFile = (unixFile*)id;
   27585   afpLockingContext *context;
   27586 
   27587   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   27588 
   27589   assert( pFile );
   27590   context = (afpLockingContext *) pFile->lockingContext;
   27591   if( context->reserved ){
   27592     *pResOut = 1;
   27593     return SQLITE_OK;
   27594   }
   27595   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   27596 
   27597   /* Check if a thread in this process holds such a lock */
   27598   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   27599     reserved = 1;
   27600   }
   27601 
   27602   /* Otherwise see if some other process holds it.
   27603    */
   27604   if( !reserved ){
   27605     /* lock the RESERVED byte */
   27606     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27607     if( SQLITE_OK==lrc ){
   27608       /* if we succeeded in taking the reserved lock, unlock it to restore
   27609       ** the original state */
   27610       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27611     } else {
   27612       /* if we failed to get the lock then someone else must have it */
   27613       reserved = 1;
   27614     }
   27615     if( IS_LOCK_ERROR(lrc) ){
   27616       rc=lrc;
   27617     }
   27618   }
   27619 
   27620   unixLeaveMutex();
   27621   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   27622 
   27623   *pResOut = reserved;
   27624   return rc;
   27625 }
   27626 
   27627 /*
   27628 ** Lock the file with the lock specified by parameter eFileLock - one
   27629 ** of the following:
   27630 **
   27631 **     (1) SHARED_LOCK
   27632 **     (2) RESERVED_LOCK
   27633 **     (3) PENDING_LOCK
   27634 **     (4) EXCLUSIVE_LOCK
   27635 **
   27636 ** Sometimes when requesting one lock state, additional lock states
   27637 ** are inserted in between.  The locking might fail on one of the later
   27638 ** transitions leaving the lock state different from what it started but
   27639 ** still short of its goal.  The following chart shows the allowed
   27640 ** transitions and the inserted intermediate states:
   27641 **
   27642 **    UNLOCKED -> SHARED
   27643 **    SHARED -> RESERVED
   27644 **    SHARED -> (PENDING) -> EXCLUSIVE
   27645 **    RESERVED -> (PENDING) -> EXCLUSIVE
   27646 **    PENDING -> EXCLUSIVE
   27647 **
   27648 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   27649 ** routine to lower a locking level.
   27650 */
   27651 static int afpLock(sqlite3_file *id, int eFileLock){
   27652   int rc = SQLITE_OK;
   27653   unixFile *pFile = (unixFile*)id;
   27654   unixInodeInfo *pInode = pFile->pInode;
   27655   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27656 
   27657   assert( pFile );
   27658   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   27659            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   27660            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   27661 
   27662   /* If there is already a lock of this type or more restrictive on the
   27663   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   27664   ** unixEnterMutex() hasn't been called yet.
   27665   */
   27666   if( pFile->eFileLock>=eFileLock ){
   27667     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   27668            azFileLock(eFileLock)));
   27669     return SQLITE_OK;
   27670   }
   27671 
   27672   /* Make sure the locking sequence is correct
   27673   **  (1) We never move from unlocked to anything higher than shared lock.
   27674   **  (2) SQLite never explicitly requests a pendig lock.
   27675   **  (3) A shared lock is always held when a reserve lock is requested.
   27676   */
   27677   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   27678   assert( eFileLock!=PENDING_LOCK );
   27679   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   27680 
   27681   /* This mutex is needed because pFile->pInode is shared across threads
   27682   */
   27683   unixEnterMutex();
   27684   pInode = pFile->pInode;
   27685 
   27686   /* If some thread using this PID has a lock via a different unixFile*
   27687   ** handle that precludes the requested lock, return BUSY.
   27688   */
   27689   if( (pFile->eFileLock!=pInode->eFileLock &&
   27690        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   27691      ){
   27692     rc = SQLITE_BUSY;
   27693     goto afp_end_lock;
   27694   }
   27695 
   27696   /* If a SHARED lock is requested, and some thread using this PID already
   27697   ** has a SHARED or RESERVED lock, then increment reference counts and
   27698   ** return SQLITE_OK.
   27699   */
   27700   if( eFileLock==SHARED_LOCK &&
   27701      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   27702     assert( eFileLock==SHARED_LOCK );
   27703     assert( pFile->eFileLock==0 );
   27704     assert( pInode->nShared>0 );
   27705     pFile->eFileLock = SHARED_LOCK;
   27706     pInode->nShared++;
   27707     pInode->nLock++;
   27708     goto afp_end_lock;
   27709   }
   27710 
   27711   /* A PENDING lock is needed before acquiring a SHARED lock and before
   27712   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   27713   ** be released.
   27714   */
   27715   if( eFileLock==SHARED_LOCK
   27716       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   27717   ){
   27718     int failed;
   27719     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   27720     if (failed) {
   27721       rc = failed;
   27722       goto afp_end_lock;
   27723     }
   27724   }
   27725 
   27726   /* If control gets to this point, then actually go ahead and make
   27727   ** operating system calls for the specified lock.
   27728   */
   27729   if( eFileLock==SHARED_LOCK ){
   27730     int lrc1, lrc2, lrc1Errno = 0;
   27731     long lk, mask;
   27732 
   27733     assert( pInode->nShared==0 );
   27734     assert( pInode->eFileLock==0 );
   27735 
   27736     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   27737     /* Now get the read-lock SHARED_LOCK */
   27738     /* note that the quality of the randomness doesn't matter that much */
   27739     lk = random();
   27740     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   27741     lrc1 = afpSetLock(context->dbPath, pFile,
   27742           SHARED_FIRST+pInode->sharedByte, 1, 1);
   27743     if( IS_LOCK_ERROR(lrc1) ){
   27744       lrc1Errno = pFile->lastErrno;
   27745     }
   27746     /* Drop the temporary PENDING lock */
   27747     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27748 
   27749     if( IS_LOCK_ERROR(lrc1) ) {
   27750       pFile->lastErrno = lrc1Errno;
   27751       rc = lrc1;
   27752       goto afp_end_lock;
   27753     } else if( IS_LOCK_ERROR(lrc2) ){
   27754       rc = lrc2;
   27755       goto afp_end_lock;
   27756     } else if( lrc1 != SQLITE_OK ) {
   27757       rc = lrc1;
   27758     } else {
   27759       pFile->eFileLock = SHARED_LOCK;
   27760       pInode->nLock++;
   27761       pInode->nShared = 1;
   27762     }
   27763   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   27764     /* We are trying for an exclusive lock but another thread in this
   27765      ** same process is still holding a shared lock. */
   27766     rc = SQLITE_BUSY;
   27767   }else{
   27768     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   27769     ** assumed that there is a SHARED or greater lock on the file
   27770     ** already.
   27771     */
   27772     int failed = 0;
   27773     assert( 0!=pFile->eFileLock );
   27774     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   27775         /* Acquire a RESERVED lock */
   27776         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   27777       if( !failed ){
   27778         context->reserved = 1;
   27779       }
   27780     }
   27781     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   27782       /* Acquire an EXCLUSIVE lock */
   27783 
   27784       /* Remove the shared lock before trying the range.  we'll need to
   27785       ** reestablish the shared lock if we can't get the  afpUnlock
   27786       */
   27787       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   27788                          pInode->sharedByte, 1, 0)) ){
   27789         int failed2 = SQLITE_OK;
   27790         /* now attemmpt to get the exclusive lock range */
   27791         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   27792                                SHARED_SIZE, 1);
   27793         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   27794                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   27795           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   27796           ** a critical I/O error
   27797           */
   27798           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   27799                SQLITE_IOERR_LOCK;
   27800           goto afp_end_lock;
   27801         }
   27802       }else{
   27803         rc = failed;
   27804       }
   27805     }
   27806     if( failed ){
   27807       rc = failed;
   27808     }
   27809   }
   27810 
   27811   if( rc==SQLITE_OK ){
   27812     pFile->eFileLock = eFileLock;
   27813     pInode->eFileLock = eFileLock;
   27814   }else if( eFileLock==EXCLUSIVE_LOCK ){
   27815     pFile->eFileLock = PENDING_LOCK;
   27816     pInode->eFileLock = PENDING_LOCK;
   27817   }
   27818 
   27819 afp_end_lock:
   27820   unixLeaveMutex();
   27821   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   27822          rc==SQLITE_OK ? "ok" : "failed"));
   27823   return rc;
   27824 }
   27825 
   27826 /*
   27827 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27828 ** must be either NO_LOCK or SHARED_LOCK.
   27829 **
   27830 ** If the locking level of the file descriptor is already at or below
   27831 ** the requested locking level, this routine is a no-op.
   27832 */
   27833 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   27834   int rc = SQLITE_OK;
   27835   unixFile *pFile = (unixFile*)id;
   27836   unixInodeInfo *pInode;
   27837   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   27838   int skipShared = 0;
   27839 #ifdef SQLITE_TEST
   27840   int h = pFile->h;
   27841 #endif
   27842 
   27843   assert( pFile );
   27844   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   27845            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   27846            getpid()));
   27847 
   27848   assert( eFileLock<=SHARED_LOCK );
   27849   if( pFile->eFileLock<=eFileLock ){
   27850     return SQLITE_OK;
   27851   }
   27852   unixEnterMutex();
   27853   pInode = pFile->pInode;
   27854   assert( pInode->nShared!=0 );
   27855   if( pFile->eFileLock>SHARED_LOCK ){
   27856     assert( pInode->eFileLock==pFile->eFileLock );
   27857     SimulateIOErrorBenign(1);
   27858     SimulateIOError( h=(-1) )
   27859     SimulateIOErrorBenign(0);
   27860 
   27861 #ifndef NDEBUG
   27862     /* When reducing a lock such that other processes can start
   27863     ** reading the database file again, make sure that the
   27864     ** transaction counter was updated if any part of the database
   27865     ** file changed.  If the transaction counter is not updated,
   27866     ** other connections to the same file might not realize that
   27867     ** the file has changed and hence might not know to flush their
   27868     ** cache.  The use of a stale cache can lead to database corruption.
   27869     */
   27870     assert( pFile->inNormalWrite==0
   27871            || pFile->dbUpdate==0
   27872            || pFile->transCntrChng==1 );
   27873     pFile->inNormalWrite = 0;
   27874 #endif
   27875 
   27876     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   27877       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   27878       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   27879         /* only re-establish the shared lock if necessary */
   27880         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27881         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   27882       } else {
   27883         skipShared = 1;
   27884       }
   27885     }
   27886     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   27887       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   27888     }
   27889     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   27890       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   27891       if( !rc ){
   27892         context->reserved = 0;
   27893       }
   27894     }
   27895     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   27896       pInode->eFileLock = SHARED_LOCK;
   27897     }
   27898   }
   27899   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   27900 
   27901     /* Decrement the shared lock counter.  Release the lock using an
   27902     ** OS call only when all threads in this same process have released
   27903     ** the lock.
   27904     */
   27905     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   27906     pInode->nShared--;
   27907     if( pInode->nShared==0 ){
   27908       SimulateIOErrorBenign(1);
   27909       SimulateIOError( h=(-1) )
   27910       SimulateIOErrorBenign(0);
   27911       if( !skipShared ){
   27912         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   27913       }
   27914       if( !rc ){
   27915         pInode->eFileLock = NO_LOCK;
   27916         pFile->eFileLock = NO_LOCK;
   27917       }
   27918     }
   27919     if( rc==SQLITE_OK ){
   27920       pInode->nLock--;
   27921       assert( pInode->nLock>=0 );
   27922       if( pInode->nLock==0 ){
   27923         closePendingFds(pFile);
   27924       }
   27925     }
   27926   }
   27927 
   27928   unixLeaveMutex();
   27929   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   27930   return rc;
   27931 }
   27932 
   27933 /*
   27934 ** Close a file & cleanup AFP specific locking context
   27935 */
   27936 static int afpClose(sqlite3_file *id) {
   27937   int rc = SQLITE_OK;
   27938   if( id ){
   27939     unixFile *pFile = (unixFile*)id;
   27940     afpUnlock(id, NO_LOCK);
   27941     unixEnterMutex();
   27942     if( pFile->pInode && pFile->pInode->nLock ){
   27943       /* If there are outstanding locks, do not actually close the file just
   27944       ** yet because that would clear those locks.  Instead, add the file
   27945       ** descriptor to pInode->aPending.  It will be automatically closed when
   27946       ** the last lock is cleared.
   27947       */
   27948       setPendingFd(pFile);
   27949     }
   27950     releaseInodeInfo(pFile);
   27951     sqlite3_free(pFile->lockingContext);
   27952     rc = closeUnixFile(id);
   27953     unixLeaveMutex();
   27954   }
   27955   return rc;
   27956 }
   27957 
   27958 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27959 /*
   27960 ** The code above is the AFP lock implementation.  The code is specific
   27961 ** to MacOSX and does not work on other unix platforms.  No alternative
   27962 ** is available.  If you don't compile for a mac, then the "unix-afp"
   27963 ** VFS is not available.
   27964 **
   27965 ********************* End of the AFP lock implementation **********************
   27966 ******************************************************************************/
   27967 
   27968 /******************************************************************************
   27969 *************************** Begin NFS Locking ********************************/
   27970 
   27971 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27972 /*
   27973  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   27974  ** must be either NO_LOCK or SHARED_LOCK.
   27975  **
   27976  ** If the locking level of the file descriptor is already at or below
   27977  ** the requested locking level, this routine is a no-op.
   27978  */
   27979 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   27980   return posixUnlock(id, eFileLock, 1);
   27981 }
   27982 
   27983 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27984 /*
   27985 ** The code above is the NFS lock implementation.  The code is specific
   27986 ** to MacOSX and does not work on other unix platforms.  No alternative
   27987 ** is available.
   27988 **
   27989 ********************* End of the NFS lock implementation **********************
   27990 ******************************************************************************/
   27991 
   27992 /******************************************************************************
   27993 **************** Non-locking sqlite3_file methods *****************************
   27994 **
   27995 ** The next division contains implementations for all methods of the
   27996 ** sqlite3_file object other than the locking methods.  The locking
   27997 ** methods were defined in divisions above (one locking method per
   27998 ** division).  Those methods that are common to all locking modes
   27999 ** are gather together into this division.
   28000 */
   28001 
   28002 /*
   28003 ** Seek to the offset passed as the second argument, then read cnt
   28004 ** bytes into pBuf. Return the number of bytes actually read.
   28005 **
   28006 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   28007 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   28008 ** one system to another.  Since SQLite does not define USE_PREAD
   28009 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   28010 ** See tickets #2741 and #2681.
   28011 **
   28012 ** To avoid stomping the errno value on a failed read the lastErrno value
   28013 ** is set before returning.
   28014 */
   28015 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   28016   int got;
   28017   int prior = 0;
   28018 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   28019   i64 newOffset;
   28020 #endif
   28021   TIMER_START;
   28022   do{
   28023 #if defined(USE_PREAD)
   28024     got = osPread(id->h, pBuf, cnt, offset);
   28025     SimulateIOError( got = -1 );
   28026 #elif defined(USE_PREAD64)
   28027     got = osPread64(id->h, pBuf, cnt, offset);
   28028     SimulateIOError( got = -1 );
   28029 #else
   28030     newOffset = lseek(id->h, offset, SEEK_SET);
   28031     SimulateIOError( newOffset-- );
   28032     if( newOffset!=offset ){
   28033       if( newOffset == -1 ){
   28034         ((unixFile*)id)->lastErrno = errno;
   28035       }else{
   28036         ((unixFile*)id)->lastErrno = 0;
   28037       }
   28038       return -1;
   28039     }
   28040     got = osRead(id->h, pBuf, cnt);
   28041 #endif
   28042     if( got==cnt ) break;
   28043     if( got<0 ){
   28044       if( errno==EINTR ){ got = 1; continue; }
   28045       prior = 0;
   28046       ((unixFile*)id)->lastErrno = errno;
   28047       break;
   28048     }else if( got>0 ){
   28049       cnt -= got;
   28050       offset += got;
   28051       prior += got;
   28052       pBuf = (void*)(got + (char*)pBuf);
   28053     }
   28054   }while( got>0 );
   28055   TIMER_END;
   28056   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
   28057             id->h, got+prior, offset-prior, TIMER_ELAPSED));
   28058   return got+prior;
   28059 }
   28060 
   28061 /*
   28062 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   28063 ** bytes were read successfully and SQLITE_IOERR if anything goes
   28064 ** wrong.
   28065 */
   28066 static int unixRead(
   28067   sqlite3_file *id,
   28068   void *pBuf,
   28069   int amt,
   28070   sqlite3_int64 offset
   28071 ){
   28072   unixFile *pFile = (unixFile *)id;
   28073   int got;
   28074   assert( id );
   28075 
   28076   /* If this is a database file (not a journal, master-journal or temp
   28077   ** file), the bytes in the locking range should never be read or written. */
   28078 #if 0
   28079   assert( pFile->pUnused==0
   28080        || offset>=PENDING_BYTE+512
   28081        || offset+amt<=PENDING_BYTE
   28082   );
   28083 #endif
   28084 
   28085   got = seekAndRead(pFile, offset, pBuf, amt);
   28086   if( got==amt ){
   28087     return SQLITE_OK;
   28088   }else if( got<0 ){
   28089     /* lastErrno set by seekAndRead */
   28090     return SQLITE_IOERR_READ;
   28091   }else{
   28092     pFile->lastErrno = 0; /* not a system error */
   28093     /* Unread parts of the buffer must be zero-filled */
   28094     memset(&((char*)pBuf)[got], 0, amt-got);
   28095     return SQLITE_IOERR_SHORT_READ;
   28096   }
   28097 }
   28098 
   28099 /*
   28100 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   28101 ** Return the number of bytes actually read.  Update the offset.
   28102 **
   28103 ** To avoid stomping the errno value on a failed write the lastErrno value
   28104 ** is set before returning.
   28105 */
   28106 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   28107   int got;
   28108 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   28109   i64 newOffset;
   28110 #endif
   28111   TIMER_START;
   28112 #if defined(USE_PREAD)
   28113   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   28114 #elif defined(USE_PREAD64)
   28115   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
   28116 #else
   28117   do{
   28118     newOffset = lseek(id->h, offset, SEEK_SET);
   28119     SimulateIOError( newOffset-- );
   28120     if( newOffset!=offset ){
   28121       if( newOffset == -1 ){
   28122         ((unixFile*)id)->lastErrno = errno;
   28123       }else{
   28124         ((unixFile*)id)->lastErrno = 0;
   28125       }
   28126       return -1;
   28127     }
   28128     got = osWrite(id->h, pBuf, cnt);
   28129   }while( got<0 && errno==EINTR );
   28130 #endif
   28131   TIMER_END;
   28132   if( got<0 ){
   28133     ((unixFile*)id)->lastErrno = errno;
   28134   }
   28135 
   28136   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   28137   return got;
   28138 }
   28139 
   28140 
   28141 /*
   28142 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   28143 ** or some other error code on failure.
   28144 */
   28145 static int unixWrite(
   28146   sqlite3_file *id,
   28147   const void *pBuf,
   28148   int amt,
   28149   sqlite3_int64 offset
   28150 ){
   28151   unixFile *pFile = (unixFile*)id;
   28152   int wrote = 0;
   28153   assert( id );
   28154   assert( amt>0 );
   28155 
   28156   /* If this is a database file (not a journal, master-journal or temp
   28157   ** file), the bytes in the locking range should never be read or written. */
   28158 #if 0
   28159   assert( pFile->pUnused==0
   28160        || offset>=PENDING_BYTE+512
   28161        || offset+amt<=PENDING_BYTE
   28162   );
   28163 #endif
   28164 
   28165 #ifndef NDEBUG
   28166   /* If we are doing a normal write to a database file (as opposed to
   28167   ** doing a hot-journal rollback or a write to some file other than a
   28168   ** normal database file) then record the fact that the database
   28169   ** has changed.  If the transaction counter is modified, record that
   28170   ** fact too.
   28171   */
   28172   if( pFile->inNormalWrite ){
   28173     pFile->dbUpdate = 1;  /* The database has been modified */
   28174     if( offset<=24 && offset+amt>=27 ){
   28175       int rc;
   28176       char oldCntr[4];
   28177       SimulateIOErrorBenign(1);
   28178       rc = seekAndRead(pFile, 24, oldCntr, 4);
   28179       SimulateIOErrorBenign(0);
   28180       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   28181         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   28182       }
   28183     }
   28184   }
   28185 #endif
   28186 
   28187   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   28188     amt -= wrote;
   28189     offset += wrote;
   28190     pBuf = &((char*)pBuf)[wrote];
   28191   }
   28192   SimulateIOError(( wrote=(-1), amt=1 ));
   28193   SimulateDiskfullError(( wrote=0, amt=1 ));
   28194 
   28195   if( amt>0 ){
   28196     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
   28197       /* lastErrno set by seekAndWrite */
   28198       return SQLITE_IOERR_WRITE;
   28199     }else{
   28200       pFile->lastErrno = 0; /* not a system error */
   28201       return SQLITE_FULL;
   28202     }
   28203   }
   28204 
   28205   return SQLITE_OK;
   28206 }
   28207 
   28208 #ifdef SQLITE_TEST
   28209 /*
   28210 ** Count the number of fullsyncs and normal syncs.  This is used to test
   28211 ** that syncs and fullsyncs are occurring at the right times.
   28212 */
   28213 SQLITE_API int sqlite3_sync_count = 0;
   28214 SQLITE_API int sqlite3_fullsync_count = 0;
   28215 #endif
   28216 
   28217 /*
   28218 ** We do not trust systems to provide a working fdatasync().  Some do.
   28219 ** Others do no.  To be safe, we will stick with the (slightly slower)
   28220 ** fsync(). If you know that your system does support fdatasync() correctly,
   28221 ** then simply compile with -Dfdatasync=fdatasync
   28222 */
   28223 #if !defined(fdatasync)
   28224 # define fdatasync fsync
   28225 #endif
   28226 
   28227 /*
   28228 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   28229 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   28230 ** only available on Mac OS X.  But that could change.
   28231 */
   28232 #ifdef F_FULLFSYNC
   28233 # define HAVE_FULLFSYNC 1
   28234 #else
   28235 # define HAVE_FULLFSYNC 0
   28236 #endif
   28237 
   28238 
   28239 /*
   28240 ** The fsync() system call does not work as advertised on many
   28241 ** unix systems.  The following procedure is an attempt to make
   28242 ** it work better.
   28243 **
   28244 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   28245 ** for testing when we want to run through the test suite quickly.
   28246 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   28247 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   28248 ** or power failure will likely corrupt the database file.
   28249 **
   28250 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   28251 ** The idea behind dataOnly is that it should only write the file content
   28252 ** to disk, not the inode.  We only set dataOnly if the file size is
   28253 ** unchanged since the file size is part of the inode.  However,
   28254 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   28255 ** file size has changed.  The only real difference between fdatasync()
   28256 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   28257 ** inode if the mtime or owner or other inode attributes have changed.
   28258 ** We only care about the file size, not the other file attributes, so
   28259 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   28260 ** So, we always use fdatasync() if it is available, regardless of
   28261 ** the value of the dataOnly flag.
   28262 */
   28263 static int full_fsync(int fd, int fullSync, int dataOnly){
   28264   int rc;
   28265 
   28266   /* The following "ifdef/elif/else/" block has the same structure as
   28267   ** the one below. It is replicated here solely to avoid cluttering
   28268   ** up the real code with the UNUSED_PARAMETER() macros.
   28269   */
   28270 #ifdef SQLITE_NO_SYNC
   28271   UNUSED_PARAMETER(fd);
   28272   UNUSED_PARAMETER(fullSync);
   28273   UNUSED_PARAMETER(dataOnly);
   28274 #elif HAVE_FULLFSYNC
   28275   UNUSED_PARAMETER(dataOnly);
   28276 #else
   28277   UNUSED_PARAMETER(fullSync);
   28278   UNUSED_PARAMETER(dataOnly);
   28279 #endif
   28280 
   28281   /* Record the number of times that we do a normal fsync() and
   28282   ** FULLSYNC.  This is used during testing to verify that this procedure
   28283   ** gets called with the correct arguments.
   28284   */
   28285 #ifdef SQLITE_TEST
   28286   if( fullSync ) sqlite3_fullsync_count++;
   28287   sqlite3_sync_count++;
   28288 #endif
   28289 
   28290   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   28291   ** no-op
   28292   */
   28293 #ifdef SQLITE_NO_SYNC
   28294   rc = SQLITE_OK;
   28295 #elif HAVE_FULLFSYNC
   28296   if( fullSync ){
   28297     rc = osFcntl(fd, F_FULLFSYNC, 0);
   28298   }else{
   28299     rc = 1;
   28300   }
   28301   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   28302   ** It shouldn't be possible for fullfsync to fail on the local
   28303   ** file system (on OSX), so failure indicates that FULLFSYNC
   28304   ** isn't supported for this file system. So, attempt an fsync
   28305   ** and (for now) ignore the overhead of a superfluous fcntl call.
   28306   ** It'd be better to detect fullfsync support once and avoid
   28307   ** the fcntl call every time sync is called.
   28308   */
   28309   if( rc ) rc = fsync(fd);
   28310 
   28311 #elif defined(__APPLE__)
   28312   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   28313   ** so currently we default to the macro that redefines fdatasync to fsync
   28314   */
   28315   rc = fsync(fd);
   28316 #else
   28317   rc = fdatasync(fd);
   28318 #if OS_VXWORKS
   28319   if( rc==-1 && errno==ENOTSUP ){
   28320     rc = fsync(fd);
   28321   }
   28322 #endif /* OS_VXWORKS */
   28323 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   28324 
   28325   if( OS_VXWORKS && rc!= -1 ){
   28326     rc = 0;
   28327   }
   28328   return rc;
   28329 }
   28330 
   28331 /*
   28332 ** Open a file descriptor to the directory containing file zFilename.
   28333 ** If successful, *pFd is set to the opened file descriptor and
   28334 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   28335 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   28336 ** value.
   28337 **
   28338 ** The directory file descriptor is used for only one thing - to
   28339 ** fsync() a directory to make sure file creation and deletion events
   28340 ** are flushed to disk.  Such fsyncs are not needed on newer
   28341 ** journaling filesystems, but are required on older filesystems.
   28342 **
   28343 ** This routine can be overridden using the xSetSysCall interface.
   28344 ** The ability to override this routine was added in support of the
   28345 ** chromium sandbox.  Opening a directory is a security risk (we are
   28346 ** told) so making it overrideable allows the chromium sandbox to
   28347 ** replace this routine with a harmless no-op.  To make this routine
   28348 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
   28349 ** *pFd set to a negative number.
   28350 **
   28351 ** If SQLITE_OK is returned, the caller is responsible for closing
   28352 ** the file descriptor *pFd using close().
   28353 */
   28354 static int openDirectory(const char *zFilename, int *pFd){
   28355   int ii;
   28356   int fd = -1;
   28357   char zDirname[MAX_PATHNAME+1];
   28358 
   28359   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   28360   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   28361   if( ii>0 ){
   28362     zDirname[ii] = '\0';
   28363     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
   28364     if( fd>=0 ){
   28365 #ifdef FD_CLOEXEC
   28366       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   28367 #endif
   28368       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   28369     }
   28370   }
   28371   *pFd = fd;
   28372   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   28373 }
   28374 
   28375 /*
   28376 ** Make sure all writes to a particular file are committed to disk.
   28377 **
   28378 ** If dataOnly==0 then both the file itself and its metadata (file
   28379 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   28380 ** file data is synced.
   28381 **
   28382 ** Under Unix, also make sure that the directory entry for the file
   28383 ** has been created by fsync-ing the directory that contains the file.
   28384 ** If we do not do this and we encounter a power failure, the directory
   28385 ** entry for the journal might not exist after we reboot.  The next
   28386 ** SQLite to access the file will not know that the journal exists (because
   28387 ** the directory entry for the journal was never created) and the transaction
   28388 ** will not roll back - possibly leading to database corruption.
   28389 */
   28390 static int unixSync(sqlite3_file *id, int flags){
   28391   int rc;
   28392   unixFile *pFile = (unixFile*)id;
   28393 
   28394   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   28395   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   28396 
   28397   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   28398   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   28399       || (flags&0x0F)==SQLITE_SYNC_FULL
   28400   );
   28401 
   28402   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   28403   ** line is to test that doing so does not cause any problems.
   28404   */
   28405   SimulateDiskfullError( return SQLITE_FULL );
   28406 
   28407   assert( pFile );
   28408   OSTRACE(("SYNC    %-3d\n", pFile->h));
   28409   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   28410   SimulateIOError( rc=1 );
   28411   if( rc ){
   28412     pFile->lastErrno = errno;
   28413     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   28414   }
   28415 
   28416   /* Also fsync the directory containing the file if the DIRSYNC flag
   28417   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
   28418   ** are unable to fsync a directory, so ignore errors on the fsync.
   28419   */
   28420   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
   28421     int dirfd;
   28422     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
   28423             HAVE_FULLFSYNC, isFullsync));
   28424     rc = osOpenDirectory(pFile->zPath, &dirfd);
   28425     if( rc==SQLITE_OK && dirfd>=0 ){
   28426       full_fsync(dirfd, 0, 0);
   28427       robust_close(pFile, dirfd, __LINE__);
   28428     }else if( rc==SQLITE_CANTOPEN ){
   28429       rc = SQLITE_OK;
   28430     }
   28431     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
   28432   }
   28433   return rc;
   28434 }
   28435 
   28436 /*
   28437 ** Truncate an open file to a specified size
   28438 */
   28439 static int unixTruncate(sqlite3_file *id, i64 nByte){
   28440   unixFile *pFile = (unixFile *)id;
   28441   int rc;
   28442   assert( pFile );
   28443   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   28444 
   28445   /* If the user has configured a chunk-size for this file, truncate the
   28446   ** file so that it consists of an integer number of chunks (i.e. the
   28447   ** actual file size after the operation may be larger than the requested
   28448   ** size).
   28449   */
   28450   if( pFile->szChunk ){
   28451     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   28452   }
   28453 
   28454   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   28455   if( rc ){
   28456     pFile->lastErrno = errno;
   28457     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   28458   }else{
   28459 #ifndef NDEBUG
   28460     /* If we are doing a normal write to a database file (as opposed to
   28461     ** doing a hot-journal rollback or a write to some file other than a
   28462     ** normal database file) and we truncate the file to zero length,
   28463     ** that effectively updates the change counter.  This might happen
   28464     ** when restoring a database using the backup API from a zero-length
   28465     ** source.
   28466     */
   28467     if( pFile->inNormalWrite && nByte==0 ){
   28468       pFile->transCntrChng = 1;
   28469     }
   28470 #endif
   28471 
   28472     return SQLITE_OK;
   28473   }
   28474 }
   28475 
   28476 /*
   28477 ** Determine the current size of a file in bytes
   28478 */
   28479 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   28480   int rc;
   28481   struct stat buf;
   28482   assert( id );
   28483   rc = osFstat(((unixFile*)id)->h, &buf);
   28484   SimulateIOError( rc=1 );
   28485   if( rc!=0 ){
   28486     ((unixFile*)id)->lastErrno = errno;
   28487     return SQLITE_IOERR_FSTAT;
   28488   }
   28489   *pSize = buf.st_size;
   28490 
   28491   /* When opening a zero-size database, the findInodeInfo() procedure
   28492   ** writes a single byte into that file in order to work around a bug
   28493   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   28494   ** layers, we need to report this file size as zero even though it is
   28495   ** really 1.   Ticket #3260.
   28496   */
   28497   if( *pSize==1 ) *pSize = 0;
   28498 
   28499 
   28500   return SQLITE_OK;
   28501 }
   28502 
   28503 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28504 /*
   28505 ** Handler for proxy-locking file-control verbs.  Defined below in the
   28506 ** proxying locking division.
   28507 */
   28508 static int proxyFileControl(sqlite3_file*,int,void*);
   28509 #endif
   28510 
   28511 /*
   28512 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   28513 ** file-control operation.  Enlarge the database to nBytes in size
   28514 ** (rounded up to the next chunk-size).  If the database is already
   28515 ** nBytes or larger, this routine is a no-op.
   28516 */
   28517 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   28518   if( pFile->szChunk>0 ){
   28519     i64 nSize;                    /* Required file size */
   28520     struct stat buf;              /* Used to hold return values of fstat() */
   28521 
   28522     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
   28523 
   28524     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   28525     if( nSize>(i64)buf.st_size ){
   28526 
   28527 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   28528       /* The code below is handling the return value of osFallocate()
   28529       ** correctly. posix_fallocate() is defined to "returns zero on success,
   28530       ** or an error number on  failure". See the manpage for details. */
   28531       int err;
   28532       do{
   28533         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
   28534       }while( err==EINTR );
   28535       if( err ) return SQLITE_IOERR_WRITE;
   28536 #else
   28537       /* If the OS does not have posix_fallocate(), fake it. First use
   28538       ** ftruncate() to set the file size, then write a single byte to
   28539       ** the last byte in each block within the extended region. This
   28540       ** is the same technique used by glibc to implement posix_fallocate()
   28541       ** on systems that do not have a real fallocate() system call.
   28542       */
   28543       int nBlk = buf.st_blksize;  /* File-system block size */
   28544       i64 iWrite;                 /* Next offset to write to */
   28545 
   28546       if( robust_ftruncate(pFile->h, nSize) ){
   28547         pFile->lastErrno = errno;
   28548         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   28549       }
   28550       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   28551       while( iWrite<nSize ){
   28552         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
   28553         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   28554         iWrite += nBlk;
   28555       }
   28556 #endif
   28557     }
   28558   }
   28559 
   28560   return SQLITE_OK;
   28561 }
   28562 
   28563 /*
   28564 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   28565 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   28566 **
   28567 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   28568 */
   28569 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
   28570   if( *pArg<0 ){
   28571     *pArg = (pFile->ctrlFlags & mask)!=0;
   28572   }else if( (*pArg)==0 ){
   28573     pFile->ctrlFlags &= ~mask;
   28574   }else{
   28575     pFile->ctrlFlags |= mask;
   28576   }
   28577 }
   28578 
   28579 /*
   28580 ** Information and control of an open file handle.
   28581 */
   28582 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   28583   unixFile *pFile = (unixFile*)id;
   28584   switch( op ){
   28585     case SQLITE_FCNTL_LOCKSTATE: {
   28586       *(int*)pArg = pFile->eFileLock;
   28587       return SQLITE_OK;
   28588     }
   28589     case SQLITE_LAST_ERRNO: {
   28590       *(int*)pArg = pFile->lastErrno;
   28591       return SQLITE_OK;
   28592     }
   28593     case SQLITE_FCNTL_CHUNK_SIZE: {
   28594       pFile->szChunk = *(int *)pArg;
   28595       return SQLITE_OK;
   28596     }
   28597     case SQLITE_FCNTL_SIZE_HINT: {
   28598       int rc;
   28599       SimulateIOErrorBenign(1);
   28600       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
   28601       SimulateIOErrorBenign(0);
   28602       return rc;
   28603     }
   28604     case SQLITE_FCNTL_PERSIST_WAL: {
   28605       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
   28606       return SQLITE_OK;
   28607     }
   28608     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   28609       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
   28610       return SQLITE_OK;
   28611     }
   28612     case SQLITE_FCNTL_VFSNAME: {
   28613       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
   28614       return SQLITE_OK;
   28615     }
   28616 #ifndef NDEBUG
   28617     /* The pager calls this method to signal that it has done
   28618     ** a rollback and that the database is therefore unchanged and
   28619     ** it hence it is OK for the transaction change counter to be
   28620     ** unchanged.
   28621     */
   28622     case SQLITE_FCNTL_DB_UNCHANGED: {
   28623       ((unixFile*)id)->dbUpdate = 0;
   28624       return SQLITE_OK;
   28625     }
   28626 #endif
   28627 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   28628     case SQLITE_SET_LOCKPROXYFILE:
   28629     case SQLITE_GET_LOCKPROXYFILE: {
   28630       return proxyFileControl(id,op,pArg);
   28631     }
   28632 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   28633   }
   28634   return SQLITE_NOTFOUND;
   28635 }
   28636 
   28637 /*
   28638 ** Return the sector size in bytes of the underlying block device for
   28639 ** the specified file. This is almost always 512 bytes, but may be
   28640 ** larger for some devices.
   28641 **
   28642 ** SQLite code assumes this function cannot fail. It also assumes that
   28643 ** if two files are created in the same file-system directory (i.e.
   28644 ** a database and its journal file) that the sector size will be the
   28645 ** same for both.
   28646 */
   28647 static int unixSectorSize(sqlite3_file *pFile){
   28648   (void)pFile;
   28649   return SQLITE_DEFAULT_SECTOR_SIZE;
   28650 }
   28651 
   28652 /*
   28653 ** Return the device characteristics for the file.
   28654 **
   28655 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
   28656 ** However, that choice is contraversial since technically the underlying
   28657 ** file system does not always provide powersafe overwrites.  (In other
   28658 ** words, after a power-loss event, parts of the file that were never
   28659 ** written might end up being altered.)  However, non-PSOW behavior is very,
   28660 ** very rare.  And asserting PSOW makes a large reduction in the amount
   28661 ** of required I/O for journaling, since a lot of padding is eliminated.
   28662 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
   28663 ** available to turn it off and URI query parameter available to turn it off.
   28664 */
   28665 static int unixDeviceCharacteristics(sqlite3_file *id){
   28666   unixFile *p = (unixFile*)id;
   28667   if( p->ctrlFlags & UNIXFILE_PSOW ){
   28668     return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
   28669   }else{
   28670     return 0;
   28671   }
   28672 }
   28673 
   28674 #ifndef SQLITE_OMIT_WAL
   28675 
   28676 
   28677 /*
   28678 ** Object used to represent an shared memory buffer.
   28679 **
   28680 ** When multiple threads all reference the same wal-index, each thread
   28681 ** has its own unixShm object, but they all point to a single instance
   28682 ** of this unixShmNode object.  In other words, each wal-index is opened
   28683 ** only once per process.
   28684 **
   28685 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   28686 ** We could coalesce this object into unixInodeInfo, but that would mean
   28687 ** every open file that does not use shared memory (in other words, most
   28688 ** open files) would have to carry around this extra information.  So
   28689 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   28690 ** and the unixShmNode object is created only when needed.
   28691 **
   28692 ** unixMutexHeld() must be true when creating or destroying
   28693 ** this object or while reading or writing the following fields:
   28694 **
   28695 **      nRef
   28696 **
   28697 ** The following fields are read-only after the object is created:
   28698 **
   28699 **      fid
   28700 **      zFilename
   28701 **
   28702 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   28703 ** unixMutexHeld() is true when reading or writing any other field
   28704 ** in this structure.
   28705 */
   28706 struct unixShmNode {
   28707   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   28708   sqlite3_mutex *mutex;      /* Mutex to access this object */
   28709   char *zFilename;           /* Name of the mmapped file */
   28710   int h;                     /* Open file descriptor */
   28711   int szRegion;              /* Size of shared-memory regions */
   28712   u16 nRegion;               /* Size of array apRegion */
   28713   u8 isReadonly;             /* True if read-only */
   28714   char **apRegion;           /* Array of mapped shared-memory regions */
   28715   int nRef;                  /* Number of unixShm objects pointing to this */
   28716   unixShm *pFirst;           /* All unixShm objects pointing to this */
   28717 #ifdef SQLITE_DEBUG
   28718   u8 exclMask;               /* Mask of exclusive locks held */
   28719   u8 sharedMask;             /* Mask of shared locks held */
   28720   u8 nextShmId;              /* Next available unixShm.id value */
   28721 #endif
   28722 };
   28723 
   28724 /*
   28725 ** Structure used internally by this VFS to record the state of an
   28726 ** open shared memory connection.
   28727 **
   28728 ** The following fields are initialized when this object is created and
   28729 ** are read-only thereafter:
   28730 **
   28731 **    unixShm.pFile
   28732 **    unixShm.id
   28733 **
   28734 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   28735 ** while accessing any read/write fields.
   28736 */
   28737 struct unixShm {
   28738   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   28739   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   28740   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   28741   u8 id;                     /* Id of this connection within its unixShmNode */
   28742   u16 sharedMask;            /* Mask of shared locks held */
   28743   u16 exclMask;              /* Mask of exclusive locks held */
   28744 };
   28745 
   28746 /*
   28747 ** Constants used for locking
   28748 */
   28749 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   28750 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   28751 
   28752 /*
   28753 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   28754 **
   28755 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   28756 ** otherwise.
   28757 */
   28758 static int unixShmSystemLock(
   28759   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   28760   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   28761   int ofst,              /* First byte of the locking range */
   28762   int n                  /* Number of bytes to lock */
   28763 ){
   28764   struct flock f;       /* The posix advisory locking structure */
   28765   int rc = SQLITE_OK;   /* Result code form fcntl() */
   28766 
   28767   /* Access to the unixShmNode object is serialized by the caller */
   28768   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   28769 
   28770   /* Shared locks never span more than one byte */
   28771   assert( n==1 || lockType!=F_RDLCK );
   28772 
   28773   /* Locks are within range */
   28774   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   28775 
   28776   if( pShmNode->h>=0 ){
   28777     /* Initialize the locking parameters */
   28778     memset(&f, 0, sizeof(f));
   28779     f.l_type = lockType;
   28780     f.l_whence = SEEK_SET;
   28781     f.l_start = ofst;
   28782     f.l_len = n;
   28783 
   28784     rc = osFcntl(pShmNode->h, F_SETLK, &f);
   28785     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   28786   }
   28787 
   28788   /* Update the global lock state and do debug tracing */
   28789 #ifdef SQLITE_DEBUG
   28790   { u16 mask;
   28791   OSTRACE(("SHM-LOCK "));
   28792   mask = (1<<(ofst+n)) - (1<<ofst);
   28793   if( rc==SQLITE_OK ){
   28794     if( lockType==F_UNLCK ){
   28795       OSTRACE(("unlock %d ok", ofst));
   28796       pShmNode->exclMask &= ~mask;
   28797       pShmNode->sharedMask &= ~mask;
   28798     }else if( lockType==F_RDLCK ){
   28799       OSTRACE(("read-lock %d ok", ofst));
   28800       pShmNode->exclMask &= ~mask;
   28801       pShmNode->sharedMask |= mask;
   28802     }else{
   28803       assert( lockType==F_WRLCK );
   28804       OSTRACE(("write-lock %d ok", ofst));
   28805       pShmNode->exclMask |= mask;
   28806       pShmNode->sharedMask &= ~mask;
   28807     }
   28808   }else{
   28809     if( lockType==F_UNLCK ){
   28810       OSTRACE(("unlock %d failed", ofst));
   28811     }else if( lockType==F_RDLCK ){
   28812       OSTRACE(("read-lock failed"));
   28813     }else{
   28814       assert( lockType==F_WRLCK );
   28815       OSTRACE(("write-lock %d failed", ofst));
   28816     }
   28817   }
   28818   OSTRACE((" - afterwards %03x,%03x\n",
   28819            pShmNode->sharedMask, pShmNode->exclMask));
   28820   }
   28821 #endif
   28822 
   28823   return rc;
   28824 }
   28825 
   28826 
   28827 /*
   28828 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   28829 **
   28830 ** This is not a VFS shared-memory method; it is a utility function called
   28831 ** by VFS shared-memory methods.
   28832 */
   28833 static void unixShmPurge(unixFile *pFd){
   28834   unixShmNode *p = pFd->pInode->pShmNode;
   28835   assert( unixMutexHeld() );
   28836   if( p && p->nRef==0 ){
   28837     int i;
   28838     assert( p->pInode==pFd->pInode );
   28839     sqlite3_mutex_free(p->mutex);
   28840     for(i=0; i<p->nRegion; i++){
   28841       if( p->h>=0 ){
   28842         munmap(p->apRegion[i], p->szRegion);
   28843       }else{
   28844         sqlite3_free(p->apRegion[i]);
   28845       }
   28846     }
   28847     sqlite3_free(p->apRegion);
   28848     if( p->h>=0 ){
   28849       robust_close(pFd, p->h, __LINE__);
   28850       p->h = -1;
   28851     }
   28852     p->pInode->pShmNode = 0;
   28853     sqlite3_free(p);
   28854   }
   28855 }
   28856 
   28857 /*
   28858 ** Open a shared-memory area associated with open database file pDbFd.
   28859 ** This particular implementation uses mmapped files.
   28860 **
   28861 ** The file used to implement shared-memory is in the same directory
   28862 ** as the open database file and has the same name as the open database
   28863 ** file with the "-shm" suffix added.  For example, if the database file
   28864 ** is "/home/user1/config.db" then the file that is created and mmapped
   28865 ** for shared memory will be called "/home/user1/config.db-shm".
   28866 **
   28867 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   28868 ** some other tmpfs mount. But if a file in a different directory
   28869 ** from the database file is used, then differing access permissions
   28870 ** or a chroot() might cause two different processes on the same
   28871 ** database to end up using different files for shared memory -
   28872 ** meaning that their memory would not really be shared - resulting
   28873 ** in database corruption.  Nevertheless, this tmpfs file usage
   28874 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   28875 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   28876 ** option results in an incompatible build of SQLite;  builds of SQLite
   28877 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   28878 ** same database file at the same time, database corruption will likely
   28879 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   28880 ** "unsupported" and may go away in a future SQLite release.
   28881 **
   28882 ** When opening a new shared-memory file, if no other instances of that
   28883 ** file are currently open, in this process or in other processes, then
   28884 ** the file must be truncated to zero length or have its header cleared.
   28885 **
   28886 ** If the original database file (pDbFd) is using the "unix-excl" VFS
   28887 ** that means that an exclusive lock is held on the database file and
   28888 ** that no other processes are able to read or write the database.  In
   28889 ** that case, we do not really need shared memory.  No shared memory
   28890 ** file is created.  The shared memory will be simulated with heap memory.
   28891 */
   28892 static int unixOpenSharedMemory(unixFile *pDbFd){
   28893   struct unixShm *p = 0;          /* The connection to be opened */
   28894   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   28895   int rc;                         /* Result code */
   28896   unixInodeInfo *pInode;          /* The inode of fd */
   28897   char *zShmFilename;             /* Name of the file used for SHM */
   28898   int nShmFilename;               /* Size of the SHM filename in bytes */
   28899 
   28900   /* Allocate space for the new unixShm object. */
   28901   p = sqlite3_malloc( sizeof(*p) );
   28902   if( p==0 ) return SQLITE_NOMEM;
   28903   memset(p, 0, sizeof(*p));
   28904   assert( pDbFd->pShm==0 );
   28905 
   28906   /* Check to see if a unixShmNode object already exists. Reuse an existing
   28907   ** one if present. Create a new one if necessary.
   28908   */
   28909   unixEnterMutex();
   28910   pInode = pDbFd->pInode;
   28911   pShmNode = pInode->pShmNode;
   28912   if( pShmNode==0 ){
   28913     struct stat sStat;                 /* fstat() info for database file */
   28914 
   28915     /* Call fstat() to figure out the permissions on the database file. If
   28916     ** a new *-shm file is created, an attempt will be made to create it
   28917     ** with the same permissions.
   28918     */
   28919     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
   28920       rc = SQLITE_IOERR_FSTAT;
   28921       goto shm_open_err;
   28922     }
   28923 
   28924 #ifdef SQLITE_SHM_DIRECTORY
   28925     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
   28926 #else
   28927     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
   28928 #endif
   28929     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   28930     if( pShmNode==0 ){
   28931       rc = SQLITE_NOMEM;
   28932       goto shm_open_err;
   28933     }
   28934     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
   28935     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   28936 #ifdef SQLITE_SHM_DIRECTORY
   28937     sqlite3_snprintf(nShmFilename, zShmFilename,
   28938                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   28939                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   28940 #else
   28941     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   28942     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
   28943 #endif
   28944     pShmNode->h = -1;
   28945     pDbFd->pInode->pShmNode = pShmNode;
   28946     pShmNode->pInode = pDbFd->pInode;
   28947     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   28948     if( pShmNode->mutex==0 ){
   28949       rc = SQLITE_NOMEM;
   28950       goto shm_open_err;
   28951     }
   28952 
   28953     if( pInode->bProcessLock==0 ){
   28954       int openFlags = O_RDWR | O_CREAT;
   28955       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
   28956         openFlags = O_RDONLY;
   28957         pShmNode->isReadonly = 1;
   28958       }
   28959       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
   28960       if( pShmNode->h<0 ){
   28961         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   28962         goto shm_open_err;
   28963       }
   28964 
   28965       /* If this process is running as root, make sure that the SHM file
   28966       ** is owned by the same user that owns the original database.  Otherwise,
   28967       ** the original owner will not be able to connect. If this process is
   28968       ** not root, the following fchown() will fail, but we don't care.  The
   28969       ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
   28970       ** warnings.
   28971       */
   28972       if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
   28973         pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
   28974       }
   28975 
   28976       /* Check to see if another process is holding the dead-man switch.
   28977       ** If not, truncate the file to zero length.
   28978       */
   28979       rc = SQLITE_OK;
   28980       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   28981         if( robust_ftruncate(pShmNode->h, 0) ){
   28982           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   28983         }
   28984       }
   28985       if( rc==SQLITE_OK ){
   28986         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   28987       }
   28988       if( rc ) goto shm_open_err;
   28989     }
   28990   }
   28991 
   28992   /* Make the new connection a child of the unixShmNode */
   28993   p->pShmNode = pShmNode;
   28994 #ifdef SQLITE_DEBUG
   28995   p->id = pShmNode->nextShmId++;
   28996 #endif
   28997   pShmNode->nRef++;
   28998   pDbFd->pShm = p;
   28999   unixLeaveMutex();
   29000 
   29001   /* The reference count on pShmNode has already been incremented under
   29002   ** the cover of the unixEnterMutex() mutex and the pointer from the
   29003   ** new (struct unixShm) object to the pShmNode has been set. All that is
   29004   ** left to do is to link the new object into the linked list starting
   29005   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   29006   ** mutex.
   29007   */
   29008   sqlite3_mutex_enter(pShmNode->mutex);
   29009   p->pNext = pShmNode->pFirst;
   29010   pShmNode->pFirst = p;
   29011   sqlite3_mutex_leave(pShmNode->mutex);
   29012   return SQLITE_OK;
   29013 
   29014   /* Jump here on any error */
   29015 shm_open_err:
   29016   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   29017   sqlite3_free(p);
   29018   unixLeaveMutex();
   29019   return rc;
   29020 }
   29021 
   29022 /*
   29023 ** This function is called to obtain a pointer to region iRegion of the
   29024 ** shared-memory associated with the database file fd. Shared-memory regions
   29025 ** are numbered starting from zero. Each shared-memory region is szRegion
   29026 ** bytes in size.
   29027 **
   29028 ** If an error occurs, an error code is returned and *pp is set to NULL.
   29029 **
   29030 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   29031 ** region has not been allocated (by any client, including one running in a
   29032 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   29033 ** bExtend is non-zero and the requested shared-memory region has not yet
   29034 ** been allocated, it is allocated by this function.
   29035 **
   29036 ** If the shared-memory region has already been allocated or is allocated by
   29037 ** this call as described above, then it is mapped into this processes
   29038 ** address space (if it is not already), *pp is set to point to the mapped
   29039 ** memory and SQLITE_OK returned.
   29040 */
   29041 static int unixShmMap(
   29042   sqlite3_file *fd,               /* Handle open on database file */
   29043   int iRegion,                    /* Region to retrieve */
   29044   int szRegion,                   /* Size of regions */
   29045   int bExtend,                    /* True to extend file if necessary */
   29046   void volatile **pp              /* OUT: Mapped memory */
   29047 ){
   29048   unixFile *pDbFd = (unixFile*)fd;
   29049   unixShm *p;
   29050   unixShmNode *pShmNode;
   29051   int rc = SQLITE_OK;
   29052 
   29053   /* If the shared-memory file has not yet been opened, open it now. */
   29054   if( pDbFd->pShm==0 ){
   29055     rc = unixOpenSharedMemory(pDbFd);
   29056     if( rc!=SQLITE_OK ) return rc;
   29057   }
   29058 
   29059   p = pDbFd->pShm;
   29060   pShmNode = p->pShmNode;
   29061   sqlite3_mutex_enter(pShmNode->mutex);
   29062   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   29063   assert( pShmNode->pInode==pDbFd->pInode );
   29064   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   29065   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   29066 
   29067   if( pShmNode->nRegion<=iRegion ){
   29068     char **apNew;                      /* New apRegion[] array */
   29069     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   29070     struct stat sStat;                 /* Used by fstat() */
   29071 
   29072     pShmNode->szRegion = szRegion;
   29073 
   29074     if( pShmNode->h>=0 ){
   29075       /* The requested region is not mapped into this processes address space.
   29076       ** Check to see if it has been allocated (i.e. if the wal-index file is
   29077       ** large enough to contain the requested region).
   29078       */
   29079       if( osFstat(pShmNode->h, &sStat) ){
   29080         rc = SQLITE_IOERR_SHMSIZE;
   29081         goto shmpage_out;
   29082       }
   29083 
   29084       if( sStat.st_size<nByte ){
   29085         /* The requested memory region does not exist. If bExtend is set to
   29086         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   29087         **
   29088         ** Alternatively, if bExtend is true, use ftruncate() to allocate
   29089         ** the requested memory region.
   29090         */
   29091         if( !bExtend ) goto shmpage_out;
   29092         if( robust_ftruncate(pShmNode->h, nByte) ){
   29093           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
   29094                             pShmNode->zFilename);
   29095           goto shmpage_out;
   29096         }
   29097       }
   29098     }
   29099 
   29100     /* Map the requested memory region into this processes address space. */
   29101     apNew = (char **)sqlite3_realloc(
   29102         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
   29103     );
   29104     if( !apNew ){
   29105       rc = SQLITE_IOERR_NOMEM;
   29106       goto shmpage_out;
   29107     }
   29108     pShmNode->apRegion = apNew;
   29109     while(pShmNode->nRegion<=iRegion){
   29110       void *pMem;
   29111       if( pShmNode->h>=0 ){
   29112         pMem = mmap(0, szRegion,
   29113             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
   29114             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
   29115         );
   29116         if( pMem==MAP_FAILED ){
   29117           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
   29118           goto shmpage_out;
   29119         }
   29120       }else{
   29121         pMem = sqlite3_malloc(szRegion);
   29122         if( pMem==0 ){
   29123           rc = SQLITE_NOMEM;
   29124           goto shmpage_out;
   29125         }
   29126         memset(pMem, 0, szRegion);
   29127       }
   29128       pShmNode->apRegion[pShmNode->nRegion] = pMem;
   29129       pShmNode->nRegion++;
   29130     }
   29131   }
   29132 
   29133 shmpage_out:
   29134   if( pShmNode->nRegion>iRegion ){
   29135     *pp = pShmNode->apRegion[iRegion];
   29136   }else{
   29137     *pp = 0;
   29138   }
   29139   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
   29140   sqlite3_mutex_leave(pShmNode->mutex);
   29141   return rc;
   29142 }
   29143 
   29144 /*
   29145 ** Change the lock state for a shared-memory segment.
   29146 **
   29147 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   29148 ** different here than in posix.  In xShmLock(), one can go from unlocked
   29149 ** to shared and back or from unlocked to exclusive and back.  But one may
   29150 ** not go from shared to exclusive or from exclusive to shared.
   29151 */
   29152 static int unixShmLock(
   29153   sqlite3_file *fd,          /* Database file holding the shared memory */
   29154   int ofst,                  /* First lock to acquire or release */
   29155   int n,                     /* Number of locks to acquire or release */
   29156   int flags                  /* What to do with the lock */
   29157 ){
   29158   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   29159   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   29160   unixShm *pX;                          /* For looping over all siblings */
   29161   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   29162   int rc = SQLITE_OK;                   /* Result code */
   29163   u16 mask;                             /* Mask of locks to take or release */
   29164 
   29165   assert( pShmNode==pDbFd->pInode->pShmNode );
   29166   assert( pShmNode->pInode==pDbFd->pInode );
   29167   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   29168   assert( n>=1 );
   29169   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   29170        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   29171        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   29172        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   29173   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   29174   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
   29175   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
   29176 
   29177   mask = (1<<(ofst+n)) - (1<<ofst);
   29178   assert( n>1 || mask==(1<<ofst) );
   29179   sqlite3_mutex_enter(pShmNode->mutex);
   29180   if( flags & SQLITE_SHM_UNLOCK ){
   29181     u16 allMask = 0; /* Mask of locks held by siblings */
   29182 
   29183     /* See if any siblings hold this same lock */
   29184     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29185       if( pX==p ) continue;
   29186       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   29187       allMask |= pX->sharedMask;
   29188     }
   29189 
   29190     /* Unlock the system-level locks */
   29191     if( (mask & allMask)==0 ){
   29192       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   29193     }else{
   29194       rc = SQLITE_OK;
   29195     }
   29196 
   29197     /* Undo the local locks */
   29198     if( rc==SQLITE_OK ){
   29199       p->exclMask &= ~mask;
   29200       p->sharedMask &= ~mask;
   29201     }
   29202   }else if( flags & SQLITE_SHM_SHARED ){
   29203     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   29204 
   29205     /* Find out which shared locks are already held by sibling connections.
   29206     ** If any sibling already holds an exclusive lock, go ahead and return
   29207     ** SQLITE_BUSY.
   29208     */
   29209     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29210       if( (pX->exclMask & mask)!=0 ){
   29211         rc = SQLITE_BUSY;
   29212         break;
   29213       }
   29214       allShared |= pX->sharedMask;
   29215     }
   29216 
   29217     /* Get shared locks at the system level, if necessary */
   29218     if( rc==SQLITE_OK ){
   29219       if( (allShared & mask)==0 ){
   29220         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   29221       }else{
   29222         rc = SQLITE_OK;
   29223       }
   29224     }
   29225 
   29226     /* Get the local shared locks */
   29227     if( rc==SQLITE_OK ){
   29228       p->sharedMask |= mask;
   29229     }
   29230   }else{
   29231     /* Make sure no sibling connections hold locks that will block this
   29232     ** lock.  If any do, return SQLITE_BUSY right away.
   29233     */
   29234     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   29235       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   29236         rc = SQLITE_BUSY;
   29237         break;
   29238       }
   29239     }
   29240 
   29241     /* Get the exclusive locks at the system level.  Then if successful
   29242     ** also mark the local connection as being locked.
   29243     */
   29244     if( rc==SQLITE_OK ){
   29245       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   29246       if( rc==SQLITE_OK ){
   29247         assert( (p->sharedMask & mask)==0 );
   29248         p->exclMask |= mask;
   29249       }
   29250     }
   29251   }
   29252   sqlite3_mutex_leave(pShmNode->mutex);
   29253   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   29254            p->id, getpid(), p->sharedMask, p->exclMask));
   29255   return rc;
   29256 }
   29257 
   29258 /*
   29259 ** Implement a memory barrier or memory fence on shared memory.
   29260 **
   29261 ** All loads and stores begun before the barrier must complete before
   29262 ** any load or store begun after the barrier.
   29263 */
   29264 static void unixShmBarrier(
   29265   sqlite3_file *fd                /* Database file holding the shared memory */
   29266 ){
   29267   UNUSED_PARAMETER(fd);
   29268   unixEnterMutex();
   29269   unixLeaveMutex();
   29270 }
   29271 
   29272 /*
   29273 ** Close a connection to shared-memory.  Delete the underlying
   29274 ** storage if deleteFlag is true.
   29275 **
   29276 ** If there is no shared memory associated with the connection then this
   29277 ** routine is a harmless no-op.
   29278 */
   29279 static int unixShmUnmap(
   29280   sqlite3_file *fd,               /* The underlying database file */
   29281   int deleteFlag                  /* Delete shared-memory if true */
   29282 ){
   29283   unixShm *p;                     /* The connection to be closed */
   29284   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   29285   unixShm **pp;                   /* For looping over sibling connections */
   29286   unixFile *pDbFd;                /* The underlying database file */
   29287 
   29288   pDbFd = (unixFile*)fd;
   29289   p = pDbFd->pShm;
   29290   if( p==0 ) return SQLITE_OK;
   29291   pShmNode = p->pShmNode;
   29292 
   29293   assert( pShmNode==pDbFd->pInode->pShmNode );
   29294   assert( pShmNode->pInode==pDbFd->pInode );
   29295 
   29296   /* Remove connection p from the set of connections associated
   29297   ** with pShmNode */
   29298   sqlite3_mutex_enter(pShmNode->mutex);
   29299   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   29300   *pp = p->pNext;
   29301 
   29302   /* Free the connection p */
   29303   sqlite3_free(p);
   29304   pDbFd->pShm = 0;
   29305   sqlite3_mutex_leave(pShmNode->mutex);
   29306 
   29307   /* If pShmNode->nRef has reached 0, then close the underlying
   29308   ** shared-memory file, too */
   29309   unixEnterMutex();
   29310   assert( pShmNode->nRef>0 );
   29311   pShmNode->nRef--;
   29312   if( pShmNode->nRef==0 ){
   29313     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
   29314     unixShmPurge(pDbFd);
   29315   }
   29316   unixLeaveMutex();
   29317 
   29318   return SQLITE_OK;
   29319 }
   29320 
   29321 
   29322 #else
   29323 # define unixShmMap     0
   29324 # define unixShmLock    0
   29325 # define unixShmBarrier 0
   29326 # define unixShmUnmap   0
   29327 #endif /* #ifndef SQLITE_OMIT_WAL */
   29328 
   29329 /*
   29330 ** Here ends the implementation of all sqlite3_file methods.
   29331 **
   29332 ********************** End sqlite3_file Methods *******************************
   29333 ******************************************************************************/
   29334 
   29335 /*
   29336 ** This division contains definitions of sqlite3_io_methods objects that
   29337 ** implement various file locking strategies.  It also contains definitions
   29338 ** of "finder" functions.  A finder-function is used to locate the appropriate
   29339 ** sqlite3_io_methods object for a particular database file.  The pAppData
   29340 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   29341 ** the correct finder-function for that VFS.
   29342 **
   29343 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   29344 ** object.  The only interesting finder-function is autolockIoFinder, which
   29345 ** looks at the filesystem type and tries to guess the best locking
   29346 ** strategy from that.
   29347 **
   29348 ** For finder-funtion F, two objects are created:
   29349 **
   29350 **    (1) The real finder-function named "FImpt()".
   29351 **
   29352 **    (2) A constant pointer to this function named just "F".
   29353 **
   29354 **
   29355 ** A pointer to the F pointer is used as the pAppData value for VFS
   29356 ** objects.  We have to do this instead of letting pAppData point
   29357 ** directly at the finder-function since C90 rules prevent a void*
   29358 ** from be cast into a function pointer.
   29359 **
   29360 **
   29361 ** Each instance of this macro generates two objects:
   29362 **
   29363 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   29364 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   29365 **
   29366 **   *  An I/O method finder function called FINDER that returns a pointer
   29367 **      to the METHOD object in the previous bullet.
   29368 */
   29369 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   29370 static const sqlite3_io_methods METHOD = {                                   \
   29371    VERSION,                    /* iVersion */                                \
   29372    CLOSE,                      /* xClose */                                  \
   29373    unixRead,                   /* xRead */                                   \
   29374    unixWrite,                  /* xWrite */                                  \
   29375    unixTruncate,               /* xTruncate */                               \
   29376    unixSync,                   /* xSync */                                   \
   29377    unixFileSize,               /* xFileSize */                               \
   29378    LOCK,                       /* xLock */                                   \
   29379    UNLOCK,                     /* xUnlock */                                 \
   29380    CKLOCK,                     /* xCheckReservedLock */                      \
   29381    unixFileControl,            /* xFileControl */                            \
   29382    unixSectorSize,             /* xSectorSize */                             \
   29383    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   29384    unixShmMap,                 /* xShmMap */                                 \
   29385    unixShmLock,                /* xShmLock */                                \
   29386    unixShmBarrier,             /* xShmBarrier */                             \
   29387    unixShmUnmap                /* xShmUnmap */                               \
   29388 };                                                                           \
   29389 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   29390   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   29391   return &METHOD;                                                            \
   29392 }                                                                            \
   29393 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   29394     = FINDER##Impl;
   29395 
   29396 /*
   29397 ** Here are all of the sqlite3_io_methods objects for each of the
   29398 ** locking strategies.  Functions that return pointers to these methods
   29399 ** are also created.
   29400 */
   29401 IOMETHODS(
   29402   posixIoFinder,            /* Finder function name */
   29403   posixIoMethods,           /* sqlite3_io_methods object name */
   29404   2,                        /* shared memory is enabled */
   29405   unixClose,                /* xClose method */
   29406   unixLock,                 /* xLock method */
   29407   unixUnlock,               /* xUnlock method */
   29408   unixCheckReservedLock     /* xCheckReservedLock method */
   29409 )
   29410 IOMETHODS(
   29411   nolockIoFinder,           /* Finder function name */
   29412   nolockIoMethods,          /* sqlite3_io_methods object name */
   29413   1,                        /* shared memory is disabled */
   29414   nolockClose,              /* xClose method */
   29415   nolockLock,               /* xLock method */
   29416   nolockUnlock,             /* xUnlock method */
   29417   nolockCheckReservedLock   /* xCheckReservedLock method */
   29418 )
   29419 IOMETHODS(
   29420   dotlockIoFinder,          /* Finder function name */
   29421   dotlockIoMethods,         /* sqlite3_io_methods object name */
   29422   1,                        /* shared memory is disabled */
   29423   dotlockClose,             /* xClose method */
   29424   dotlockLock,              /* xLock method */
   29425   dotlockUnlock,            /* xUnlock method */
   29426   dotlockCheckReservedLock  /* xCheckReservedLock method */
   29427 )
   29428 
   29429 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   29430 IOMETHODS(
   29431   flockIoFinder,            /* Finder function name */
   29432   flockIoMethods,           /* sqlite3_io_methods object name */
   29433   1,                        /* shared memory is disabled */
   29434   flockClose,               /* xClose method */
   29435   flockLock,                /* xLock method */
   29436   flockUnlock,              /* xUnlock method */
   29437   flockCheckReservedLock    /* xCheckReservedLock method */
   29438 )
   29439 #endif
   29440 
   29441 #if OS_VXWORKS
   29442 IOMETHODS(
   29443   semIoFinder,              /* Finder function name */
   29444   semIoMethods,             /* sqlite3_io_methods object name */
   29445   1,                        /* shared memory is disabled */
   29446   semClose,                 /* xClose method */
   29447   semLock,                  /* xLock method */
   29448   semUnlock,                /* xUnlock method */
   29449   semCheckReservedLock      /* xCheckReservedLock method */
   29450 )
   29451 #endif
   29452 
   29453 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29454 IOMETHODS(
   29455   afpIoFinder,              /* Finder function name */
   29456   afpIoMethods,             /* sqlite3_io_methods object name */
   29457   1,                        /* shared memory is disabled */
   29458   afpClose,                 /* xClose method */
   29459   afpLock,                  /* xLock method */
   29460   afpUnlock,                /* xUnlock method */
   29461   afpCheckReservedLock      /* xCheckReservedLock method */
   29462 )
   29463 #endif
   29464 
   29465 /*
   29466 ** The proxy locking method is a "super-method" in the sense that it
   29467 ** opens secondary file descriptors for the conch and lock files and
   29468 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   29469 ** secondary files.  For this reason, the division that implements
   29470 ** proxy locking is located much further down in the file.  But we need
   29471 ** to go ahead and define the sqlite3_io_methods and finder function
   29472 ** for proxy locking here.  So we forward declare the I/O methods.
   29473 */
   29474 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29475 static int proxyClose(sqlite3_file*);
   29476 static int proxyLock(sqlite3_file*, int);
   29477 static int proxyUnlock(sqlite3_file*, int);
   29478 static int proxyCheckReservedLock(sqlite3_file*, int*);
   29479 IOMETHODS(
   29480   proxyIoFinder,            /* Finder function name */
   29481   proxyIoMethods,           /* sqlite3_io_methods object name */
   29482   1,                        /* shared memory is disabled */
   29483   proxyClose,               /* xClose method */
   29484   proxyLock,                /* xLock method */
   29485   proxyUnlock,              /* xUnlock method */
   29486   proxyCheckReservedLock    /* xCheckReservedLock method */
   29487 )
   29488 #endif
   29489 
   29490 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   29491 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29492 IOMETHODS(
   29493   nfsIoFinder,               /* Finder function name */
   29494   nfsIoMethods,              /* sqlite3_io_methods object name */
   29495   1,                         /* shared memory is disabled */
   29496   unixClose,                 /* xClose method */
   29497   unixLock,                  /* xLock method */
   29498   nfsUnlock,                 /* xUnlock method */
   29499   unixCheckReservedLock      /* xCheckReservedLock method */
   29500 )
   29501 #endif
   29502 
   29503 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29504 /*
   29505 ** This "finder" function attempts to determine the best locking strategy
   29506 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29507 ** object that implements that strategy.
   29508 **
   29509 ** This is for MacOSX only.
   29510 */
   29511 static const sqlite3_io_methods *autolockIoFinderImpl(
   29512   const char *filePath,    /* name of the database file */
   29513   unixFile *pNew           /* open file object for the database file */
   29514 ){
   29515   static const struct Mapping {
   29516     const char *zFilesystem;              /* Filesystem type name */
   29517     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   29518   } aMap[] = {
   29519     { "hfs",    &posixIoMethods },
   29520     { "ufs",    &posixIoMethods },
   29521     { "afpfs",  &afpIoMethods },
   29522     { "smbfs",  &afpIoMethods },
   29523     { "webdav", &nolockIoMethods },
   29524     { 0, 0 }
   29525   };
   29526   int i;
   29527   struct statfs fsInfo;
   29528   struct flock lockInfo;
   29529 
   29530   if( !filePath ){
   29531     /* If filePath==NULL that means we are dealing with a transient file
   29532     ** that does not need to be locked. */
   29533     return &nolockIoMethods;
   29534   }
   29535   if( statfs(filePath, &fsInfo) != -1 ){
   29536     if( fsInfo.f_flags & MNT_RDONLY ){
   29537       return &nolockIoMethods;
   29538     }
   29539     for(i=0; aMap[i].zFilesystem; i++){
   29540       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   29541         return aMap[i].pMethods;
   29542       }
   29543     }
   29544   }
   29545 
   29546   /* Default case. Handles, amongst others, "nfs".
   29547   ** Test byte-range lock using fcntl(). If the call succeeds,
   29548   ** assume that the file-system supports POSIX style locks.
   29549   */
   29550   lockInfo.l_len = 1;
   29551   lockInfo.l_start = 0;
   29552   lockInfo.l_whence = SEEK_SET;
   29553   lockInfo.l_type = F_RDLCK;
   29554   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29555     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   29556       return &nfsIoMethods;
   29557     } else {
   29558       return &posixIoMethods;
   29559     }
   29560   }else{
   29561     return &dotlockIoMethods;
   29562   }
   29563 }
   29564 static const sqlite3_io_methods
   29565   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29566 
   29567 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   29568 
   29569 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   29570 /*
   29571 ** This "finder" function attempts to determine the best locking strategy
   29572 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   29573 ** object that implements that strategy.
   29574 **
   29575 ** This is for VXWorks only.
   29576 */
   29577 static const sqlite3_io_methods *autolockIoFinderImpl(
   29578   const char *filePath,    /* name of the database file */
   29579   unixFile *pNew           /* the open file object */
   29580 ){
   29581   struct flock lockInfo;
   29582 
   29583   if( !filePath ){
   29584     /* If filePath==NULL that means we are dealing with a transient file
   29585     ** that does not need to be locked. */
   29586     return &nolockIoMethods;
   29587   }
   29588 
   29589   /* Test if fcntl() is supported and use POSIX style locks.
   29590   ** Otherwise fall back to the named semaphore method.
   29591   */
   29592   lockInfo.l_len = 1;
   29593   lockInfo.l_start = 0;
   29594   lockInfo.l_whence = SEEK_SET;
   29595   lockInfo.l_type = F_RDLCK;
   29596   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   29597     return &posixIoMethods;
   29598   }else{
   29599     return &semIoMethods;
   29600   }
   29601 }
   29602 static const sqlite3_io_methods
   29603   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   29604 
   29605 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   29606 
   29607 /*
   29608 ** An abstract type for a pointer to a IO method finder function:
   29609 */
   29610 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   29611 
   29612 
   29613 /****************************************************************************
   29614 **************************** sqlite3_vfs methods ****************************
   29615 **
   29616 ** This division contains the implementation of methods on the
   29617 ** sqlite3_vfs object.
   29618 */
   29619 
   29620 /*
   29621 ** Initialize the contents of the unixFile structure pointed to by pId.
   29622 */
   29623 static int fillInUnixFile(
   29624   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   29625   int h,                  /* Open file descriptor of file being opened */
   29626   sqlite3_file *pId,      /* Write to the unixFile structure here */
   29627   const char *zFilename,  /* Name of the file being opened */
   29628   int ctrlFlags           /* Zero or more UNIXFILE_* values */
   29629 ){
   29630   const sqlite3_io_methods *pLockingStyle;
   29631   unixFile *pNew = (unixFile *)pId;
   29632   int rc = SQLITE_OK;
   29633 
   29634   assert( pNew->pInode==NULL );
   29635 
   29636   /* Usually the path zFilename should not be a relative pathname. The
   29637   ** exception is when opening the proxy "conch" file in builds that
   29638   ** include the special Apple locking styles.
   29639   */
   29640 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29641   assert( zFilename==0 || zFilename[0]=='/'
   29642     || pVfs->pAppData==(void*)&autolockIoFinder );
   29643 #else
   29644   assert( zFilename==0 || zFilename[0]=='/' );
   29645 #endif
   29646 
   29647   /* No locking occurs in temporary files */
   29648   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
   29649 
   29650   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   29651   pNew->h = h;
   29652   pNew->pVfs = pVfs;
   29653   pNew->zPath = zFilename;
   29654   pNew->ctrlFlags = (u8)ctrlFlags;
   29655   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
   29656                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   29657     pNew->ctrlFlags |= UNIXFILE_PSOW;
   29658   }
   29659   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
   29660     pNew->ctrlFlags |= UNIXFILE_EXCL;
   29661   }
   29662 
   29663 #if OS_VXWORKS
   29664   pNew->pId = vxworksFindFileId(zFilename);
   29665   if( pNew->pId==0 ){
   29666     ctrlFlags |= UNIXFILE_NOLOCK;
   29667     rc = SQLITE_NOMEM;
   29668   }
   29669 #endif
   29670 
   29671   if( ctrlFlags & UNIXFILE_NOLOCK ){
   29672     pLockingStyle = &nolockIoMethods;
   29673   }else{
   29674     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   29675 #if SQLITE_ENABLE_LOCKING_STYLE
   29676     /* Cache zFilename in the locking context (AFP and dotlock override) for
   29677     ** proxyLock activation is possible (remote proxy is based on db name)
   29678     ** zFilename remains valid until file is closed, to support */
   29679     pNew->lockingContext = (void*)zFilename;
   29680 #endif
   29681   }
   29682 
   29683   if( pLockingStyle == &posixIoMethods
   29684 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   29685     || pLockingStyle == &nfsIoMethods
   29686 #endif
   29687   ){
   29688     unixEnterMutex();
   29689     rc = findInodeInfo(pNew, &pNew->pInode);
   29690     if( rc!=SQLITE_OK ){
   29691       /* If an error occured in findInodeInfo(), close the file descriptor
   29692       ** immediately, before releasing the mutex. findInodeInfo() may fail
   29693       ** in two scenarios:
   29694       **
   29695       **   (a) A call to fstat() failed.
   29696       **   (b) A malloc failed.
   29697       **
   29698       ** Scenario (b) may only occur if the process is holding no other
   29699       ** file descriptors open on the same file. If there were other file
   29700       ** descriptors on this file, then no malloc would be required by
   29701       ** findInodeInfo(). If this is the case, it is quite safe to close
   29702       ** handle h - as it is guaranteed that no posix locks will be released
   29703       ** by doing so.
   29704       **
   29705       ** If scenario (a) caused the error then things are not so safe. The
   29706       ** implicit assumption here is that if fstat() fails, things are in
   29707       ** such bad shape that dropping a lock or two doesn't matter much.
   29708       */
   29709       robust_close(pNew, h, __LINE__);
   29710       h = -1;
   29711     }
   29712     unixLeaveMutex();
   29713   }
   29714 
   29715 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29716   else if( pLockingStyle == &afpIoMethods ){
   29717     /* AFP locking uses the file path so it needs to be included in
   29718     ** the afpLockingContext.
   29719     */
   29720     afpLockingContext *pCtx;
   29721     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   29722     if( pCtx==0 ){
   29723       rc = SQLITE_NOMEM;
   29724     }else{
   29725       /* NB: zFilename exists and remains valid until the file is closed
   29726       ** according to requirement F11141.  So we do not need to make a
   29727       ** copy of the filename. */
   29728       pCtx->dbPath = zFilename;
   29729       pCtx->reserved = 0;
   29730       srandomdev();
   29731       unixEnterMutex();
   29732       rc = findInodeInfo(pNew, &pNew->pInode);
   29733       if( rc!=SQLITE_OK ){
   29734         sqlite3_free(pNew->lockingContext);
   29735         robust_close(pNew, h, __LINE__);
   29736         h = -1;
   29737       }
   29738       unixLeaveMutex();
   29739     }
   29740   }
   29741 #endif
   29742 
   29743   else if( pLockingStyle == &dotlockIoMethods ){
   29744     /* Dotfile locking uses the file path so it needs to be included in
   29745     ** the dotlockLockingContext
   29746     */
   29747     char *zLockFile;
   29748     int nFilename;
   29749     assert( zFilename!=0 );
   29750     nFilename = (int)strlen(zFilename) + 6;
   29751     zLockFile = (char *)sqlite3_malloc(nFilename);
   29752     if( zLockFile==0 ){
   29753       rc = SQLITE_NOMEM;
   29754     }else{
   29755       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   29756     }
   29757     pNew->lockingContext = zLockFile;
   29758   }
   29759 
   29760 #if OS_VXWORKS
   29761   else if( pLockingStyle == &semIoMethods ){
   29762     /* Named semaphore locking uses the file path so it needs to be
   29763     ** included in the semLockingContext
   29764     */
   29765     unixEnterMutex();
   29766     rc = findInodeInfo(pNew, &pNew->pInode);
   29767     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   29768       char *zSemName = pNew->pInode->aSemName;
   29769       int n;
   29770       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   29771                        pNew->pId->zCanonicalName);
   29772       for( n=1; zSemName[n]; n++ )
   29773         if( zSemName[n]=='/' ) zSemName[n] = '_';
   29774       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   29775       if( pNew->pInode->pSem == SEM_FAILED ){
   29776         rc = SQLITE_NOMEM;
   29777         pNew->pInode->aSemName[0] = '\0';
   29778       }
   29779     }
   29780     unixLeaveMutex();
   29781   }
   29782 #endif
   29783 
   29784   pNew->lastErrno = 0;
   29785 #if OS_VXWORKS
   29786   if( rc!=SQLITE_OK ){
   29787     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29788     h = -1;
   29789     osUnlink(zFilename);
   29790     isDelete = 0;
   29791   }
   29792   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
   29793 #endif
   29794   if( rc!=SQLITE_OK ){
   29795     if( h>=0 ) robust_close(pNew, h, __LINE__);
   29796   }else{
   29797     pNew->pMethod = pLockingStyle;
   29798     OpenCounter(+1);
   29799   }
   29800   return rc;
   29801 }
   29802 
   29803 /*
   29804 ** Return the name of a directory in which to put temporary files.
   29805 ** If no suitable temporary file directory can be found, return NULL.
   29806 */
   29807 static const char *unixTempFileDir(void){
   29808   static const char *azDirs[] = {
   29809      0,
   29810      0,
   29811      "/var/tmp",
   29812      "/usr/tmp",
   29813      "/tmp",
   29814      0        /* List terminator */
   29815   };
   29816   unsigned int i;
   29817   struct stat buf;
   29818   const char *zDir = 0;
   29819 
   29820   azDirs[0] = sqlite3_temp_directory;
   29821   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   29822   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   29823     if( zDir==0 ) continue;
   29824     if( osStat(zDir, &buf) ) continue;
   29825     if( !S_ISDIR(buf.st_mode) ) continue;
   29826     if( osAccess(zDir, 07) ) continue;
   29827     break;
   29828   }
   29829   return zDir;
   29830 }
   29831 
   29832 /*
   29833 ** Create a temporary file name in zBuf.  zBuf must be allocated
   29834 ** by the calling process and must be big enough to hold at least
   29835 ** pVfs->mxPathname bytes.
   29836 */
   29837 static int unixGetTempname(int nBuf, char *zBuf){
   29838   static const unsigned char zChars[] =
   29839     "abcdefghijklmnopqrstuvwxyz"
   29840     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   29841     "0123456789";
   29842   unsigned int i, j;
   29843   const char *zDir;
   29844 
   29845   /* It's odd to simulate an io-error here, but really this is just
   29846   ** using the io-error infrastructure to test that SQLite handles this
   29847   ** function failing.
   29848   */
   29849   SimulateIOError( return SQLITE_IOERR );
   29850 
   29851   zDir = unixTempFileDir();
   29852   if( zDir==0 ) zDir = ".";
   29853 
   29854   /* Check that the output buffer is large enough for the temporary file
   29855   ** name. If it is not, return SQLITE_ERROR.
   29856   */
   29857   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
   29858     return SQLITE_ERROR;
   29859   }
   29860 
   29861   do{
   29862     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   29863     j = (int)strlen(zBuf);
   29864     sqlite3_randomness(15, &zBuf[j]);
   29865     for(i=0; i<15; i++, j++){
   29866       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   29867     }
   29868     zBuf[j] = 0;
   29869     zBuf[j+1] = 0;
   29870   }while( osAccess(zBuf,0)==0 );
   29871   return SQLITE_OK;
   29872 }
   29873 
   29874 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29875 /*
   29876 ** Routine to transform a unixFile into a proxy-locking unixFile.
   29877 ** Implementation in the proxy-lock division, but used by unixOpen()
   29878 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   29879 */
   29880 static int proxyTransformUnixFile(unixFile*, const char*);
   29881 #endif
   29882 
   29883 /*
   29884 ** Search for an unused file descriptor that was opened on the database
   29885 ** file (not a journal or master-journal file) identified by pathname
   29886 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   29887 ** argument to this function.
   29888 **
   29889 ** Such a file descriptor may exist if a database connection was closed
   29890 ** but the associated file descriptor could not be closed because some
   29891 ** other file descriptor open on the same file is holding a file-lock.
   29892 ** Refer to comments in the unixClose() function and the lengthy comment
   29893 ** describing "Posix Advisory Locking" at the start of this file for
   29894 ** further details. Also, ticket #4018.
   29895 **
   29896 ** If a suitable file descriptor is found, then it is returned. If no
   29897 ** such file descriptor is located, -1 is returned.
   29898 */
   29899 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   29900   UnixUnusedFd *pUnused = 0;
   29901 
   29902   /* Do not search for an unused file descriptor on vxworks. Not because
   29903   ** vxworks would not benefit from the change (it might, we're not sure),
   29904   ** but because no way to test it is currently available. It is better
   29905   ** not to risk breaking vxworks support for the sake of such an obscure
   29906   ** feature.  */
   29907 #if !OS_VXWORKS
   29908   struct stat sStat;                   /* Results of stat() call */
   29909 
   29910   /* A stat() call may fail for various reasons. If this happens, it is
   29911   ** almost certain that an open() call on the same path will also fail.
   29912   ** For this reason, if an error occurs in the stat() call here, it is
   29913   ** ignored and -1 is returned. The caller will try to open a new file
   29914   ** descriptor on the same path, fail, and return an error to SQLite.
   29915   **
   29916   ** Even if a subsequent open() call does succeed, the consequences of
   29917   ** not searching for a resusable file descriptor are not dire.  */
   29918   if( 0==osStat(zPath, &sStat) ){
   29919     unixInodeInfo *pInode;
   29920 
   29921     unixEnterMutex();
   29922     pInode = inodeList;
   29923     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   29924                      || pInode->fileId.ino!=sStat.st_ino) ){
   29925        pInode = pInode->pNext;
   29926     }
   29927     if( pInode ){
   29928       UnixUnusedFd **pp;
   29929       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   29930       pUnused = *pp;
   29931       if( pUnused ){
   29932         *pp = pUnused->pNext;
   29933       }
   29934     }
   29935     unixLeaveMutex();
   29936   }
   29937 #endif    /* if !OS_VXWORKS */
   29938   return pUnused;
   29939 }
   29940 
   29941 /*
   29942 ** This function is called by unixOpen() to determine the unix permissions
   29943 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   29944 ** and a value suitable for passing as the third argument to open(2) is
   29945 ** written to *pMode. If an IO error occurs, an SQLite error code is
   29946 ** returned and the value of *pMode is not modified.
   29947 **
   29948 ** In most cases cases, this routine sets *pMode to 0, which will become
   29949 ** an indication to robust_open() to create the file using
   29950 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
   29951 ** But if the file being opened is a WAL or regular journal file, then
   29952 ** this function queries the file-system for the permissions on the
   29953 ** corresponding database file and sets *pMode to this value. Whenever
   29954 ** possible, WAL and journal files are created using the same permissions
   29955 ** as the associated database file.
   29956 **
   29957 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
   29958 ** original filename is unavailable.  But 8_3_NAMES is only used for
   29959 ** FAT filesystems and permissions do not matter there, so just use
   29960 ** the default permissions.
   29961 */
   29962 static int findCreateFileMode(
   29963   const char *zPath,              /* Path of file (possibly) being created */
   29964   int flags,                      /* Flags passed as 4th argument to xOpen() */
   29965   mode_t *pMode,                  /* OUT: Permissions to open file with */
   29966   uid_t *pUid,                    /* OUT: uid to set on the file */
   29967   gid_t *pGid                     /* OUT: gid to set on the file */
   29968 ){
   29969   int rc = SQLITE_OK;             /* Return Code */
   29970   *pMode = 0;
   29971   *pUid = 0;
   29972   *pGid = 0;
   29973   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   29974     char zDb[MAX_PATHNAME+1];     /* Database file path */
   29975     int nDb;                      /* Number of valid bytes in zDb */
   29976     struct stat sStat;            /* Output of stat() on database file */
   29977 
   29978     /* zPath is a path to a WAL or journal file. The following block derives
   29979     ** the path to the associated database file from zPath. This block handles
   29980     ** the following naming conventions:
   29981     **
   29982     **   "<path to db>-journal"
   29983     **   "<path to db>-wal"
   29984     **   "<path to db>-journalNN"
   29985     **   "<path to db>-walNN"
   29986     **
   29987     ** where NN is a decimal number. The NN naming schemes are
   29988     ** used by the test_multiplex.c module.
   29989     */
   29990     nDb = sqlite3Strlen30(zPath) - 1;
   29991 #ifdef SQLITE_ENABLE_8_3_NAMES
   29992     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
   29993     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
   29994 #else
   29995     while( zPath[nDb]!='-' ){
   29996       assert( nDb>0 );
   29997       assert( zPath[nDb]!='\n' );
   29998       nDb--;
   29999     }
   30000 #endif
   30001     memcpy(zDb, zPath, nDb);
   30002     zDb[nDb] = '\0';
   30003 
   30004     if( 0==osStat(zDb, &sStat) ){
   30005       *pMode = sStat.st_mode & 0777;
   30006       *pUid = sStat.st_uid;
   30007       *pGid = sStat.st_gid;
   30008     }else{
   30009       rc = SQLITE_IOERR_FSTAT;
   30010     }
   30011   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   30012     *pMode = 0600;
   30013   }
   30014   return rc;
   30015 }
   30016 
   30017 /*
   30018 ** Open the file zPath.
   30019 **
   30020 ** Previously, the SQLite OS layer used three functions in place of this
   30021 ** one:
   30022 **
   30023 **     sqlite3OsOpenReadWrite();
   30024 **     sqlite3OsOpenReadOnly();
   30025 **     sqlite3OsOpenExclusive();
   30026 **
   30027 ** These calls correspond to the following combinations of flags:
   30028 **
   30029 **     ReadWrite() ->     (READWRITE | CREATE)
   30030 **     ReadOnly()  ->     (READONLY)
   30031 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   30032 **
   30033 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   30034 ** true, the file was configured to be automatically deleted when the
   30035 ** file handle closed. To achieve the same effect using this new
   30036 ** interface, add the DELETEONCLOSE flag to those specified above for
   30037 ** OpenExclusive().
   30038 */
   30039 static int unixOpen(
   30040   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   30041   const char *zPath,           /* Pathname of file to be opened */
   30042   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   30043   int flags,                   /* Input flags to control the opening */
   30044   int *pOutFlags               /* Output flags returned to SQLite core */
   30045 ){
   30046   unixFile *p = (unixFile *)pFile;
   30047   int fd = -1;                   /* File descriptor returned by open() */
   30048   int openFlags = 0;             /* Flags to pass to open() */
   30049   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   30050   int noLock;                    /* True to omit locking primitives */
   30051   int rc = SQLITE_OK;            /* Function Return Code */
   30052   int ctrlFlags = 0;             /* UNIXFILE_* flags */
   30053 
   30054   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   30055   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   30056   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   30057   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   30058   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   30059 #if SQLITE_ENABLE_LOCKING_STYLE
   30060   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   30061 #endif
   30062 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30063   struct statfs fsInfo;
   30064 #endif
   30065 
   30066   /* If creating a master or main-file journal, this function will open
   30067   ** a file-descriptor on the directory too. The first time unixSync()
   30068   ** is called the directory file descriptor will be fsync()ed and close()d.
   30069   */
   30070   int syncDir = (isCreate && (
   30071         eType==SQLITE_OPEN_MASTER_JOURNAL
   30072      || eType==SQLITE_OPEN_MAIN_JOURNAL
   30073      || eType==SQLITE_OPEN_WAL
   30074   ));
   30075 
   30076   /* If argument zPath is a NULL pointer, this function is required to open
   30077   ** a temporary file. Use this buffer to store the file name in.
   30078   */
   30079   char zTmpname[MAX_PATHNAME+2];
   30080   const char *zName = zPath;
   30081 
   30082   /* Check the following statements are true:
   30083   **
   30084   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   30085   **   (b) if CREATE is set, then READWRITE must also be set, and
   30086   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   30087   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   30088   */
   30089   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   30090   assert(isCreate==0 || isReadWrite);
   30091   assert(isExclusive==0 || isCreate);
   30092   assert(isDelete==0 || isCreate);
   30093 
   30094   /* The main DB, main journal, WAL file and master journal are never
   30095   ** automatically deleted. Nor are they ever temporary files.  */
   30096   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   30097   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   30098   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   30099   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   30100 
   30101   /* Assert that the upper layer has set one of the "file-type" flags. */
   30102   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   30103        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   30104        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   30105        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   30106   );
   30107 
   30108   memset(p, 0, sizeof(unixFile));
   30109 
   30110   if( eType==SQLITE_OPEN_MAIN_DB ){
   30111     UnixUnusedFd *pUnused;
   30112     pUnused = findReusableFd(zName, flags);
   30113     if( pUnused ){
   30114       fd = pUnused->fd;
   30115     }else{
   30116       pUnused = sqlite3_malloc(sizeof(*pUnused));
   30117       if( !pUnused ){
   30118         return SQLITE_NOMEM;
   30119       }
   30120     }
   30121     p->pUnused = pUnused;
   30122 
   30123     /* Database filenames are double-zero terminated if they are not
   30124     ** URIs with parameters.  Hence, they can always be passed into
   30125     ** sqlite3_uri_parameter(). */
   30126     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
   30127 
   30128   }else if( !zName ){
   30129     /* If zName is NULL, the upper layer is requesting a temp file. */
   30130     assert(isDelete && !syncDir);
   30131     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
   30132     if( rc!=SQLITE_OK ){
   30133       return rc;
   30134     }
   30135     zName = zTmpname;
   30136 
   30137     /* Generated temporary filenames are always double-zero terminated
   30138     ** for use by sqlite3_uri_parameter(). */
   30139     assert( zName[strlen(zName)+1]==0 );
   30140   }
   30141 
   30142   /* Determine the value of the flags parameter passed to POSIX function
   30143   ** open(). These must be calculated even if open() is not called, as
   30144   ** they may be stored as part of the file handle and used by the
   30145   ** 'conch file' locking functions later on.  */
   30146   if( isReadonly )  openFlags |= O_RDONLY;
   30147   if( isReadWrite ) openFlags |= O_RDWR;
   30148   if( isCreate )    openFlags |= O_CREAT;
   30149   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   30150   openFlags |= (O_LARGEFILE|O_BINARY);
   30151 
   30152   if( fd<0 ){
   30153     mode_t openMode;              /* Permissions to create file with */
   30154     uid_t uid;                    /* Userid for the file */
   30155     gid_t gid;                    /* Groupid for the file */
   30156     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
   30157     if( rc!=SQLITE_OK ){
   30158       assert( !p->pUnused );
   30159       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   30160       return rc;
   30161     }
   30162     fd = robust_open(zName, openFlags, openMode);
   30163     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   30164     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   30165       /* Failed to open the file for read/write access. Try read-only. */
   30166       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   30167       openFlags &= ~(O_RDWR|O_CREAT);
   30168       flags |= SQLITE_OPEN_READONLY;
   30169       openFlags |= O_RDONLY;
   30170       isReadonly = 1;
   30171       fd = robust_open(zName, openFlags, openMode);
   30172     }
   30173     if( fd<0 ){
   30174       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   30175       goto open_finished;
   30176     }
   30177 
   30178     /* If this process is running as root and if creating a new rollback
   30179     ** journal or WAL file, set the ownership of the journal or WAL to be
   30180     ** the same as the original database.  If we are not running as root,
   30181     ** then the fchown() call will fail, but that's ok.  The "if(){}" and
   30182     ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
   30183     ** warnings from gcc.
   30184     */
   30185     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   30186       if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
   30187     }
   30188   }
   30189   assert( fd>=0 );
   30190   if( pOutFlags ){
   30191     *pOutFlags = flags;
   30192   }
   30193 
   30194   if( p->pUnused ){
   30195     p->pUnused->fd = fd;
   30196     p->pUnused->flags = flags;
   30197   }
   30198 
   30199   if( isDelete ){
   30200 #if OS_VXWORKS
   30201     zPath = zName;
   30202 #else
   30203     osUnlink(zName);
   30204 #endif
   30205   }
   30206 #if SQLITE_ENABLE_LOCKING_STYLE
   30207   else{
   30208     p->openFlags = openFlags;
   30209   }
   30210 #endif
   30211 
   30212 #ifdef FD_CLOEXEC
   30213   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   30214 #endif
   30215 
   30216   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   30217 
   30218 
   30219 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   30220   if( fstatfs(fd, &fsInfo) == -1 ){
   30221     ((unixFile*)pFile)->lastErrno = errno;
   30222     robust_close(p, fd, __LINE__);
   30223     return SQLITE_IOERR_ACCESS;
   30224   }
   30225   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   30226     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   30227   }
   30228 #endif
   30229 
   30230   /* Set up appropriate ctrlFlags */
   30231   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
   30232   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
   30233   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
   30234   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
   30235   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
   30236 
   30237 #if SQLITE_ENABLE_LOCKING_STYLE
   30238 #if SQLITE_PREFER_PROXY_LOCKING
   30239   isAutoProxy = 1;
   30240 #endif
   30241   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   30242     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   30243     int useProxy = 0;
   30244 
   30245     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   30246     ** never use proxy, NULL means use proxy for non-local files only.  */
   30247     if( envforce!=NULL ){
   30248       useProxy = atoi(envforce)>0;
   30249     }else{
   30250       if( statfs(zPath, &fsInfo) == -1 ){
   30251         /* In theory, the close(fd) call is sub-optimal. If the file opened
   30252         ** with fd is a database file, and there are other connections open
   30253         ** on that file that are currently holding advisory locks on it,
   30254         ** then the call to close() will cancel those locks. In practice,
   30255         ** we're assuming that statfs() doesn't fail very often. At least
   30256         ** not while other file descriptors opened by the same process on
   30257         ** the same file are working.  */
   30258         p->lastErrno = errno;
   30259         robust_close(p, fd, __LINE__);
   30260         rc = SQLITE_IOERR_ACCESS;
   30261         goto open_finished;
   30262       }
   30263       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   30264     }
   30265     if( useProxy ){
   30266       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30267       if( rc==SQLITE_OK ){
   30268         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   30269         if( rc!=SQLITE_OK ){
   30270           /* Use unixClose to clean up the resources added in fillInUnixFile
   30271           ** and clear all the structure's references.  Specifically,
   30272           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   30273           */
   30274           unixClose(pFile);
   30275           return rc;
   30276         }
   30277       }
   30278       goto open_finished;
   30279     }
   30280   }
   30281 #endif
   30282 
   30283   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
   30284 
   30285 open_finished:
   30286   if( rc!=SQLITE_OK ){
   30287     sqlite3_free(p->pUnused);
   30288   }
   30289   return rc;
   30290 }
   30291 
   30292 
   30293 /*
   30294 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   30295 ** the directory after deleting the file.
   30296 */
   30297 static int unixDelete(
   30298   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   30299   const char *zPath,        /* Name of file to be deleted */
   30300   int dirSync               /* If true, fsync() directory after deleting file */
   30301 ){
   30302   int rc = SQLITE_OK;
   30303   UNUSED_PARAMETER(NotUsed);
   30304   SimulateIOError(return SQLITE_IOERR_DELETE);
   30305   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
   30306     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   30307   }
   30308 #ifndef SQLITE_DISABLE_DIRSYNC
   30309   if( (dirSync & 1)!=0 ){
   30310     int fd;
   30311     rc = osOpenDirectory(zPath, &fd);
   30312     if( rc==SQLITE_OK ){
   30313 #if OS_VXWORKS
   30314       if( fsync(fd)==-1 )
   30315 #else
   30316       if( fsync(fd) )
   30317 #endif
   30318       {
   30319         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   30320       }
   30321       robust_close(0, fd, __LINE__);
   30322     }else if( rc==SQLITE_CANTOPEN ){
   30323       rc = SQLITE_OK;
   30324     }
   30325   }
   30326 #endif
   30327   return rc;
   30328 }
   30329 
   30330 /*
   30331 ** Test the existance of or access permissions of file zPath. The
   30332 ** test performed depends on the value of flags:
   30333 **
   30334 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   30335 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   30336 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   30337 **
   30338 ** Otherwise return 0.
   30339 */
   30340 static int unixAccess(
   30341   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   30342   const char *zPath,      /* Path of the file to examine */
   30343   int flags,              /* What do we want to learn about the zPath file? */
   30344   int *pResOut            /* Write result boolean here */
   30345 ){
   30346   int amode = 0;
   30347   UNUSED_PARAMETER(NotUsed);
   30348   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   30349   switch( flags ){
   30350     case SQLITE_ACCESS_EXISTS:
   30351       amode = F_OK;
   30352       break;
   30353     case SQLITE_ACCESS_READWRITE:
   30354       amode = W_OK|R_OK;
   30355       break;
   30356     case SQLITE_ACCESS_READ:
   30357       amode = R_OK;
   30358       break;
   30359 
   30360     default:
   30361       assert(!"Invalid flags argument");
   30362   }
   30363   *pResOut = (osAccess(zPath, amode)==0);
   30364   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   30365     struct stat buf;
   30366     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
   30367       *pResOut = 0;
   30368     }
   30369   }
   30370   return SQLITE_OK;
   30371 }
   30372 
   30373 
   30374 /*
   30375 ** Turn a relative pathname into a full pathname. The relative path
   30376 ** is stored as a nul-terminated string in the buffer pointed to by
   30377 ** zPath.
   30378 **
   30379 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   30380 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   30381 ** this buffer before returning.
   30382 */
   30383 static int unixFullPathname(
   30384   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   30385   const char *zPath,            /* Possibly relative input path */
   30386   int nOut,                     /* Size of output buffer in bytes */
   30387   char *zOut                    /* Output buffer */
   30388 ){
   30389 
   30390   /* It's odd to simulate an io-error here, but really this is just
   30391   ** using the io-error infrastructure to test that SQLite handles this
   30392   ** function failing. This function could fail if, for example, the
   30393   ** current working directory has been unlinked.
   30394   */
   30395   SimulateIOError( return SQLITE_ERROR );
   30396 
   30397   assert( pVfs->mxPathname==MAX_PATHNAME );
   30398   UNUSED_PARAMETER(pVfs);
   30399 
   30400   zOut[nOut-1] = '\0';
   30401   if( zPath[0]=='/' ){
   30402     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   30403   }else{
   30404     int nCwd;
   30405     if( osGetcwd(zOut, nOut-1)==0 ){
   30406       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   30407     }
   30408     nCwd = (int)strlen(zOut);
   30409     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   30410   }
   30411   return SQLITE_OK;
   30412 }
   30413 
   30414 
   30415 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   30416 /*
   30417 ** Interfaces for opening a shared library, finding entry points
   30418 ** within the shared library, and closing the shared library.
   30419 */
   30420 #include <dlfcn.h>
   30421 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   30422   UNUSED_PARAMETER(NotUsed);
   30423   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   30424 }
   30425 
   30426 /*
   30427 ** SQLite calls this function immediately after a call to unixDlSym() or
   30428 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   30429 ** message is available, it is written to zBufOut. If no error message
   30430 ** is available, zBufOut is left unmodified and SQLite uses a default
   30431 ** error message.
   30432 */
   30433 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   30434   const char *zErr;
   30435   UNUSED_PARAMETER(NotUsed);
   30436   unixEnterMutex();
   30437   zErr = dlerror();
   30438   if( zErr ){
   30439     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   30440   }
   30441   unixLeaveMutex();
   30442 }
   30443 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   30444   /*
   30445   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   30446   ** cast into a pointer to a function.  And yet the library dlsym() routine
   30447   ** returns a void* which is really a pointer to a function.  So how do we
   30448   ** use dlsym() with -pedantic-errors?
   30449   **
   30450   ** Variable x below is defined to be a pointer to a function taking
   30451   ** parameters void* and const char* and returning a pointer to a function.
   30452   ** We initialize x by assigning it a pointer to the dlsym() function.
   30453   ** (That assignment requires a cast.)  Then we call the function that
   30454   ** x points to.
   30455   **
   30456   ** This work-around is unlikely to work correctly on any system where
   30457   ** you really cannot cast a function pointer into void*.  But then, on the
   30458   ** other hand, dlsym() will not work on such a system either, so we have
   30459   ** not really lost anything.
   30460   */
   30461   void (*(*x)(void*,const char*))(void);
   30462   UNUSED_PARAMETER(NotUsed);
   30463   x = (void(*(*)(void*,const char*))(void))dlsym;
   30464   return (*x)(p, zSym);
   30465 }
   30466 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   30467   UNUSED_PARAMETER(NotUsed);
   30468   dlclose(pHandle);
   30469 }
   30470 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   30471   #define unixDlOpen  0
   30472   #define unixDlError 0
   30473   #define unixDlSym   0
   30474   #define unixDlClose 0
   30475 #endif
   30476 
   30477 /*
   30478 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   30479 */
   30480 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   30481   UNUSED_PARAMETER(NotUsed);
   30482   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   30483 
   30484   /* We have to initialize zBuf to prevent valgrind from reporting
   30485   ** errors.  The reports issued by valgrind are incorrect - we would
   30486   ** prefer that the randomness be increased by making use of the
   30487   ** uninitialized space in zBuf - but valgrind errors tend to worry
   30488   ** some users.  Rather than argue, it seems easier just to initialize
   30489   ** the whole array and silence valgrind, even if that means less randomness
   30490   ** in the random seed.
   30491   **
   30492   ** When testing, initializing zBuf[] to zero is all we do.  That means
   30493   ** that we always use the same random number sequence.  This makes the
   30494   ** tests repeatable.
   30495   */
   30496   memset(zBuf, 0, nBuf);
   30497 #if !defined(SQLITE_TEST)
   30498   {
   30499     int pid, fd, got;
   30500     fd = robust_open("/dev/urandom", O_RDONLY, 0);
   30501     if( fd<0 ){
   30502       time_t t;
   30503       time(&t);
   30504       memcpy(zBuf, &t, sizeof(t));
   30505       pid = getpid();
   30506       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
   30507       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
   30508       nBuf = sizeof(t) + sizeof(pid);
   30509     }else{
   30510       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
   30511       robust_close(0, fd, __LINE__);
   30512     }
   30513   }
   30514 #endif
   30515   return nBuf;
   30516 }
   30517 
   30518 
   30519 /*
   30520 ** Sleep for a little while.  Return the amount of time slept.
   30521 ** The argument is the number of microseconds we want to sleep.
   30522 ** The return value is the number of microseconds of sleep actually
   30523 ** requested from the underlying operating system, a number which
   30524 ** might be greater than or equal to the argument, but not less
   30525 ** than the argument.
   30526 */
   30527 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   30528 #if OS_VXWORKS
   30529   struct timespec sp;
   30530 
   30531   sp.tv_sec = microseconds / 1000000;
   30532   sp.tv_nsec = (microseconds % 1000000) * 1000;
   30533   nanosleep(&sp, NULL);
   30534   UNUSED_PARAMETER(NotUsed);
   30535   return microseconds;
   30536 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   30537   usleep(microseconds);
   30538   UNUSED_PARAMETER(NotUsed);
   30539   return microseconds;
   30540 #else
   30541   int seconds = (microseconds+999999)/1000000;
   30542   sleep(seconds);
   30543   UNUSED_PARAMETER(NotUsed);
   30544   return seconds*1000000;
   30545 #endif
   30546 }
   30547 
   30548 /*
   30549 ** The following variable, if set to a non-zero value, is interpreted as
   30550 ** the number of seconds since 1970 and is used to set the result of
   30551 ** sqlite3OsCurrentTime() during testing.
   30552 */
   30553 #ifdef SQLITE_TEST
   30554 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   30555 #endif
   30556 
   30557 /*
   30558 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   30559 ** the current time and date as a Julian Day number times 86_400_000.  In
   30560 ** other words, write into *piNow the number of milliseconds since the Julian
   30561 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   30562 ** proleptic Gregorian calendar.
   30563 **
   30564 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   30565 ** cannot be found.
   30566 */
   30567 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   30568   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   30569   int rc = SQLITE_OK;
   30570 #if defined(NO_GETTOD)
   30571   time_t t;
   30572   time(&t);
   30573   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   30574 #elif OS_VXWORKS
   30575   struct timespec sNow;
   30576   clock_gettime(CLOCK_REALTIME, &sNow);
   30577   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   30578 #else
   30579   struct timeval sNow;
   30580   if( gettimeofday(&sNow, 0)==0 ){
   30581     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   30582   }else{
   30583     rc = SQLITE_ERROR;
   30584   }
   30585 #endif
   30586 
   30587 #ifdef SQLITE_TEST
   30588   if( sqlite3_current_time ){
   30589     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   30590   }
   30591 #endif
   30592   UNUSED_PARAMETER(NotUsed);
   30593   return rc;
   30594 }
   30595 
   30596 /*
   30597 ** Find the current time (in Universal Coordinated Time).  Write the
   30598 ** current time and date as a Julian Day number into *prNow and
   30599 ** return 0.  Return 1 if the time and date cannot be found.
   30600 */
   30601 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   30602   sqlite3_int64 i = 0;
   30603   int rc;
   30604   UNUSED_PARAMETER(NotUsed);
   30605   rc = unixCurrentTimeInt64(0, &i);
   30606   *prNow = i/86400000.0;
   30607   return rc;
   30608 }
   30609 
   30610 /*
   30611 ** We added the xGetLastError() method with the intention of providing
   30612 ** better low-level error messages when operating-system problems come up
   30613 ** during SQLite operation.  But so far, none of that has been implemented
   30614 ** in the core.  So this routine is never called.  For now, it is merely
   30615 ** a place-holder.
   30616 */
   30617 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   30618   UNUSED_PARAMETER(NotUsed);
   30619   UNUSED_PARAMETER(NotUsed2);
   30620   UNUSED_PARAMETER(NotUsed3);
   30621   return 0;
   30622 }
   30623 
   30624 
   30625 /*
   30626 ************************ End of sqlite3_vfs methods ***************************
   30627 ******************************************************************************/
   30628 
   30629 /******************************************************************************
   30630 ************************** Begin Proxy Locking ********************************
   30631 **
   30632 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   30633 ** other locking methods on secondary lock files.  Proxy locking is a
   30634 ** meta-layer over top of the primitive locking implemented above.  For
   30635 ** this reason, the division that implements of proxy locking is deferred
   30636 ** until late in the file (here) after all of the other I/O methods have
   30637 ** been defined - so that the primitive locking methods are available
   30638 ** as services to help with the implementation of proxy locking.
   30639 **
   30640 ****
   30641 **
   30642 ** The default locking schemes in SQLite use byte-range locks on the
   30643 ** database file to coordinate safe, concurrent access by multiple readers
   30644 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   30645 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   30646 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   30647 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   30648 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   30649 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   30650 ** address in the shared range is taken for a SHARED lock, the entire
   30651 ** shared range is taken for an EXCLUSIVE lock):
   30652 **
   30653 **      PENDING_BYTE        0x40000000
   30654 **      RESERVED_BYTE       0x40000001
   30655 **      SHARED_RANGE        0x40000002 -> 0x40000200
   30656 **
   30657 ** This works well on the local file system, but shows a nearly 100x
   30658 ** slowdown in read performance on AFP because the AFP client disables
   30659 ** the read cache when byte-range locks are present.  Enabling the read
   30660 ** cache exposes a cache coherency problem that is present on all OS X
   30661 ** supported network file systems.  NFS and AFP both observe the
   30662 ** close-to-open semantics for ensuring cache coherency
   30663 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   30664 ** address the requirements for concurrent database access by multiple
   30665 ** readers and writers
   30666 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   30667 **
   30668 ** To address the performance and cache coherency issues, proxy file locking
   30669 ** changes the way database access is controlled by limiting access to a
   30670 ** single host at a time and moving file locks off of the database file
   30671 ** and onto a proxy file on the local file system.
   30672 **
   30673 **
   30674 ** Using proxy locks
   30675 ** -----------------
   30676 **
   30677 ** C APIs
   30678 **
   30679 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   30680 **                       <proxy_path> | ":auto:");
   30681 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   30682 **
   30683 **
   30684 ** SQL pragmas
   30685 **
   30686 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   30687 **  PRAGMA [database.]lock_proxy_file
   30688 **
   30689 ** Specifying ":auto:" means that if there is a conch file with a matching
   30690 ** host ID in it, the proxy path in the conch file will be used, otherwise
   30691 ** a proxy path based on the user's temp dir
   30692 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   30693 ** actual proxy file name is generated from the name and path of the
   30694 ** database file.  For example:
   30695 **
   30696 **       For database path "/Users/me/foo.db"
   30697 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   30698 **
   30699 ** Once a lock proxy is configured for a database connection, it can not
   30700 ** be removed, however it may be switched to a different proxy path via
   30701 ** the above APIs (assuming the conch file is not being held by another
   30702 ** connection or process).
   30703 **
   30704 **
   30705 ** How proxy locking works
   30706 ** -----------------------
   30707 **
   30708 ** Proxy file locking relies primarily on two new supporting files:
   30709 **
   30710 **   *  conch file to limit access to the database file to a single host
   30711 **      at a time
   30712 **
   30713 **   *  proxy file to act as a proxy for the advisory locks normally
   30714 **      taken on the database
   30715 **
   30716 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   30717 ** by taking an sqlite-style shared lock on the conch file, reading the
   30718 ** contents and comparing the host's unique host ID (see below) and lock
   30719 ** proxy path against the values stored in the conch.  The conch file is
   30720 ** stored in the same directory as the database file and the file name
   30721 ** is patterned after the database file name as ".<databasename>-conch".
   30722 ** If the conch file does not exist, or it's contents do not match the
   30723 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   30724 ** lock and the conch file contents is updated with the host ID and proxy
   30725 ** path and the lock is downgraded to a shared lock again.  If the conch
   30726 ** is held by another process (with a shared lock), the exclusive lock
   30727 ** will fail and SQLITE_BUSY is returned.
   30728 **
   30729 ** The proxy file - a single-byte file used for all advisory file locks
   30730 ** normally taken on the database file.   This allows for safe sharing
   30731 ** of the database file for multiple readers and writers on the same
   30732 ** host (the conch ensures that they all use the same local lock file).
   30733 **
   30734 ** Requesting the lock proxy does not immediately take the conch, it is
   30735 ** only taken when the first request to lock database file is made.
   30736 ** This matches the semantics of the traditional locking behavior, where
   30737 ** opening a connection to a database file does not take a lock on it.
   30738 ** The shared lock and an open file descriptor are maintained until
   30739 ** the connection to the database is closed.
   30740 **
   30741 ** The proxy file and the lock file are never deleted so they only need
   30742 ** to be created the first time they are used.
   30743 **
   30744 ** Configuration options
   30745 ** ---------------------
   30746 **
   30747 **  SQLITE_PREFER_PROXY_LOCKING
   30748 **
   30749 **       Database files accessed on non-local file systems are
   30750 **       automatically configured for proxy locking, lock files are
   30751 **       named automatically using the same logic as
   30752 **       PRAGMA lock_proxy_file=":auto:"
   30753 **
   30754 **  SQLITE_PROXY_DEBUG
   30755 **
   30756 **       Enables the logging of error messages during host id file
   30757 **       retrieval and creation
   30758 **
   30759 **  LOCKPROXYDIR
   30760 **
   30761 **       Overrides the default directory used for lock proxy files that
   30762 **       are named automatically via the ":auto:" setting
   30763 **
   30764 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   30765 **
   30766 **       Permissions to use when creating a directory for storing the
   30767 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   30768 **
   30769 **
   30770 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   30771 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   30772 ** force proxy locking to be used for every database file opened, and 0
   30773 ** will force automatic proxy locking to be disabled for all database
   30774 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   30775 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   30776 */
   30777 
   30778 /*
   30779 ** Proxy locking is only available on MacOSX
   30780 */
   30781 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   30782 
   30783 /*
   30784 ** The proxyLockingContext has the path and file structures for the remote
   30785 ** and local proxy files in it
   30786 */
   30787 typedef struct proxyLockingContext proxyLockingContext;
   30788 struct proxyLockingContext {
   30789   unixFile *conchFile;         /* Open conch file */
   30790   char *conchFilePath;         /* Name of the conch file */
   30791   unixFile *lockProxy;         /* Open proxy lock file */
   30792   char *lockProxyPath;         /* Name of the proxy lock file */
   30793   char *dbPath;                /* Name of the open file */
   30794   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   30795   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   30796   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   30797 };
   30798 
   30799 /*
   30800 ** The proxy lock file path for the database at dbPath is written into lPath,
   30801 ** which must point to valid, writable memory large enough for a maxLen length
   30802 ** file path.
   30803 */
   30804 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   30805   int len;
   30806   int dbLen;
   30807   int i;
   30808 
   30809 #ifdef LOCKPROXYDIR
   30810   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   30811 #else
   30812 # ifdef _CS_DARWIN_USER_TEMP_DIR
   30813   {
   30814     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   30815       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   30816                lPath, errno, getpid()));
   30817       return SQLITE_IOERR_LOCK;
   30818     }
   30819     len = strlcat(lPath, "sqliteplocks", maxLen);
   30820   }
   30821 # else
   30822   len = strlcpy(lPath, "/tmp/", maxLen);
   30823 # endif
   30824 #endif
   30825 
   30826   if( lPath[len-1]!='/' ){
   30827     len = strlcat(lPath, "/", maxLen);
   30828   }
   30829 
   30830   /* transform the db path to a unique cache name */
   30831   dbLen = (int)strlen(dbPath);
   30832   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   30833     char c = dbPath[i];
   30834     lPath[i+len] = (c=='/')?'_':c;
   30835   }
   30836   lPath[i+len]='\0';
   30837   strlcat(lPath, ":auto:", maxLen);
   30838   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   30839   return SQLITE_OK;
   30840 }
   30841 
   30842 /*
   30843  ** Creates the lock file and any missing directories in lockPath
   30844  */
   30845 static int proxyCreateLockPath(const char *lockPath){
   30846   int i, len;
   30847   char buf[MAXPATHLEN];
   30848   int start = 0;
   30849 
   30850   assert(lockPath!=NULL);
   30851   /* try to create all the intermediate directories */
   30852   len = (int)strlen(lockPath);
   30853   buf[0] = lockPath[0];
   30854   for( i=1; i<len; i++ ){
   30855     if( lockPath[i] == '/' && (i - start > 0) ){
   30856       /* only mkdir if leaf dir != "." or "/" or ".." */
   30857       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   30858          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   30859         buf[i]='\0';
   30860         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   30861           int err=errno;
   30862           if( err!=EEXIST ) {
   30863             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   30864                      "'%s' proxy lock path=%s pid=%d\n",
   30865                      buf, strerror(err), lockPath, getpid()));
   30866             return err;
   30867           }
   30868         }
   30869       }
   30870       start=i+1;
   30871     }
   30872     buf[i] = lockPath[i];
   30873   }
   30874   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   30875   return 0;
   30876 }
   30877 
   30878 /*
   30879 ** Create a new VFS file descriptor (stored in memory obtained from
   30880 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   30881 **
   30882 ** The caller is responsible not only for closing the file descriptor
   30883 ** but also for freeing the memory associated with the file descriptor.
   30884 */
   30885 static int proxyCreateUnixFile(
   30886     const char *path,        /* path for the new unixFile */
   30887     unixFile **ppFile,       /* unixFile created and returned by ref */
   30888     int islockfile           /* if non zero missing dirs will be created */
   30889 ) {
   30890   int fd = -1;
   30891   unixFile *pNew;
   30892   int rc = SQLITE_OK;
   30893   int openFlags = O_RDWR | O_CREAT;
   30894   sqlite3_vfs dummyVfs;
   30895   int terrno = 0;
   30896   UnixUnusedFd *pUnused = NULL;
   30897 
   30898   /* 1. first try to open/create the file
   30899   ** 2. if that fails, and this is a lock file (not-conch), try creating
   30900   ** the parent directories and then try again.
   30901   ** 3. if that fails, try to open the file read-only
   30902   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   30903   */
   30904   pUnused = findReusableFd(path, openFlags);
   30905   if( pUnused ){
   30906     fd = pUnused->fd;
   30907   }else{
   30908     pUnused = sqlite3_malloc(sizeof(*pUnused));
   30909     if( !pUnused ){
   30910       return SQLITE_NOMEM;
   30911     }
   30912   }
   30913   if( fd<0 ){
   30914     fd = robust_open(path, openFlags, 0);
   30915     terrno = errno;
   30916     if( fd<0 && errno==ENOENT && islockfile ){
   30917       if( proxyCreateLockPath(path) == SQLITE_OK ){
   30918         fd = robust_open(path, openFlags, 0);
   30919       }
   30920     }
   30921   }
   30922   if( fd<0 ){
   30923     openFlags = O_RDONLY;
   30924     fd = robust_open(path, openFlags, 0);
   30925     terrno = errno;
   30926   }
   30927   if( fd<0 ){
   30928     if( islockfile ){
   30929       return SQLITE_BUSY;
   30930     }
   30931     switch (terrno) {
   30932       case EACCES:
   30933         return SQLITE_PERM;
   30934       case EIO:
   30935         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   30936       default:
   30937         return SQLITE_CANTOPEN_BKPT;
   30938     }
   30939   }
   30940 
   30941   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   30942   if( pNew==NULL ){
   30943     rc = SQLITE_NOMEM;
   30944     goto end_create_proxy;
   30945   }
   30946   memset(pNew, 0, sizeof(unixFile));
   30947   pNew->openFlags = openFlags;
   30948   memset(&dummyVfs, 0, sizeof(dummyVfs));
   30949   dummyVfs.pAppData = (void*)&autolockIoFinder;
   30950   dummyVfs.zName = "dummy";
   30951   pUnused->fd = fd;
   30952   pUnused->flags = openFlags;
   30953   pNew->pUnused = pUnused;
   30954 
   30955   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   30956   if( rc==SQLITE_OK ){
   30957     *ppFile = pNew;
   30958     return SQLITE_OK;
   30959   }
   30960 end_create_proxy:
   30961   robust_close(pNew, fd, __LINE__);
   30962   sqlite3_free(pNew);
   30963   sqlite3_free(pUnused);
   30964   return rc;
   30965 }
   30966 
   30967 #ifdef SQLITE_TEST
   30968 /* simulate multiple hosts by creating unique hostid file paths */
   30969 SQLITE_API int sqlite3_hostid_num = 0;
   30970 #endif
   30971 
   30972 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   30973 
   30974 /* Not always defined in the headers as it ought to be */
   30975 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   30976 
   30977 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   30978 ** bytes of writable memory.
   30979 */
   30980 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   30981   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   30982   memset(pHostID, 0, PROXY_HOSTIDLEN);
   30983 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   30984                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   30985   {
   30986     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
   30987     if( gethostuuid(pHostID, &timeout) ){
   30988       int err = errno;
   30989       if( pError ){
   30990         *pError = err;
   30991       }
   30992       return SQLITE_IOERR;
   30993     }
   30994   }
   30995 #else
   30996   UNUSED_PARAMETER(pError);
   30997 #endif
   30998 #ifdef SQLITE_TEST
   30999   /* simulate multiple hosts by creating unique hostid file paths */
   31000   if( sqlite3_hostid_num != 0){
   31001     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   31002   }
   31003 #endif
   31004 
   31005   return SQLITE_OK;
   31006 }
   31007 
   31008 /* The conch file contains the header, host id and lock file path
   31009  */
   31010 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   31011 #define PROXY_HEADERLEN    1   /* conch file header length */
   31012 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   31013 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   31014 
   31015 /*
   31016 ** Takes an open conch file, copies the contents to a new path and then moves
   31017 ** it back.  The newly created file's file descriptor is assigned to the
   31018 ** conch file structure and finally the original conch file descriptor is
   31019 ** closed.  Returns zero if successful.
   31020 */
   31021 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   31022   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31023   unixFile *conchFile = pCtx->conchFile;
   31024   char tPath[MAXPATHLEN];
   31025   char buf[PROXY_MAXCONCHLEN];
   31026   char *cPath = pCtx->conchFilePath;
   31027   size_t readLen = 0;
   31028   size_t pathLen = 0;
   31029   char errmsg[64] = "";
   31030   int fd = -1;
   31031   int rc = -1;
   31032   UNUSED_PARAMETER(myHostID);
   31033 
   31034   /* create a new path by replace the trailing '-conch' with '-break' */
   31035   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   31036   if( pathLen>MAXPATHLEN || pathLen<6 ||
   31037      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   31038     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   31039     goto end_breaklock;
   31040   }
   31041   /* read the conch content */
   31042   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   31043   if( readLen<PROXY_PATHINDEX ){
   31044     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   31045     goto end_breaklock;
   31046   }
   31047   /* write it out to the temporary break file */
   31048   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
   31049   if( fd<0 ){
   31050     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   31051     goto end_breaklock;
   31052   }
   31053   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   31054     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   31055     goto end_breaklock;
   31056   }
   31057   if( rename(tPath, cPath) ){
   31058     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   31059     goto end_breaklock;
   31060   }
   31061   rc = 0;
   31062   fprintf(stderr, "broke stale lock on %s\n", cPath);
   31063   robust_close(pFile, conchFile->h, __LINE__);
   31064   conchFile->h = fd;
   31065   conchFile->openFlags = O_RDWR | O_CREAT;
   31066 
   31067 end_breaklock:
   31068   if( rc ){
   31069     if( fd>=0 ){
   31070       osUnlink(tPath);
   31071       robust_close(pFile, fd, __LINE__);
   31072     }
   31073     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   31074   }
   31075   return rc;
   31076 }
   31077 
   31078 /* Take the requested lock on the conch file and break a stale lock if the
   31079 ** host id matches.
   31080 */
   31081 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   31082   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31083   unixFile *conchFile = pCtx->conchFile;
   31084   int rc = SQLITE_OK;
   31085   int nTries = 0;
   31086   struct timespec conchModTime;
   31087 
   31088   memset(&conchModTime, 0, sizeof(conchModTime));
   31089   do {
   31090     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31091     nTries ++;
   31092     if( rc==SQLITE_BUSY ){
   31093       /* If the lock failed (busy):
   31094        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   31095        * 2nd try: fail if the mod time changed or host id is different, wait
   31096        *           10 sec and try again
   31097        * 3rd try: break the lock unless the mod time has changed.
   31098        */
   31099       struct stat buf;
   31100       if( osFstat(conchFile->h, &buf) ){
   31101         pFile->lastErrno = errno;
   31102         return SQLITE_IOERR_LOCK;
   31103       }
   31104 
   31105       if( nTries==1 ){
   31106         conchModTime = buf.st_mtimespec;
   31107         usleep(500000); /* wait 0.5 sec and try the lock again*/
   31108         continue;
   31109       }
   31110 
   31111       assert( nTries>1 );
   31112       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   31113          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   31114         return SQLITE_BUSY;
   31115       }
   31116 
   31117       if( nTries==2 ){
   31118         char tBuf[PROXY_MAXCONCHLEN];
   31119         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   31120         if( len<0 ){
   31121           pFile->lastErrno = errno;
   31122           return SQLITE_IOERR_LOCK;
   31123         }
   31124         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   31125           /* don't break the lock if the host id doesn't match */
   31126           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   31127             return SQLITE_BUSY;
   31128           }
   31129         }else{
   31130           /* don't break the lock on short read or a version mismatch */
   31131           return SQLITE_BUSY;
   31132         }
   31133         usleep(10000000); /* wait 10 sec and try the lock again */
   31134         continue;
   31135       }
   31136 
   31137       assert( nTries==3 );
   31138       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   31139         rc = SQLITE_OK;
   31140         if( lockType==EXCLUSIVE_LOCK ){
   31141           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   31142         }
   31143         if( !rc ){
   31144           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   31145         }
   31146       }
   31147     }
   31148   } while( rc==SQLITE_BUSY && nTries<3 );
   31149 
   31150   return rc;
   31151 }
   31152 
   31153 /* Takes the conch by taking a shared lock and read the contents conch, if
   31154 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   31155 ** lockPath means that the lockPath in the conch file will be used if the
   31156 ** host IDs match, or a new lock path will be generated automatically
   31157 ** and written to the conch file.
   31158 */
   31159 static int proxyTakeConch(unixFile *pFile){
   31160   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31161 
   31162   if( pCtx->conchHeld!=0 ){
   31163     return SQLITE_OK;
   31164   }else{
   31165     unixFile *conchFile = pCtx->conchFile;
   31166     uuid_t myHostID;
   31167     int pError = 0;
   31168     char readBuf[PROXY_MAXCONCHLEN];
   31169     char lockPath[MAXPATHLEN];
   31170     char *tempLockPath = NULL;
   31171     int rc = SQLITE_OK;
   31172     int createConch = 0;
   31173     int hostIdMatch = 0;
   31174     int readLen = 0;
   31175     int tryOldLockPath = 0;
   31176     int forceNewLockPath = 0;
   31177 
   31178     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   31179              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   31180 
   31181     rc = proxyGetHostID(myHostID, &pError);
   31182     if( (rc&0xff)==SQLITE_IOERR ){
   31183       pFile->lastErrno = pError;
   31184       goto end_takeconch;
   31185     }
   31186     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   31187     if( rc!=SQLITE_OK ){
   31188       goto end_takeconch;
   31189     }
   31190     /* read the existing conch file */
   31191     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   31192     if( readLen<0 ){
   31193       /* I/O error: lastErrno set by seekAndRead */
   31194       pFile->lastErrno = conchFile->lastErrno;
   31195       rc = SQLITE_IOERR_READ;
   31196       goto end_takeconch;
   31197     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   31198              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   31199       /* a short read or version format mismatch means we need to create a new
   31200       ** conch file.
   31201       */
   31202       createConch = 1;
   31203     }
   31204     /* if the host id matches and the lock path already exists in the conch
   31205     ** we'll try to use the path there, if we can't open that path, we'll
   31206     ** retry with a new auto-generated path
   31207     */
   31208     do { /* in case we need to try again for an :auto: named lock file */
   31209 
   31210       if( !createConch && !forceNewLockPath ){
   31211         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   31212                                   PROXY_HOSTIDLEN);
   31213         /* if the conch has data compare the contents */
   31214         if( !pCtx->lockProxyPath ){
   31215           /* for auto-named local lock file, just check the host ID and we'll
   31216            ** use the local lock file path that's already in there
   31217            */
   31218           if( hostIdMatch ){
   31219             size_t pathLen = (readLen - PROXY_PATHINDEX);
   31220 
   31221             if( pathLen>=MAXPATHLEN ){
   31222               pathLen=MAXPATHLEN-1;
   31223             }
   31224             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   31225             lockPath[pathLen] = 0;
   31226             tempLockPath = lockPath;
   31227             tryOldLockPath = 1;
   31228             /* create a copy of the lock path if the conch is taken */
   31229             goto end_takeconch;
   31230           }
   31231         }else if( hostIdMatch
   31232                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   31233                            readLen-PROXY_PATHINDEX)
   31234         ){
   31235           /* conch host and lock path match */
   31236           goto end_takeconch;
   31237         }
   31238       }
   31239 
   31240       /* if the conch isn't writable and doesn't match, we can't take it */
   31241       if( (conchFile->openFlags&O_RDWR) == 0 ){
   31242         rc = SQLITE_BUSY;
   31243         goto end_takeconch;
   31244       }
   31245 
   31246       /* either the conch didn't match or we need to create a new one */
   31247       if( !pCtx->lockProxyPath ){
   31248         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   31249         tempLockPath = lockPath;
   31250         /* create a copy of the lock path _only_ if the conch is taken */
   31251       }
   31252 
   31253       /* update conch with host and path (this will fail if other process
   31254       ** has a shared lock already), if the host id matches, use the big
   31255       ** stick.
   31256       */
   31257       futimes(conchFile->h, NULL);
   31258       if( hostIdMatch && !createConch ){
   31259         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   31260           /* We are trying for an exclusive lock but another thread in this
   31261            ** same process is still holding a shared lock. */
   31262           rc = SQLITE_BUSY;
   31263         } else {
   31264           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   31265         }
   31266       }else{
   31267         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   31268       }
   31269       if( rc==SQLITE_OK ){
   31270         char writeBuffer[PROXY_MAXCONCHLEN];
   31271         int writeSize = 0;
   31272 
   31273         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   31274         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   31275         if( pCtx->lockProxyPath!=NULL ){
   31276           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   31277         }else{
   31278           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   31279         }
   31280         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   31281         robust_ftruncate(conchFile->h, writeSize);
   31282         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   31283         fsync(conchFile->h);
   31284         /* If we created a new conch file (not just updated the contents of a
   31285          ** valid conch file), try to match the permissions of the database
   31286          */
   31287         if( rc==SQLITE_OK && createConch ){
   31288           struct stat buf;
   31289           int err = osFstat(pFile->h, &buf);
   31290           if( err==0 ){
   31291             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   31292                                         S_IROTH|S_IWOTH);
   31293             /* try to match the database file R/W permissions, ignore failure */
   31294 #ifndef SQLITE_PROXY_DEBUG
   31295             osFchmod(conchFile->h, cmode);
   31296 #else
   31297             do{
   31298               rc = osFchmod(conchFile->h, cmode);
   31299             }while( rc==(-1) && errno==EINTR );
   31300             if( rc!=0 ){
   31301               int code = errno;
   31302               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   31303                       cmode, code, strerror(code));
   31304             } else {
   31305               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   31306             }
   31307           }else{
   31308             int code = errno;
   31309             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   31310                     err, code, strerror(code));
   31311 #endif
   31312           }
   31313         }
   31314       }
   31315       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   31316 
   31317     end_takeconch:
   31318       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   31319       if( rc==SQLITE_OK && pFile->openFlags ){
   31320         int fd;
   31321         if( pFile->h>=0 ){
   31322           robust_close(pFile, pFile->h, __LINE__);
   31323         }
   31324         pFile->h = -1;
   31325         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
   31326         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   31327         if( fd>=0 ){
   31328           pFile->h = fd;
   31329         }else{
   31330           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   31331            during locking */
   31332         }
   31333       }
   31334       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   31335         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   31336         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   31337         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   31338           /* we couldn't create the proxy lock file with the old lock file path
   31339            ** so try again via auto-naming
   31340            */
   31341           forceNewLockPath = 1;
   31342           tryOldLockPath = 0;
   31343           continue; /* go back to the do {} while start point, try again */
   31344         }
   31345       }
   31346       if( rc==SQLITE_OK ){
   31347         /* Need to make a copy of path if we extracted the value
   31348          ** from the conch file or the path was allocated on the stack
   31349          */
   31350         if( tempLockPath ){
   31351           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   31352           if( !pCtx->lockProxyPath ){
   31353             rc = SQLITE_NOMEM;
   31354           }
   31355         }
   31356       }
   31357       if( rc==SQLITE_OK ){
   31358         pCtx->conchHeld = 1;
   31359 
   31360         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   31361           afpLockingContext *afpCtx;
   31362           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   31363           afpCtx->dbPath = pCtx->lockProxyPath;
   31364         }
   31365       } else {
   31366         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31367       }
   31368       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   31369                rc==SQLITE_OK?"ok":"failed"));
   31370       return rc;
   31371     } while (1); /* in case we need to retry the :auto: lock file -
   31372                  ** we should never get here except via the 'continue' call. */
   31373   }
   31374 }
   31375 
   31376 /*
   31377 ** If pFile holds a lock on a conch file, then release that lock.
   31378 */
   31379 static int proxyReleaseConch(unixFile *pFile){
   31380   int rc = SQLITE_OK;         /* Subroutine return code */
   31381   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   31382   unixFile *conchFile;        /* Name of the conch file */
   31383 
   31384   pCtx = (proxyLockingContext *)pFile->lockingContext;
   31385   conchFile = pCtx->conchFile;
   31386   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   31387            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   31388            getpid()));
   31389   if( pCtx->conchHeld>0 ){
   31390     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   31391   }
   31392   pCtx->conchHeld = 0;
   31393   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   31394            (rc==SQLITE_OK ? "ok" : "failed")));
   31395   return rc;
   31396 }
   31397 
   31398 /*
   31399 ** Given the name of a database file, compute the name of its conch file.
   31400 ** Store the conch filename in memory obtained from sqlite3_malloc().
   31401 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   31402 ** or SQLITE_NOMEM if unable to obtain memory.
   31403 **
   31404 ** The caller is responsible for ensuring that the allocated memory
   31405 ** space is eventually freed.
   31406 **
   31407 ** *pConchPath is set to NULL if a memory allocation error occurs.
   31408 */
   31409 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   31410   int i;                        /* Loop counter */
   31411   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   31412   char *conchPath;              /* buffer in which to construct conch name */
   31413 
   31414   /* Allocate space for the conch filename and initialize the name to
   31415   ** the name of the original database file. */
   31416   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   31417   if( conchPath==0 ){
   31418     return SQLITE_NOMEM;
   31419   }
   31420   memcpy(conchPath, dbPath, len+1);
   31421 
   31422   /* now insert a "." before the last / character */
   31423   for( i=(len-1); i>=0; i-- ){
   31424     if( conchPath[i]=='/' ){
   31425       i++;
   31426       break;
   31427     }
   31428   }
   31429   conchPath[i]='.';
   31430   while ( i<len ){
   31431     conchPath[i+1]=dbPath[i];
   31432     i++;
   31433   }
   31434 
   31435   /* append the "-conch" suffix to the file */
   31436   memcpy(&conchPath[i+1], "-conch", 7);
   31437   assert( (int)strlen(conchPath) == len+7 );
   31438 
   31439   return SQLITE_OK;
   31440 }
   31441 
   31442 
   31443 /* Takes a fully configured proxy locking-style unix file and switches
   31444 ** the local lock file path
   31445 */
   31446 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   31447   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31448   char *oldPath = pCtx->lockProxyPath;
   31449   int rc = SQLITE_OK;
   31450 
   31451   if( pFile->eFileLock!=NO_LOCK ){
   31452     return SQLITE_BUSY;
   31453   }
   31454 
   31455   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   31456   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   31457     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   31458     return SQLITE_OK;
   31459   }else{
   31460     unixFile *lockProxy = pCtx->lockProxy;
   31461     pCtx->lockProxy=NULL;
   31462     pCtx->conchHeld = 0;
   31463     if( lockProxy!=NULL ){
   31464       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   31465       if( rc ) return rc;
   31466       sqlite3_free(lockProxy);
   31467     }
   31468     sqlite3_free(oldPath);
   31469     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   31470   }
   31471 
   31472   return rc;
   31473 }
   31474 
   31475 /*
   31476 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   31477 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   31478 **
   31479 ** This routine find the filename associated with pFile and writes it
   31480 ** int dbPath.
   31481 */
   31482 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   31483 #if defined(__APPLE__)
   31484   if( pFile->pMethod == &afpIoMethods ){
   31485     /* afp style keeps a reference to the db path in the filePath field
   31486     ** of the struct */
   31487     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31488     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   31489   } else
   31490 #endif
   31491   if( pFile->pMethod == &dotlockIoMethods ){
   31492     /* dot lock style uses the locking context to store the dot lock
   31493     ** file path */
   31494     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   31495     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   31496   }else{
   31497     /* all other styles use the locking context to store the db file path */
   31498     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   31499     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   31500   }
   31501   return SQLITE_OK;
   31502 }
   31503 
   31504 /*
   31505 ** Takes an already filled in unix file and alters it so all file locking
   31506 ** will be performed on the local proxy lock file.  The following fields
   31507 ** are preserved in the locking context so that they can be restored and
   31508 ** the unix structure properly cleaned up at close time:
   31509 **  ->lockingContext
   31510 **  ->pMethod
   31511 */
   31512 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   31513   proxyLockingContext *pCtx;
   31514   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   31515   char *lockPath=NULL;
   31516   int rc = SQLITE_OK;
   31517 
   31518   if( pFile->eFileLock!=NO_LOCK ){
   31519     return SQLITE_BUSY;
   31520   }
   31521   proxyGetDbPathForUnixFile(pFile, dbPath);
   31522   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   31523     lockPath=NULL;
   31524   }else{
   31525     lockPath=(char *)path;
   31526   }
   31527 
   31528   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   31529            (lockPath ? lockPath : ":auto:"), getpid()));
   31530 
   31531   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   31532   if( pCtx==0 ){
   31533     return SQLITE_NOMEM;
   31534   }
   31535   memset(pCtx, 0, sizeof(*pCtx));
   31536 
   31537   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   31538   if( rc==SQLITE_OK ){
   31539     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   31540     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   31541       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   31542       ** (c) the file system is read-only, then enable no-locking access.
   31543       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   31544       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   31545       */
   31546       struct statfs fsInfo;
   31547       struct stat conchInfo;
   31548       int goLockless = 0;
   31549 
   31550       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   31551         int err = errno;
   31552         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   31553           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   31554         }
   31555       }
   31556       if( goLockless ){
   31557         pCtx->conchHeld = -1; /* read only FS/ lockless */
   31558         rc = SQLITE_OK;
   31559       }
   31560     }
   31561   }
   31562   if( rc==SQLITE_OK && lockPath ){
   31563     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   31564   }
   31565 
   31566   if( rc==SQLITE_OK ){
   31567     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   31568     if( pCtx->dbPath==NULL ){
   31569       rc = SQLITE_NOMEM;
   31570     }
   31571   }
   31572   if( rc==SQLITE_OK ){
   31573     /* all memory is allocated, proxys are created and assigned,
   31574     ** switch the locking context and pMethod then return.
   31575     */
   31576     pCtx->oldLockingContext = pFile->lockingContext;
   31577     pFile->lockingContext = pCtx;
   31578     pCtx->pOldMethod = pFile->pMethod;
   31579     pFile->pMethod = &proxyIoMethods;
   31580   }else{
   31581     if( pCtx->conchFile ){
   31582       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   31583       sqlite3_free(pCtx->conchFile);
   31584     }
   31585     sqlite3DbFree(0, pCtx->lockProxyPath);
   31586     sqlite3_free(pCtx->conchFilePath);
   31587     sqlite3_free(pCtx);
   31588   }
   31589   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   31590            (rc==SQLITE_OK ? "ok" : "failed")));
   31591   return rc;
   31592 }
   31593 
   31594 
   31595 /*
   31596 ** This routine handles sqlite3_file_control() calls that are specific
   31597 ** to proxy locking.
   31598 */
   31599 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   31600   switch( op ){
   31601     case SQLITE_GET_LOCKPROXYFILE: {
   31602       unixFile *pFile = (unixFile*)id;
   31603       if( pFile->pMethod == &proxyIoMethods ){
   31604         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   31605         proxyTakeConch(pFile);
   31606         if( pCtx->lockProxyPath ){
   31607           *(const char **)pArg = pCtx->lockProxyPath;
   31608         }else{
   31609           *(const char **)pArg = ":auto: (not held)";
   31610         }
   31611       } else {
   31612         *(const char **)pArg = NULL;
   31613       }
   31614       return SQLITE_OK;
   31615     }
   31616     case SQLITE_SET_LOCKPROXYFILE: {
   31617       unixFile *pFile = (unixFile*)id;
   31618       int rc = SQLITE_OK;
   31619       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   31620       if( pArg==NULL || (const char *)pArg==0 ){
   31621         if( isProxyStyle ){
   31622           /* turn off proxy locking - not supported */
   31623           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   31624         }else{
   31625           /* turn off proxy locking - already off - NOOP */
   31626           rc = SQLITE_OK;
   31627         }
   31628       }else{
   31629         const char *proxyPath = (const char *)pArg;
   31630         if( isProxyStyle ){
   31631           proxyLockingContext *pCtx =
   31632             (proxyLockingContext*)pFile->lockingContext;
   31633           if( !strcmp(pArg, ":auto:")
   31634            || (pCtx->lockProxyPath &&
   31635                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   31636           ){
   31637             rc = SQLITE_OK;
   31638           }else{
   31639             rc = switchLockProxyPath(pFile, proxyPath);
   31640           }
   31641         }else{
   31642           /* turn on proxy file locking */
   31643           rc = proxyTransformUnixFile(pFile, proxyPath);
   31644         }
   31645       }
   31646       return rc;
   31647     }
   31648     default: {
   31649       assert( 0 );  /* The call assures that only valid opcodes are sent */
   31650     }
   31651   }
   31652   /*NOTREACHED*/
   31653   return SQLITE_ERROR;
   31654 }
   31655 
   31656 /*
   31657 ** Within this division (the proxying locking implementation) the procedures
   31658 ** above this point are all utilities.  The lock-related methods of the
   31659 ** proxy-locking sqlite3_io_method object follow.
   31660 */
   31661 
   31662 
   31663 /*
   31664 ** This routine checks if there is a RESERVED lock held on the specified
   31665 ** file by this or any other process. If such a lock is held, set *pResOut
   31666 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   31667 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   31668 */
   31669 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   31670   unixFile *pFile = (unixFile*)id;
   31671   int rc = proxyTakeConch(pFile);
   31672   if( rc==SQLITE_OK ){
   31673     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31674     if( pCtx->conchHeld>0 ){
   31675       unixFile *proxy = pCtx->lockProxy;
   31676       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   31677     }else{ /* conchHeld < 0 is lockless */
   31678       pResOut=0;
   31679     }
   31680   }
   31681   return rc;
   31682 }
   31683 
   31684 /*
   31685 ** Lock the file with the lock specified by parameter eFileLock - one
   31686 ** of the following:
   31687 **
   31688 **     (1) SHARED_LOCK
   31689 **     (2) RESERVED_LOCK
   31690 **     (3) PENDING_LOCK
   31691 **     (4) EXCLUSIVE_LOCK
   31692 **
   31693 ** Sometimes when requesting one lock state, additional lock states
   31694 ** are inserted in between.  The locking might fail on one of the later
   31695 ** transitions leaving the lock state different from what it started but
   31696 ** still short of its goal.  The following chart shows the allowed
   31697 ** transitions and the inserted intermediate states:
   31698 **
   31699 **    UNLOCKED -> SHARED
   31700 **    SHARED -> RESERVED
   31701 **    SHARED -> (PENDING) -> EXCLUSIVE
   31702 **    RESERVED -> (PENDING) -> EXCLUSIVE
   31703 **    PENDING -> EXCLUSIVE
   31704 **
   31705 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   31706 ** routine to lower a locking level.
   31707 */
   31708 static int proxyLock(sqlite3_file *id, int eFileLock) {
   31709   unixFile *pFile = (unixFile*)id;
   31710   int rc = proxyTakeConch(pFile);
   31711   if( rc==SQLITE_OK ){
   31712     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31713     if( pCtx->conchHeld>0 ){
   31714       unixFile *proxy = pCtx->lockProxy;
   31715       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   31716       pFile->eFileLock = proxy->eFileLock;
   31717     }else{
   31718       /* conchHeld < 0 is lockless */
   31719     }
   31720   }
   31721   return rc;
   31722 }
   31723 
   31724 
   31725 /*
   31726 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   31727 ** must be either NO_LOCK or SHARED_LOCK.
   31728 **
   31729 ** If the locking level of the file descriptor is already at or below
   31730 ** the requested locking level, this routine is a no-op.
   31731 */
   31732 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   31733   unixFile *pFile = (unixFile*)id;
   31734   int rc = proxyTakeConch(pFile);
   31735   if( rc==SQLITE_OK ){
   31736     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31737     if( pCtx->conchHeld>0 ){
   31738       unixFile *proxy = pCtx->lockProxy;
   31739       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   31740       pFile->eFileLock = proxy->eFileLock;
   31741     }else{
   31742       /* conchHeld < 0 is lockless */
   31743     }
   31744   }
   31745   return rc;
   31746 }
   31747 
   31748 /*
   31749 ** Close a file that uses proxy locks.
   31750 */
   31751 static int proxyClose(sqlite3_file *id) {
   31752   if( id ){
   31753     unixFile *pFile = (unixFile*)id;
   31754     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   31755     unixFile *lockProxy = pCtx->lockProxy;
   31756     unixFile *conchFile = pCtx->conchFile;
   31757     int rc = SQLITE_OK;
   31758 
   31759     if( lockProxy ){
   31760       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   31761       if( rc ) return rc;
   31762       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   31763       if( rc ) return rc;
   31764       sqlite3_free(lockProxy);
   31765       pCtx->lockProxy = 0;
   31766     }
   31767     if( conchFile ){
   31768       if( pCtx->conchHeld ){
   31769         rc = proxyReleaseConch(pFile);
   31770         if( rc ) return rc;
   31771       }
   31772       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   31773       if( rc ) return rc;
   31774       sqlite3_free(conchFile);
   31775     }
   31776     sqlite3DbFree(0, pCtx->lockProxyPath);
   31777     sqlite3_free(pCtx->conchFilePath);
   31778     sqlite3DbFree(0, pCtx->dbPath);
   31779     /* restore the original locking context and pMethod then close it */
   31780     pFile->lockingContext = pCtx->oldLockingContext;
   31781     pFile->pMethod = pCtx->pOldMethod;
   31782     sqlite3_free(pCtx);
   31783     return pFile->pMethod->xClose(id);
   31784   }
   31785   return SQLITE_OK;
   31786 }
   31787 
   31788 
   31789 
   31790 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   31791 /*
   31792 ** The proxy locking style is intended for use with AFP filesystems.
   31793 ** And since AFP is only supported on MacOSX, the proxy locking is also
   31794 ** restricted to MacOSX.
   31795 **
   31796 **
   31797 ******************* End of the proxy lock implementation **********************
   31798 ******************************************************************************/
   31799 
   31800 /*
   31801 ** Initialize the operating system interface.
   31802 **
   31803 ** This routine registers all VFS implementations for unix-like operating
   31804 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   31805 ** should be the only routines in this file that are visible from other
   31806 ** files.
   31807 **
   31808 ** This routine is called once during SQLite initialization and by a
   31809 ** single thread.  The memory allocation and mutex subsystems have not
   31810 ** necessarily been initialized when this routine is called, and so they
   31811 ** should not be used.
   31812 */
   31813 SQLITE_API int sqlite3_os_init(void){
   31814   /*
   31815   ** The following macro defines an initializer for an sqlite3_vfs object.
   31816   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   31817   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   31818   ** silly C90 rules prohibit a void* from being cast to a function pointer
   31819   ** and so we have to go through the intermediate pointer to avoid problems
   31820   ** when compiling with -pedantic-errors on GCC.)
   31821   **
   31822   ** The FINDER parameter to this macro is the name of the pointer to the
   31823   ** finder-function.  The finder-function returns a pointer to the
   31824   ** sqlite_io_methods object that implements the desired locking
   31825   ** behaviors.  See the division above that contains the IOMETHODS
   31826   ** macro for addition information on finder-functions.
   31827   **
   31828   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   31829   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   31830   ** more than that; it looks at the filesystem type that hosts the
   31831   ** database file and tries to choose an locking method appropriate for
   31832   ** that filesystem time.
   31833   */
   31834   #define UNIXVFS(VFSNAME, FINDER) {                        \
   31835     3,                    /* iVersion */                    \
   31836     sizeof(unixFile),     /* szOsFile */                    \
   31837     MAX_PATHNAME,         /* mxPathname */                  \
   31838     0,                    /* pNext */                       \
   31839     VFSNAME,              /* zName */                       \
   31840     (void*)&FINDER,       /* pAppData */                    \
   31841     unixOpen,             /* xOpen */                       \
   31842     unixDelete,           /* xDelete */                     \
   31843     unixAccess,           /* xAccess */                     \
   31844     unixFullPathname,     /* xFullPathname */               \
   31845     unixDlOpen,           /* xDlOpen */                     \
   31846     unixDlError,          /* xDlError */                    \
   31847     unixDlSym,            /* xDlSym */                      \
   31848     unixDlClose,          /* xDlClose */                    \
   31849     unixRandomness,       /* xRandomness */                 \
   31850     unixSleep,            /* xSleep */                      \
   31851     unixCurrentTime,      /* xCurrentTime */                \
   31852     unixGetLastError,     /* xGetLastError */               \
   31853     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   31854     unixSetSystemCall,    /* xSetSystemCall */              \
   31855     unixGetSystemCall,    /* xGetSystemCall */              \
   31856     unixNextSystemCall,   /* xNextSystemCall */             \
   31857   }
   31858 
   31859   /*
   31860   ** All default VFSes for unix are contained in the following array.
   31861   **
   31862   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   31863   ** by the SQLite core when the VFS is registered.  So the following
   31864   ** array cannot be const.
   31865   */
   31866   static sqlite3_vfs aVfs[] = {
   31867 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   31868     UNIXVFS("unix",          autolockIoFinder ),
   31869 #else
   31870     UNIXVFS("unix",          posixIoFinder ),
   31871 #endif
   31872     UNIXVFS("unix-none",     nolockIoFinder ),
   31873     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   31874     UNIXVFS("unix-excl",     posixIoFinder ),
   31875 #if OS_VXWORKS
   31876     UNIXVFS("unix-namedsem", semIoFinder ),
   31877 #endif
   31878 #if SQLITE_ENABLE_LOCKING_STYLE
   31879     UNIXVFS("unix-posix",    posixIoFinder ),
   31880 #if !OS_VXWORKS
   31881     UNIXVFS("unix-flock",    flockIoFinder ),
   31882 #endif
   31883 #endif
   31884 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   31885     UNIXVFS("unix-afp",      afpIoFinder ),
   31886     UNIXVFS("unix-nfs",      nfsIoFinder ),
   31887     UNIXVFS("unix-proxy",    proxyIoFinder ),
   31888 #endif
   31889   };
   31890   unsigned int i;          /* Loop counter */
   31891 
   31892   /* Double-check that the aSyscall[] array has been constructed
   31893   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   31894   assert( ArraySize(aSyscall)==22 );
   31895 
   31896   /* Register all VFSes defined in the aVfs[] array */
   31897   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   31898     sqlite3_vfs_register(&aVfs[i], i==0);
   31899   }
   31900   return SQLITE_OK;
   31901 }
   31902 
   31903 /*
   31904 ** Shutdown the operating system interface.
   31905 **
   31906 ** Some operating systems might need to do some cleanup in this routine,
   31907 ** to release dynamically allocated objects.  But not on unix.
   31908 ** This routine is a no-op for unix.
   31909 */
   31910 SQLITE_API int sqlite3_os_end(void){
   31911   return SQLITE_OK;
   31912 }
   31913 
   31914 #endif /* SQLITE_OS_UNIX */
   31915 
   31916 /************** End of os_unix.c *********************************************/
   31917 /************** Begin file os_win.c ******************************************/
   31918 /*
   31919 ** 2004 May 22
   31920 **
   31921 ** The author disclaims copyright to this source code.  In place of
   31922 ** a legal notice, here is a blessing:
   31923 **
   31924 **    May you do good and not evil.
   31925 **    May you find forgiveness for yourself and forgive others.
   31926 **    May you share freely, never taking more than you give.
   31927 **
   31928 ******************************************************************************
   31929 **
   31930 ** This file contains code that is specific to Windows.
   31931 */
   31932 #if SQLITE_OS_WIN               /* This file is used for Windows only */
   31933 
   31934 #ifdef __CYGWIN__
   31935 # include <sys/cygwin.h>
   31936 #endif
   31937 
   31938 /*
   31939 ** Include code that is common to all os_*.c files
   31940 */
   31941 /************** Include os_common.h in the middle of os_win.c ****************/
   31942 /************** Begin file os_common.h ***************************************/
   31943 /*
   31944 ** 2004 May 22
   31945 **
   31946 ** The author disclaims copyright to this source code.  In place of
   31947 ** a legal notice, here is a blessing:
   31948 **
   31949 **    May you do good and not evil.
   31950 **    May you find forgiveness for yourself and forgive others.
   31951 **    May you share freely, never taking more than you give.
   31952 **
   31953 ******************************************************************************
   31954 **
   31955 ** This file contains macros and a little bit of code that is common to
   31956 ** all of the platform-specific files (os_*.c) and is #included into those
   31957 ** files.
   31958 **
   31959 ** This file should be #included by the os_*.c files only.  It is not a
   31960 ** general purpose header file.
   31961 */
   31962 #ifndef _OS_COMMON_H_
   31963 #define _OS_COMMON_H_
   31964 
   31965 /*
   31966 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   31967 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   31968 ** switch.  The following code should catch this problem at compile-time.
   31969 */
   31970 #ifdef MEMORY_DEBUG
   31971 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   31972 #endif
   31973 
   31974 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   31975 # ifndef SQLITE_DEBUG_OS_TRACE
   31976 #   define SQLITE_DEBUG_OS_TRACE 0
   31977 # endif
   31978   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
   31979 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   31980 #else
   31981 # define OSTRACE(X)
   31982 #endif
   31983 
   31984 /*
   31985 ** Macros for performance tracing.  Normally turned off.  Only works
   31986 ** on i486 hardware.
   31987 */
   31988 #ifdef SQLITE_PERFORMANCE_TRACE
   31989 
   31990 /*
   31991 ** hwtime.h contains inline assembler code for implementing
   31992 ** high-performance timing routines.
   31993 */
   31994 /************** Include hwtime.h in the middle of os_common.h ****************/
   31995 /************** Begin file hwtime.h ******************************************/
   31996 /*
   31997 ** 2008 May 27
   31998 **
   31999 ** The author disclaims copyright to this source code.  In place of
   32000 ** a legal notice, here is a blessing:
   32001 **
   32002 **    May you do good and not evil.
   32003 **    May you find forgiveness for yourself and forgive others.
   32004 **    May you share freely, never taking more than you give.
   32005 **
   32006 ******************************************************************************
   32007 **
   32008 ** This file contains inline asm code for retrieving "high-performance"
   32009 ** counters for x86 class CPUs.
   32010 */
   32011 #ifndef _HWTIME_H_
   32012 #define _HWTIME_H_
   32013 
   32014 /*
   32015 ** The following routine only works on pentium-class (or newer) processors.
   32016 ** It uses the RDTSC opcode to read the cycle count value out of the
   32017 ** processor and returns that value.  This can be used for high-res
   32018 ** profiling.
   32019 */
   32020 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   32021       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   32022 
   32023   #if defined(__GNUC__)
   32024 
   32025   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32026      unsigned int lo, hi;
   32027      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   32028      return (sqlite_uint64)hi << 32 | lo;
   32029   }
   32030 
   32031   #elif defined(_MSC_VER)
   32032 
   32033   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   32034      __asm {
   32035         rdtsc
   32036         ret       ; return value at EDX:EAX
   32037      }
   32038   }
   32039 
   32040   #endif
   32041 
   32042 #elif (defined(__GNUC__) && defined(__x86_64__))
   32043 
   32044   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32045       unsigned long val;
   32046       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   32047       return val;
   32048   }
   32049 
   32050 #elif (defined(__GNUC__) && defined(__ppc__))
   32051 
   32052   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   32053       unsigned long long retval;
   32054       unsigned long junk;
   32055       __asm__ __volatile__ ("\n\
   32056           1:      mftbu   %1\n\
   32057                   mftb    %L0\n\
   32058                   mftbu   %0\n\
   32059                   cmpw    %0,%1\n\
   32060                   bne     1b"
   32061                   : "=r" (retval), "=r" (junk));
   32062       return retval;
   32063   }
   32064 
   32065 #else
   32066 
   32067   #error Need implementation of sqlite3Hwtime() for your platform.
   32068 
   32069   /*
   32070   ** To compile without implementing sqlite3Hwtime() for your platform,
   32071   ** you can remove the above #error and use the following
   32072   ** stub function.  You will lose timing support for many
   32073   ** of the debugging and testing utilities, but it should at
   32074   ** least compile and run.
   32075   */
   32076 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   32077 
   32078 #endif
   32079 
   32080 #endif /* !defined(_HWTIME_H_) */
   32081 
   32082 /************** End of hwtime.h **********************************************/
   32083 /************** Continuing where we left off in os_common.h ******************/
   32084 
   32085 static sqlite_uint64 g_start;
   32086 static sqlite_uint64 g_elapsed;
   32087 #define TIMER_START       g_start=sqlite3Hwtime()
   32088 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   32089 #define TIMER_ELAPSED     g_elapsed
   32090 #else
   32091 #define TIMER_START
   32092 #define TIMER_END
   32093 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   32094 #endif
   32095 
   32096 /*
   32097 ** If we compile with the SQLITE_TEST macro set, then the following block
   32098 ** of code will give us the ability to simulate a disk I/O error.  This
   32099 ** is used for testing the I/O recovery logic.
   32100 */
   32101 #ifdef SQLITE_TEST
   32102 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   32103 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   32104 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   32105 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   32106 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   32107 SQLITE_API int sqlite3_diskfull_pending = 0;
   32108 SQLITE_API int sqlite3_diskfull = 0;
   32109 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   32110 #define SimulateIOError(CODE)  \
   32111   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   32112        || sqlite3_io_error_pending-- == 1 )  \
   32113               { local_ioerr(); CODE; }
   32114 static void local_ioerr(){
   32115   IOTRACE(("IOERR\n"));
   32116   sqlite3_io_error_hit++;
   32117   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   32118 }
   32119 #define SimulateDiskfullError(CODE) \
   32120    if( sqlite3_diskfull_pending ){ \
   32121      if( sqlite3_diskfull_pending == 1 ){ \
   32122        local_ioerr(); \
   32123        sqlite3_diskfull = 1; \
   32124        sqlite3_io_error_hit = 1; \
   32125        CODE; \
   32126      }else{ \
   32127        sqlite3_diskfull_pending--; \
   32128      } \
   32129    }
   32130 #else
   32131 #define SimulateIOErrorBenign(X)
   32132 #define SimulateIOError(A)
   32133 #define SimulateDiskfullError(A)
   32134 #endif
   32135 
   32136 /*
   32137 ** When testing, keep a count of the number of open files.
   32138 */
   32139 #ifdef SQLITE_TEST
   32140 SQLITE_API int sqlite3_open_file_count = 0;
   32141 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   32142 #else
   32143 #define OpenCounter(X)
   32144 #endif
   32145 
   32146 #endif /* !defined(_OS_COMMON_H_) */
   32147 
   32148 /************** End of os_common.h *******************************************/
   32149 /************** Continuing where we left off in os_win.c *********************/
   32150 
   32151 /*
   32152 ** Some Microsoft compilers lack this definition.
   32153 */
   32154 #ifndef INVALID_FILE_ATTRIBUTES
   32155 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   32156 #endif
   32157 
   32158 /* Forward references */
   32159 typedef struct winShm winShm;           /* A connection to shared-memory */
   32160 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   32161 
   32162 /*
   32163 ** WinCE lacks native support for file locking so we have to fake it
   32164 ** with some code of our own.
   32165 */
   32166 #if SQLITE_OS_WINCE
   32167 typedef struct winceLock {
   32168   int nReaders;       /* Number of reader locks obtained */
   32169   BOOL bPending;      /* Indicates a pending lock has been obtained */
   32170   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   32171   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   32172 } winceLock;
   32173 #endif
   32174 
   32175 /*
   32176 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   32177 ** portability layer.
   32178 */
   32179 typedef struct winFile winFile;
   32180 struct winFile {
   32181   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   32182   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   32183   HANDLE h;               /* Handle for accessing the file */
   32184   u8 locktype;            /* Type of lock currently held on this file */
   32185   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   32186   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   32187   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   32188   winShm *pShm;           /* Instance of shared memory on this file */
   32189   const char *zPath;      /* Full pathname of this file */
   32190   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   32191 #if SQLITE_OS_WINCE
   32192   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   32193   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   32194   HANDLE hShared;         /* Shared memory segment used for locking */
   32195   winceLock local;        /* Locks obtained by this instance of winFile */
   32196   winceLock *shared;      /* Global shared lock memory for the file  */
   32197 #endif
   32198 };
   32199 
   32200 /*
   32201 ** Allowed values for winFile.ctrlFlags
   32202 */
   32203 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
   32204 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   32205 
   32206 /*
   32207  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   32208  * various Win32 API heap functions instead of our own.
   32209  */
   32210 #ifdef SQLITE_WIN32_MALLOC
   32211 /*
   32212  * The initial size of the Win32-specific heap.  This value may be zero.
   32213  */
   32214 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
   32215 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
   32216                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
   32217 #endif
   32218 
   32219 /*
   32220  * The maximum size of the Win32-specific heap.  This value may be zero.
   32221  */
   32222 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
   32223 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
   32224 #endif
   32225 
   32226 /*
   32227  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   32228  * zero for the default behavior.
   32229  */
   32230 #ifndef SQLITE_WIN32_HEAP_FLAGS
   32231 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
   32232 #endif
   32233 
   32234 /*
   32235 ** The winMemData structure stores information required by the Win32-specific
   32236 ** sqlite3_mem_methods implementation.
   32237 */
   32238 typedef struct winMemData winMemData;
   32239 struct winMemData {
   32240 #ifndef NDEBUG
   32241   u32 magic;    /* Magic number to detect structure corruption. */
   32242 #endif
   32243   HANDLE hHeap; /* The handle to our heap. */
   32244   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
   32245 };
   32246 
   32247 #ifndef NDEBUG
   32248 #define WINMEM_MAGIC     0x42b2830b
   32249 #endif
   32250 
   32251 static struct winMemData win_mem_data = {
   32252 #ifndef NDEBUG
   32253   WINMEM_MAGIC,
   32254 #endif
   32255   NULL, FALSE
   32256 };
   32257 
   32258 #ifndef NDEBUG
   32259 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
   32260 #else
   32261 #define winMemAssertMagic()
   32262 #endif
   32263 
   32264 #define winMemGetHeap() win_mem_data.hHeap
   32265 
   32266 static void *winMemMalloc(int nBytes);
   32267 static void winMemFree(void *pPrior);
   32268 static void *winMemRealloc(void *pPrior, int nBytes);
   32269 static int winMemSize(void *p);
   32270 static int winMemRoundup(int n);
   32271 static int winMemInit(void *pAppData);
   32272 static void winMemShutdown(void *pAppData);
   32273 
   32274 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   32275 #endif /* SQLITE_WIN32_MALLOC */
   32276 
   32277 /*
   32278 ** The following variable is (normally) set once and never changes
   32279 ** thereafter.  It records whether the operating system is Win9x
   32280 ** or WinNT.
   32281 **
   32282 ** 0:   Operating system unknown.
   32283 ** 1:   Operating system is Win9x.
   32284 ** 2:   Operating system is WinNT.
   32285 **
   32286 ** In order to facilitate testing on a WinNT system, the test fixture
   32287 ** can manually set this value to 1 to emulate Win98 behavior.
   32288 */
   32289 #ifdef SQLITE_TEST
   32290 SQLITE_API int sqlite3_os_type = 0;
   32291 #else
   32292 static int sqlite3_os_type = 0;
   32293 #endif
   32294 
   32295 /*
   32296 ** Many system calls are accessed through pointer-to-functions so that
   32297 ** they may be overridden at runtime to facilitate fault injection during
   32298 ** testing and sandboxing.  The following array holds the names and pointers
   32299 ** to all overrideable system calls.
   32300 */
   32301 #if !SQLITE_OS_WINCE
   32302 #  define SQLITE_WIN32_HAS_ANSI
   32303 #endif
   32304 
   32305 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT
   32306 #  define SQLITE_WIN32_HAS_WIDE
   32307 #endif
   32308 
   32309 #ifndef SYSCALL
   32310 #  define SYSCALL sqlite3_syscall_ptr
   32311 #endif
   32312 
   32313 #if SQLITE_OS_WINCE
   32314 /*
   32315 ** These macros are necessary because Windows CE does not natively support the
   32316 ** Win32 APIs LockFile, UnlockFile, and LockFileEx.
   32317  */
   32318 
   32319 #  define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
   32320 #  define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
   32321 #  define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
   32322 
   32323 /*
   32324 ** These are the special syscall hacks for Windows CE.  The locking related
   32325 ** defines here refer to the macros defined just above.
   32326  */
   32327 
   32328 #  define osAreFileApisANSI()       1
   32329 #  define osLockFile                LockFile
   32330 #  define osUnlockFile              UnlockFile
   32331 #  define osLockFileEx              LockFileEx
   32332 #endif
   32333 
   32334 static struct win_syscall {
   32335   const char *zName;            /* Name of the sytem call */
   32336   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
   32337   sqlite3_syscall_ptr pDefault; /* Default value */
   32338 } aSyscall[] = {
   32339 #if !SQLITE_OS_WINCE
   32340   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
   32341 
   32342 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
   32343 #else
   32344   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
   32345 #endif
   32346 
   32347 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32348   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
   32349 #else
   32350   { "CharLowerW",              (SYSCALL)0,                       0 },
   32351 #endif
   32352 
   32353 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
   32354 
   32355 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32356   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
   32357 #else
   32358   { "CharUpperW",              (SYSCALL)0,                       0 },
   32359 #endif
   32360 
   32361 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
   32362 
   32363   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
   32364 
   32365 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
   32366 
   32367 #if defined(SQLITE_WIN32_HAS_ANSI)
   32368   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
   32369 #else
   32370   { "CreateFileA",             (SYSCALL)0,                       0 },
   32371 #endif
   32372 
   32373 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
   32374         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
   32375 
   32376 #if defined(SQLITE_WIN32_HAS_WIDE)
   32377   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
   32378 #else
   32379   { "CreateFileW",             (SYSCALL)0,                       0 },
   32380 #endif
   32381 
   32382 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
   32383         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
   32384 
   32385   { "CreateFileMapping",       (SYSCALL)CreateFileMapping,       0 },
   32386 
   32387 #define osCreateFileMapping ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32388         DWORD,DWORD,DWORD,LPCTSTR))aSyscall[6].pCurrent)
   32389 
   32390 #if defined(SQLITE_WIN32_HAS_WIDE)
   32391   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
   32392 #else
   32393   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
   32394 #endif
   32395 
   32396 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
   32397         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
   32398 
   32399 #if defined(SQLITE_WIN32_HAS_WIDE)
   32400   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
   32401 #else
   32402   { "CreateMutexW",            (SYSCALL)0,                       0 },
   32403 #endif
   32404 
   32405 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
   32406         LPCWSTR))aSyscall[8].pCurrent)
   32407 
   32408 #if defined(SQLITE_WIN32_HAS_ANSI)
   32409   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
   32410 #else
   32411   { "DeleteFileA",             (SYSCALL)0,                       0 },
   32412 #endif
   32413 
   32414 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
   32415 
   32416 #if defined(SQLITE_WIN32_HAS_WIDE)
   32417   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
   32418 #else
   32419   { "DeleteFileW",             (SYSCALL)0,                       0 },
   32420 #endif
   32421 
   32422 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
   32423 
   32424 #if SQLITE_OS_WINCE
   32425   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
   32426 #else
   32427   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
   32428 #endif
   32429 
   32430 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32431         LPFILETIME))aSyscall[11].pCurrent)
   32432 
   32433 #if SQLITE_OS_WINCE
   32434   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
   32435 #else
   32436   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
   32437 #endif
   32438 
   32439 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
   32440         LPSYSTEMTIME))aSyscall[12].pCurrent)
   32441 
   32442   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
   32443 
   32444 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
   32445 
   32446 #if defined(SQLITE_WIN32_HAS_ANSI)
   32447   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
   32448 #else
   32449   { "FormatMessageA",          (SYSCALL)0,                       0 },
   32450 #endif
   32451 
   32452 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
   32453         DWORD,va_list*))aSyscall[14].pCurrent)
   32454 
   32455 #if defined(SQLITE_WIN32_HAS_WIDE)
   32456   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
   32457 #else
   32458   { "FormatMessageW",          (SYSCALL)0,                       0 },
   32459 #endif
   32460 
   32461 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
   32462         DWORD,va_list*))aSyscall[15].pCurrent)
   32463 
   32464   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
   32465 
   32466 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
   32467 
   32468   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
   32469 
   32470 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
   32471 
   32472 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32473   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
   32474 #else
   32475   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
   32476 #endif
   32477 
   32478 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
   32479         LPDWORD))aSyscall[18].pCurrent)
   32480 
   32481 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32482   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
   32483 #else
   32484   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
   32485 #endif
   32486 
   32487 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
   32488         LPDWORD))aSyscall[19].pCurrent)
   32489 
   32490 #if defined(SQLITE_WIN32_HAS_ANSI)
   32491   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
   32492 #else
   32493   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
   32494 #endif
   32495 
   32496 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
   32497 
   32498 #if defined(SQLITE_WIN32_HAS_WIDE)
   32499   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
   32500 #else
   32501   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
   32502 #endif
   32503 
   32504 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
   32505 
   32506 #if defined(SQLITE_WIN32_HAS_WIDE)
   32507   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
   32508 #else
   32509   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
   32510 #endif
   32511 
   32512 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
   32513         LPVOID))aSyscall[22].pCurrent)
   32514 
   32515   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
   32516 
   32517 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
   32518 
   32519 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
   32520   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
   32521 #else
   32522   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
   32523 #endif
   32524 
   32525 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
   32526         LPSTR*))aSyscall[24].pCurrent)
   32527 
   32528 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
   32529   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
   32530 #else
   32531   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
   32532 #endif
   32533 
   32534 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
   32535         LPWSTR*))aSyscall[25].pCurrent)
   32536 
   32537   { "GetLastError",            (SYSCALL)GetLastError,            0 },
   32538 
   32539 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
   32540 
   32541 #if SQLITE_OS_WINCE
   32542   /* The GetProcAddressA() routine is only available on Windows CE. */
   32543   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
   32544 #else
   32545   /* All other Windows platforms expect GetProcAddress() to take
   32546   ** an ANSI string regardless of the _UNICODE setting */
   32547   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
   32548 #endif
   32549 
   32550 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
   32551         LPCSTR))aSyscall[27].pCurrent)
   32552 
   32553   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
   32554 
   32555 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
   32556 
   32557   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
   32558 
   32559 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
   32560 
   32561 #if !SQLITE_OS_WINCE
   32562   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
   32563 #else
   32564   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
   32565 #endif
   32566 
   32567 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
   32568         LPFILETIME))aSyscall[30].pCurrent)
   32569 
   32570 #if defined(SQLITE_WIN32_HAS_ANSI)
   32571   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
   32572 #else
   32573   { "GetTempPathA",            (SYSCALL)0,                       0 },
   32574 #endif
   32575 
   32576 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
   32577 
   32578 #if defined(SQLITE_WIN32_HAS_WIDE)
   32579   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
   32580 #else
   32581   { "GetTempPathW",            (SYSCALL)0,                       0 },
   32582 #endif
   32583 
   32584 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
   32585 
   32586   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
   32587 
   32588 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
   32589 
   32590 #if defined(SQLITE_WIN32_HAS_ANSI)
   32591   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
   32592 #else
   32593   { "GetVersionExA",           (SYSCALL)0,                       0 },
   32594 #endif
   32595 
   32596 #define osGetVersionExA ((BOOL(WINAPI*)( \
   32597         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
   32598 
   32599   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
   32600 
   32601 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
   32602         SIZE_T))aSyscall[35].pCurrent)
   32603 
   32604   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
   32605 
   32606 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
   32607         SIZE_T))aSyscall[36].pCurrent)
   32608 
   32609   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
   32610 
   32611 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
   32612 
   32613   { "HeapFree",                (SYSCALL)HeapFree,                0 },
   32614 
   32615 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
   32616 
   32617   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
   32618 
   32619 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
   32620         SIZE_T))aSyscall[39].pCurrent)
   32621 
   32622   { "HeapSize",                (SYSCALL)HeapSize,                0 },
   32623 
   32624 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
   32625         LPCVOID))aSyscall[40].pCurrent)
   32626 
   32627   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
   32628 
   32629 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
   32630         LPCVOID))aSyscall[41].pCurrent)
   32631 
   32632 #if defined(SQLITE_WIN32_HAS_ANSI)
   32633   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
   32634 #else
   32635   { "LoadLibraryA",            (SYSCALL)0,                       0 },
   32636 #endif
   32637 
   32638 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
   32639 
   32640 #if defined(SQLITE_WIN32_HAS_WIDE)
   32641   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
   32642 #else
   32643   { "LoadLibraryW",            (SYSCALL)0,                       0 },
   32644 #endif
   32645 
   32646 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
   32647 
   32648   { "LocalFree",               (SYSCALL)LocalFree,               0 },
   32649 
   32650 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
   32651 
   32652 #if !SQLITE_OS_WINCE
   32653   { "LockFile",                (SYSCALL)LockFile,                0 },
   32654 
   32655 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32656         DWORD))aSyscall[45].pCurrent)
   32657 #else
   32658   { "LockFile",                (SYSCALL)0,                       0 },
   32659 #endif
   32660 
   32661 #if !SQLITE_OS_WINCE
   32662   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
   32663 
   32664 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
   32665         LPOVERLAPPED))aSyscall[46].pCurrent)
   32666 #else
   32667   { "LockFileEx",              (SYSCALL)0,                       0 },
   32668 #endif
   32669 
   32670   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
   32671 
   32672 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32673         SIZE_T))aSyscall[47].pCurrent)
   32674 
   32675   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
   32676 
   32677 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
   32678         int))aSyscall[48].pCurrent)
   32679 
   32680   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
   32681 
   32682 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
   32683         LARGE_INTEGER*))aSyscall[49].pCurrent)
   32684 
   32685   { "ReadFile",                (SYSCALL)ReadFile,                0 },
   32686 
   32687 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
   32688         LPOVERLAPPED))aSyscall[50].pCurrent)
   32689 
   32690   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
   32691 
   32692 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
   32693 
   32694   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
   32695 
   32696 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
   32697         DWORD))aSyscall[52].pCurrent)
   32698 
   32699   { "Sleep",                   (SYSCALL)Sleep,                   0 },
   32700 
   32701 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
   32702 
   32703   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
   32704 
   32705 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
   32706         LPFILETIME))aSyscall[54].pCurrent)
   32707 
   32708 #if !SQLITE_OS_WINCE
   32709   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
   32710 
   32711 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32712         DWORD))aSyscall[55].pCurrent)
   32713 #else
   32714   { "UnlockFile",              (SYSCALL)0,                       0 },
   32715 #endif
   32716 
   32717 #if !SQLITE_OS_WINCE
   32718   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
   32719 
   32720 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
   32721         LPOVERLAPPED))aSyscall[56].pCurrent)
   32722 #else
   32723   { "UnlockFileEx",            (SYSCALL)0,                       0 },
   32724 #endif
   32725 
   32726   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
   32727 
   32728 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
   32729 
   32730   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
   32731 
   32732 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
   32733         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
   32734 
   32735   { "WriteFile",               (SYSCALL)WriteFile,               0 },
   32736 
   32737 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
   32738         LPOVERLAPPED))aSyscall[59].pCurrent)
   32739 
   32740 }; /* End of the overrideable system calls */
   32741 
   32742 /*
   32743 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   32744 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
   32745 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   32746 ** system call named zName.
   32747 */
   32748 static int winSetSystemCall(
   32749   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
   32750   const char *zName,            /* Name of system call to override */
   32751   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
   32752 ){
   32753   unsigned int i;
   32754   int rc = SQLITE_NOTFOUND;
   32755 
   32756   UNUSED_PARAMETER(pNotUsed);
   32757   if( zName==0 ){
   32758     /* If no zName is given, restore all system calls to their default
   32759     ** settings and return NULL
   32760     */
   32761     rc = SQLITE_OK;
   32762     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32763       if( aSyscall[i].pDefault ){
   32764         aSyscall[i].pCurrent = aSyscall[i].pDefault;
   32765       }
   32766     }
   32767   }else{
   32768     /* If zName is specified, operate on only the one system call
   32769     ** specified.
   32770     */
   32771     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32772       if( strcmp(zName, aSyscall[i].zName)==0 ){
   32773         if( aSyscall[i].pDefault==0 ){
   32774           aSyscall[i].pDefault = aSyscall[i].pCurrent;
   32775         }
   32776         rc = SQLITE_OK;
   32777         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
   32778         aSyscall[i].pCurrent = pNewFunc;
   32779         break;
   32780       }
   32781     }
   32782   }
   32783   return rc;
   32784 }
   32785 
   32786 /*
   32787 ** Return the value of a system call.  Return NULL if zName is not a
   32788 ** recognized system call name.  NULL is also returned if the system call
   32789 ** is currently undefined.
   32790 */
   32791 static sqlite3_syscall_ptr winGetSystemCall(
   32792   sqlite3_vfs *pNotUsed,
   32793   const char *zName
   32794 ){
   32795   unsigned int i;
   32796 
   32797   UNUSED_PARAMETER(pNotUsed);
   32798   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
   32799     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
   32800   }
   32801   return 0;
   32802 }
   32803 
   32804 /*
   32805 ** Return the name of the first system call after zName.  If zName==NULL
   32806 ** then return the name of the first system call.  Return NULL if zName
   32807 ** is the last system call or if zName is not the name of a valid
   32808 ** system call.
   32809 */
   32810 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
   32811   int i = -1;
   32812 
   32813   UNUSED_PARAMETER(p);
   32814   if( zName ){
   32815     for(i=0; i<ArraySize(aSyscall)-1; i++){
   32816       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
   32817     }
   32818   }
   32819   for(i++; i<ArraySize(aSyscall); i++){
   32820     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
   32821   }
   32822   return 0;
   32823 }
   32824 
   32825 /*
   32826 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   32827 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   32828 **
   32829 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   32830 ** the LockFileEx() API.  But we can still statically link against that
   32831 ** API as long as we don't call it when running Win95/98/ME.  A call to
   32832 ** this routine is used to determine if the host is Win95/98/ME or
   32833 ** WinNT/2K/XP so that we will know whether or not we can safely call
   32834 ** the LockFileEx() API.
   32835 */
   32836 #if SQLITE_OS_WINCE
   32837 # define isNT()  (1)
   32838 #else
   32839   static int isNT(void){
   32840     if( sqlite3_os_type==0 ){
   32841       OSVERSIONINFOA sInfo;
   32842       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   32843       osGetVersionExA(&sInfo);
   32844       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   32845     }
   32846     return sqlite3_os_type==2;
   32847   }
   32848 #endif /* SQLITE_OS_WINCE */
   32849 
   32850 #ifdef SQLITE_WIN32_MALLOC
   32851 /*
   32852 ** Allocate nBytes of memory.
   32853 */
   32854 static void *winMemMalloc(int nBytes){
   32855   HANDLE hHeap;
   32856   void *p;
   32857 
   32858   winMemAssertMagic();
   32859   hHeap = winMemGetHeap();
   32860   assert( hHeap!=0 );
   32861   assert( hHeap!=INVALID_HANDLE_VALUE );
   32862 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32863   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32864 #endif
   32865   assert( nBytes>=0 );
   32866   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   32867   if( !p ){
   32868     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
   32869                 nBytes, osGetLastError(), (void*)hHeap);
   32870   }
   32871   return p;
   32872 }
   32873 
   32874 /*
   32875 ** Free memory.
   32876 */
   32877 static void winMemFree(void *pPrior){
   32878   HANDLE hHeap;
   32879 
   32880   winMemAssertMagic();
   32881   hHeap = winMemGetHeap();
   32882   assert( hHeap!=0 );
   32883   assert( hHeap!=INVALID_HANDLE_VALUE );
   32884 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32885   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   32886 #endif
   32887   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   32888   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   32889     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
   32890                 pPrior, osGetLastError(), (void*)hHeap);
   32891   }
   32892 }
   32893 
   32894 /*
   32895 ** Change the size of an existing memory allocation
   32896 */
   32897 static void *winMemRealloc(void *pPrior, int nBytes){
   32898   HANDLE hHeap;
   32899   void *p;
   32900 
   32901   winMemAssertMagic();
   32902   hHeap = winMemGetHeap();
   32903   assert( hHeap!=0 );
   32904   assert( hHeap!=INVALID_HANDLE_VALUE );
   32905 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32906   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   32907 #endif
   32908   assert( nBytes>=0 );
   32909   if( !pPrior ){
   32910     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   32911   }else{
   32912     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   32913   }
   32914   if( !p ){
   32915     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
   32916                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
   32917                 (void*)hHeap);
   32918   }
   32919   return p;
   32920 }
   32921 
   32922 /*
   32923 ** Return the size of an outstanding allocation, in bytes.
   32924 */
   32925 static int winMemSize(void *p){
   32926   HANDLE hHeap;
   32927   SIZE_T n;
   32928 
   32929   winMemAssertMagic();
   32930   hHeap = winMemGetHeap();
   32931   assert( hHeap!=0 );
   32932   assert( hHeap!=INVALID_HANDLE_VALUE );
   32933 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32934   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32935 #endif
   32936   if( !p ) return 0;
   32937   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   32938   if( n==(SIZE_T)-1 ){
   32939     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
   32940                 p, osGetLastError(), (void*)hHeap);
   32941     return 0;
   32942   }
   32943   return (int)n;
   32944 }
   32945 
   32946 /*
   32947 ** Round up a request size to the next valid allocation size.
   32948 */
   32949 static int winMemRoundup(int n){
   32950   return n;
   32951 }
   32952 
   32953 /*
   32954 ** Initialize this module.
   32955 */
   32956 static int winMemInit(void *pAppData){
   32957   winMemData *pWinMemData = (winMemData *)pAppData;
   32958 
   32959   if( !pWinMemData ) return SQLITE_ERROR;
   32960   assert( pWinMemData->magic==WINMEM_MAGIC );
   32961   if( !pWinMemData->hHeap ){
   32962     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   32963                                       SQLITE_WIN32_HEAP_INIT_SIZE,
   32964                                       SQLITE_WIN32_HEAP_MAX_SIZE);
   32965     if( !pWinMemData->hHeap ){
   32966       sqlite3_log(SQLITE_NOMEM,
   32967           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
   32968           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
   32969           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
   32970       return SQLITE_NOMEM;
   32971     }
   32972     pWinMemData->bOwned = TRUE;
   32973   }
   32974   assert( pWinMemData->hHeap!=0 );
   32975   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   32976 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32977   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32978 #endif
   32979   return SQLITE_OK;
   32980 }
   32981 
   32982 /*
   32983 ** Deinitialize this module.
   32984 */
   32985 static void winMemShutdown(void *pAppData){
   32986   winMemData *pWinMemData = (winMemData *)pAppData;
   32987 
   32988   if( !pWinMemData ) return;
   32989   if( pWinMemData->hHeap ){
   32990     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   32991 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   32992     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   32993 #endif
   32994     if( pWinMemData->bOwned ){
   32995       if( !osHeapDestroy(pWinMemData->hHeap) ){
   32996         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
   32997                     osGetLastError(), (void*)pWinMemData->hHeap);
   32998       }
   32999       pWinMemData->bOwned = FALSE;
   33000     }
   33001     pWinMemData->hHeap = NULL;
   33002   }
   33003 }
   33004 
   33005 /*
   33006 ** Populate the low-level memory allocation function pointers in
   33007 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   33008 ** arguments specify the block of memory to manage.
   33009 **
   33010 ** This routine is only called by sqlite3_config(), and therefore
   33011 ** is not required to be threadsafe (it is not).
   33012 */
   33013 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
   33014   static const sqlite3_mem_methods winMemMethods = {
   33015     winMemMalloc,
   33016     winMemFree,
   33017     winMemRealloc,
   33018     winMemSize,
   33019     winMemRoundup,
   33020     winMemInit,
   33021     winMemShutdown,
   33022     &win_mem_data
   33023   };
   33024   return &winMemMethods;
   33025 }
   33026 
   33027 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   33028   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   33029 }
   33030 #endif /* SQLITE_WIN32_MALLOC */
   33031 
   33032 /*
   33033 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
   33034 **
   33035 ** Space to hold the returned string is obtained from malloc.
   33036 */
   33037 static LPWSTR utf8ToUnicode(const char *zFilename){
   33038   int nChar;
   33039   LPWSTR zWideFilename;
   33040 
   33041   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   33042   if( nChar==0 ){
   33043     return 0;
   33044   }
   33045   zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
   33046   if( zWideFilename==0 ){
   33047     return 0;
   33048   }
   33049   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
   33050                                 nChar);
   33051   if( nChar==0 ){
   33052     sqlite3_free(zWideFilename);
   33053     zWideFilename = 0;
   33054   }
   33055   return zWideFilename;
   33056 }
   33057 
   33058 /*
   33059 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
   33060 ** obtained from sqlite3_malloc().
   33061 */
   33062 static char *unicodeToUtf8(LPCWSTR zWideFilename){
   33063   int nByte;
   33064   char *zFilename;
   33065 
   33066   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   33067   if( nByte == 0 ){
   33068     return 0;
   33069   }
   33070   zFilename = sqlite3_malloc( nByte );
   33071   if( zFilename==0 ){
   33072     return 0;
   33073   }
   33074   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   33075                                 0, 0);
   33076   if( nByte == 0 ){
   33077     sqlite3_free(zFilename);
   33078     zFilename = 0;
   33079   }
   33080   return zFilename;
   33081 }
   33082 
   33083 /*
   33084 ** Convert an ANSI string to Microsoft Unicode, based on the
   33085 ** current codepage settings for file apis.
   33086 **
   33087 ** Space to hold the returned string is obtained
   33088 ** from sqlite3_malloc.
   33089 */
   33090 static LPWSTR mbcsToUnicode(const char *zFilename){
   33091   int nByte;
   33092   LPWSTR zMbcsFilename;
   33093   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33094 
   33095   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
   33096                                 0)*sizeof(WCHAR);
   33097   if( nByte==0 ){
   33098     return 0;
   33099   }
   33100   zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
   33101   if( zMbcsFilename==0 ){
   33102     return 0;
   33103   }
   33104   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
   33105                                 nByte);
   33106   if( nByte==0 ){
   33107     sqlite3_free(zMbcsFilename);
   33108     zMbcsFilename = 0;
   33109   }
   33110   return zMbcsFilename;
   33111 }
   33112 
   33113 /*
   33114 ** Convert Microsoft Unicode to multi-byte character string, based on the
   33115 ** user's ANSI codepage.
   33116 **
   33117 ** Space to hold the returned string is obtained from
   33118 ** sqlite3_malloc().
   33119 */
   33120 static char *unicodeToMbcs(LPCWSTR zWideFilename){
   33121   int nByte;
   33122   char *zFilename;
   33123   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   33124 
   33125   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   33126   if( nByte == 0 ){
   33127     return 0;
   33128   }
   33129   zFilename = sqlite3_malloc( nByte );
   33130   if( zFilename==0 ){
   33131     return 0;
   33132   }
   33133   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
   33134                                 nByte, 0, 0);
   33135   if( nByte == 0 ){
   33136     sqlite3_free(zFilename);
   33137     zFilename = 0;
   33138   }
   33139   return zFilename;
   33140 }
   33141 
   33142 /*
   33143 ** Convert multibyte character string to UTF-8.  Space to hold the
   33144 ** returned string is obtained from sqlite3_malloc().
   33145 */
   33146 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   33147   char *zFilenameUtf8;
   33148   LPWSTR zTmpWide;
   33149 
   33150   zTmpWide = mbcsToUnicode(zFilename);
   33151   if( zTmpWide==0 ){
   33152     return 0;
   33153   }
   33154   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
   33155   sqlite3_free(zTmpWide);
   33156   return zFilenameUtf8;
   33157 }
   33158 
   33159 /*
   33160 ** Convert UTF-8 to multibyte character string.  Space to hold the
   33161 ** returned string is obtained from sqlite3_malloc().
   33162 */
   33163 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
   33164   char *zFilenameMbcs;
   33165   LPWSTR zTmpWide;
   33166 
   33167   zTmpWide = utf8ToUnicode(zFilename);
   33168   if( zTmpWide==0 ){
   33169     return 0;
   33170   }
   33171   zFilenameMbcs = unicodeToMbcs(zTmpWide);
   33172   sqlite3_free(zTmpWide);
   33173   return zFilenameMbcs;
   33174 }
   33175 
   33176 
   33177 /*
   33178 ** The return value of getLastErrorMsg
   33179 ** is zero if the error message fits in the buffer, or non-zero
   33180 ** otherwise (if the message was truncated).
   33181 */
   33182 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   33183   /* FormatMessage returns 0 on failure.  Otherwise it
   33184   ** returns the number of TCHARs written to the output
   33185   ** buffer, excluding the terminating null char.
   33186   */
   33187   DWORD dwLen = 0;
   33188   char *zOut = 0;
   33189 
   33190   if( isNT() ){
   33191     LPWSTR zTempWide = NULL;
   33192     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33193                              FORMAT_MESSAGE_FROM_SYSTEM |
   33194                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33195                              NULL,
   33196                              lastErrno,
   33197                              0,
   33198                              (LPWSTR) &zTempWide,
   33199                              0,
   33200                              0);
   33201     if( dwLen > 0 ){
   33202       /* allocate a buffer and convert to UTF8 */
   33203       sqlite3BeginBenignMalloc();
   33204       zOut = unicodeToUtf8(zTempWide);
   33205       sqlite3EndBenignMalloc();
   33206       /* free the system buffer allocated by FormatMessage */
   33207       osLocalFree(zTempWide);
   33208     }
   33209 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   33210 ** Since the ANSI version of these Windows API do not exist for WINCE,
   33211 ** it's important to not reference them for WINCE builds.
   33212 */
   33213 #if SQLITE_OS_WINCE==0
   33214   }else{
   33215     char *zTemp = NULL;
   33216     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
   33217                              FORMAT_MESSAGE_FROM_SYSTEM |
   33218                              FORMAT_MESSAGE_IGNORE_INSERTS,
   33219                              NULL,
   33220                              lastErrno,
   33221                              0,
   33222                              (LPSTR) &zTemp,
   33223                              0,
   33224                              0);
   33225     if( dwLen > 0 ){
   33226       /* allocate a buffer and convert to UTF8 */
   33227       sqlite3BeginBenignMalloc();
   33228       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   33229       sqlite3EndBenignMalloc();
   33230       /* free the system buffer allocated by FormatMessage */
   33231       osLocalFree(zTemp);
   33232     }
   33233 #endif
   33234   }
   33235   if( 0 == dwLen ){
   33236     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
   33237   }else{
   33238     /* copy a maximum of nBuf chars to output buffer */
   33239     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   33240     /* free the UTF8 buffer */
   33241     sqlite3_free(zOut);
   33242   }
   33243   return 0;
   33244 }
   33245 
   33246 /*
   33247 **
   33248 ** This function - winLogErrorAtLine() - is only ever called via the macro
   33249 ** winLogError().
   33250 **
   33251 ** This routine is invoked after an error occurs in an OS function.
   33252 ** It logs a message using sqlite3_log() containing the current value of
   33253 ** error code and, if possible, the human-readable equivalent from
   33254 ** FormatMessage.
   33255 **
   33256 ** The first argument passed to the macro should be the error code that
   33257 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   33258 ** The two subsequent arguments should be the name of the OS function that
   33259 ** failed and the the associated file-system path, if any.
   33260 */
   33261 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   33262 static int winLogErrorAtLine(
   33263   int errcode,                    /* SQLite error code */
   33264   DWORD lastErrno,                /* Win32 last error */
   33265   const char *zFunc,              /* Name of OS function that failed */
   33266   const char *zPath,              /* File path associated with error */
   33267   int iLine                       /* Source line number where error occurred */
   33268 ){
   33269   char zMsg[500];                 /* Human readable error text */
   33270   int i;                          /* Loop counter */
   33271 
   33272   zMsg[0] = 0;
   33273   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   33274   assert( errcode!=SQLITE_OK );
   33275   if( zPath==0 ) zPath = "";
   33276   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   33277   zMsg[i] = 0;
   33278   sqlite3_log(errcode,
   33279       "os_win.c:%d: (%d) %s(%s) - %s",
   33280       iLine, lastErrno, zFunc, zPath, zMsg
   33281   );
   33282 
   33283   return errcode;
   33284 }
   33285 
   33286 /*
   33287 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
   33288 ** will be retried following a locking error - probably caused by
   33289 ** antivirus software.  Also the initial delay before the first retry.
   33290 ** The delay increases linearly with each retry.
   33291 */
   33292 #ifndef SQLITE_WIN32_IOERR_RETRY
   33293 # define SQLITE_WIN32_IOERR_RETRY 10
   33294 #endif
   33295 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
   33296 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
   33297 #endif
   33298 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
   33299 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   33300 
   33301 /*
   33302 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   33303 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   33304 ** to give up with an error.
   33305 */
   33306 static int retryIoerr(int *pnRetry, DWORD *pError){
   33307   DWORD e = osGetLastError();
   33308   if( *pnRetry>=win32IoerrRetry ){
   33309     if( pError ){
   33310       *pError = e;
   33311     }
   33312     return 0;
   33313   }
   33314   if( e==ERROR_ACCESS_DENIED ||
   33315       e==ERROR_LOCK_VIOLATION ||
   33316       e==ERROR_SHARING_VIOLATION ){
   33317     osSleep(win32IoerrRetryDelay*(1+*pnRetry));
   33318     ++*pnRetry;
   33319     return 1;
   33320   }
   33321   if( pError ){
   33322     *pError = e;
   33323   }
   33324   return 0;
   33325 }
   33326 
   33327 /*
   33328 ** Log a I/O error retry episode.
   33329 */
   33330 static void logIoerr(int nRetry){
   33331   if( nRetry ){
   33332     sqlite3_log(SQLITE_IOERR,
   33333       "delayed %dms for lock/sharing conflict",
   33334       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
   33335     );
   33336   }
   33337 }
   33338 
   33339 #if SQLITE_OS_WINCE
   33340 /*************************************************************************
   33341 ** This section contains code for WinCE only.
   33342 */
   33343 /*
   33344 ** Windows CE does not have a localtime() function.  So create a
   33345 ** substitute.
   33346 */
   33347 /* #include <time.h> */
   33348 struct tm *__cdecl localtime(const time_t *t)
   33349 {
   33350   static struct tm y;
   33351   FILETIME uTm, lTm;
   33352   SYSTEMTIME pTm;
   33353   sqlite3_int64 t64;
   33354   t64 = *t;
   33355   t64 = (t64 + 11644473600)*10000000;
   33356   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   33357   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   33358   osFileTimeToLocalFileTime(&uTm,&lTm);
   33359   osFileTimeToSystemTime(&lTm,&pTm);
   33360   y.tm_year = pTm.wYear - 1900;
   33361   y.tm_mon = pTm.wMonth - 1;
   33362   y.tm_wday = pTm.wDayOfWeek;
   33363   y.tm_mday = pTm.wDay;
   33364   y.tm_hour = pTm.wHour;
   33365   y.tm_min = pTm.wMinute;
   33366   y.tm_sec = pTm.wSecond;
   33367   return &y;
   33368 }
   33369 
   33370 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   33371 
   33372 /*
   33373 ** Acquire a lock on the handle h
   33374 */
   33375 static void winceMutexAcquire(HANDLE h){
   33376    DWORD dwErr;
   33377    do {
   33378      dwErr = WaitForSingleObject(h, INFINITE);
   33379    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   33380 }
   33381 /*
   33382 ** Release a lock acquired by winceMutexAcquire()
   33383 */
   33384 #define winceMutexRelease(h) ReleaseMutex(h)
   33385 
   33386 /*
   33387 ** Create the mutex and shared memory used for locking in the file
   33388 ** descriptor pFile
   33389 */
   33390 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
   33391   LPWSTR zTok;
   33392   LPWSTR zName;
   33393   BOOL bInit = TRUE;
   33394 
   33395   zName = utf8ToUnicode(zFilename);
   33396   if( zName==0 ){
   33397     /* out of memory */
   33398     return FALSE;
   33399   }
   33400 
   33401   /* Initialize the local lockdata */
   33402   memset(&pFile->local, 0, sizeof(pFile->local));
   33403 
   33404   /* Replace the backslashes from the filename and lowercase it
   33405   ** to derive a mutex name. */
   33406   zTok = osCharLowerW(zName);
   33407   for (;*zTok;zTok++){
   33408     if (*zTok == '\\') *zTok = '_';
   33409   }
   33410 
   33411   /* Create/open the named mutex */
   33412   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   33413   if (!pFile->hMutex){
   33414     pFile->lastErrno = osGetLastError();
   33415     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
   33416     sqlite3_free(zName);
   33417     return FALSE;
   33418   }
   33419 
   33420   /* Acquire the mutex before continuing */
   33421   winceMutexAcquire(pFile->hMutex);
   33422 
   33423   /* Since the names of named mutexes, semaphores, file mappings etc are
   33424   ** case-sensitive, take advantage of that by uppercasing the mutex name
   33425   ** and using that as the shared filemapping name.
   33426   */
   33427   osCharUpperW(zName);
   33428   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   33429                                         PAGE_READWRITE, 0, sizeof(winceLock),
   33430                                         zName);
   33431 
   33432   /* Set a flag that indicates we're the first to create the memory so it
   33433   ** must be zero-initialized */
   33434   if (osGetLastError() == ERROR_ALREADY_EXISTS){
   33435     bInit = FALSE;
   33436   }
   33437 
   33438   sqlite3_free(zName);
   33439 
   33440   /* If we succeeded in making the shared memory handle, map it. */
   33441   if (pFile->hShared){
   33442     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
   33443              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   33444     /* If mapping failed, close the shared memory handle and erase it */
   33445     if (!pFile->shared){
   33446       pFile->lastErrno = osGetLastError();
   33447       winLogError(SQLITE_ERROR, pFile->lastErrno,
   33448                "winceCreateLock2", zFilename);
   33449       osCloseHandle(pFile->hShared);
   33450       pFile->hShared = NULL;
   33451     }
   33452   }
   33453 
   33454   /* If shared memory could not be created, then close the mutex and fail */
   33455   if (pFile->hShared == NULL){
   33456     winceMutexRelease(pFile->hMutex);
   33457     osCloseHandle(pFile->hMutex);
   33458     pFile->hMutex = NULL;
   33459     return FALSE;
   33460   }
   33461 
   33462   /* Initialize the shared memory if we're supposed to */
   33463   if (bInit) {
   33464     memset(pFile->shared, 0, sizeof(winceLock));
   33465   }
   33466 
   33467   winceMutexRelease(pFile->hMutex);
   33468   return TRUE;
   33469 }
   33470 
   33471 /*
   33472 ** Destroy the part of winFile that deals with wince locks
   33473 */
   33474 static void winceDestroyLock(winFile *pFile){
   33475   if (pFile->hMutex){
   33476     /* Acquire the mutex */
   33477     winceMutexAcquire(pFile->hMutex);
   33478 
   33479     /* The following blocks should probably assert in debug mode, but they
   33480        are to cleanup in case any locks remained open */
   33481     if (pFile->local.nReaders){
   33482       pFile->shared->nReaders --;
   33483     }
   33484     if (pFile->local.bReserved){
   33485       pFile->shared->bReserved = FALSE;
   33486     }
   33487     if (pFile->local.bPending){
   33488       pFile->shared->bPending = FALSE;
   33489     }
   33490     if (pFile->local.bExclusive){
   33491       pFile->shared->bExclusive = FALSE;
   33492     }
   33493 
   33494     /* De-reference and close our copy of the shared memory handle */
   33495     osUnmapViewOfFile(pFile->shared);
   33496     osCloseHandle(pFile->hShared);
   33497 
   33498     /* Done with the mutex */
   33499     winceMutexRelease(pFile->hMutex);
   33500     osCloseHandle(pFile->hMutex);
   33501     pFile->hMutex = NULL;
   33502   }
   33503 }
   33504 
   33505 /*
   33506 ** An implementation of the LockFile() API of Windows for CE
   33507 */
   33508 static BOOL winceLockFile(
   33509   HANDLE *phFile,
   33510   DWORD dwFileOffsetLow,
   33511   DWORD dwFileOffsetHigh,
   33512   DWORD nNumberOfBytesToLockLow,
   33513   DWORD nNumberOfBytesToLockHigh
   33514 ){
   33515   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   33516   BOOL bReturn = FALSE;
   33517 
   33518   UNUSED_PARAMETER(dwFileOffsetHigh);
   33519   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   33520 
   33521   if (!pFile->hMutex) return TRUE;
   33522   winceMutexAcquire(pFile->hMutex);
   33523 
   33524   /* Wanting an exclusive lock? */
   33525   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   33526        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   33527     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   33528        pFile->shared->bExclusive = TRUE;
   33529        pFile->local.bExclusive = TRUE;
   33530        bReturn = TRUE;
   33531     }
   33532   }
   33533 
   33534   /* Want a read-only lock? */
   33535   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   33536            nNumberOfBytesToLockLow == 1){
   33537     if (pFile->shared->bExclusive == 0){
   33538       pFile->local.nReaders ++;
   33539       if (pFile->local.nReaders == 1){
   33540         pFile->shared->nReaders ++;
   33541       }
   33542       bReturn = TRUE;
   33543     }
   33544   }
   33545 
   33546   /* Want a pending lock? */
   33547   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
   33548     /* If no pending lock has been acquired, then acquire it */
   33549     if (pFile->shared->bPending == 0) {
   33550       pFile->shared->bPending = TRUE;
   33551       pFile->local.bPending = TRUE;
   33552       bReturn = TRUE;
   33553     }
   33554   }
   33555 
   33556   /* Want a reserved lock? */
   33557   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
   33558     if (pFile->shared->bReserved == 0) {
   33559       pFile->shared->bReserved = TRUE;
   33560       pFile->local.bReserved = TRUE;
   33561       bReturn = TRUE;
   33562     }
   33563   }
   33564 
   33565   winceMutexRelease(pFile->hMutex);
   33566   return bReturn;
   33567 }
   33568 
   33569 /*
   33570 ** An implementation of the UnlockFile API of Windows for CE
   33571 */
   33572 static BOOL winceUnlockFile(
   33573   HANDLE *phFile,
   33574   DWORD dwFileOffsetLow,
   33575   DWORD dwFileOffsetHigh,
   33576   DWORD nNumberOfBytesToUnlockLow,
   33577   DWORD nNumberOfBytesToUnlockHigh
   33578 ){
   33579   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   33580   BOOL bReturn = FALSE;
   33581 
   33582   UNUSED_PARAMETER(dwFileOffsetHigh);
   33583   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   33584 
   33585   if (!pFile->hMutex) return TRUE;
   33586   winceMutexAcquire(pFile->hMutex);
   33587 
   33588   /* Releasing a reader lock or an exclusive lock */
   33589   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   33590     /* Did we have an exclusive lock? */
   33591     if (pFile->local.bExclusive){
   33592       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   33593       pFile->local.bExclusive = FALSE;
   33594       pFile->shared->bExclusive = FALSE;
   33595       bReturn = TRUE;
   33596     }
   33597 
   33598     /* Did we just have a reader lock? */
   33599     else if (pFile->local.nReaders){
   33600       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
   33601       pFile->local.nReaders --;
   33602       if (pFile->local.nReaders == 0)
   33603       {
   33604         pFile->shared->nReaders --;
   33605       }
   33606       bReturn = TRUE;
   33607     }
   33608   }
   33609 
   33610   /* Releasing a pending lock */
   33611   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
   33612     if (pFile->local.bPending){
   33613       pFile->local.bPending = FALSE;
   33614       pFile->shared->bPending = FALSE;
   33615       bReturn = TRUE;
   33616     }
   33617   }
   33618   /* Releasing a reserved lock */
   33619   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
   33620     if (pFile->local.bReserved) {
   33621       pFile->local.bReserved = FALSE;
   33622       pFile->shared->bReserved = FALSE;
   33623       bReturn = TRUE;
   33624     }
   33625   }
   33626 
   33627   winceMutexRelease(pFile->hMutex);
   33628   return bReturn;
   33629 }
   33630 
   33631 /*
   33632 ** An implementation of the LockFileEx() API of Windows for CE
   33633 */
   33634 static BOOL winceLockFileEx(
   33635   HANDLE *phFile,
   33636   DWORD dwFlags,
   33637   DWORD dwReserved,
   33638   DWORD nNumberOfBytesToLockLow,
   33639   DWORD nNumberOfBytesToLockHigh,
   33640   LPOVERLAPPED lpOverlapped
   33641 ){
   33642   UNUSED_PARAMETER(dwReserved);
   33643   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   33644 
   33645   /* If the caller wants a shared read lock, forward this call
   33646   ** to winceLockFile */
   33647   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
   33648       dwFlags == 1 &&
   33649       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   33650     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
   33651   }
   33652   return FALSE;
   33653 }
   33654 /*
   33655 ** End of the special code for wince
   33656 *****************************************************************************/
   33657 #endif /* SQLITE_OS_WINCE */
   33658 
   33659 /*****************************************************************************
   33660 ** The next group of routines implement the I/O methods specified
   33661 ** by the sqlite3_io_methods object.
   33662 ******************************************************************************/
   33663 
   33664 /*
   33665 ** Some Microsoft compilers lack this definition.
   33666 */
   33667 #ifndef INVALID_SET_FILE_POINTER
   33668 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   33669 #endif
   33670 
   33671 /*
   33672 ** Move the current position of the file handle passed as the first
   33673 ** argument to offset iOffset within the file. If successful, return 0.
   33674 ** Otherwise, set pFile->lastErrno and return non-zero.
   33675 */
   33676 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
   33677   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   33678   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   33679   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   33680   DWORD lastErrno;                /* Value returned by GetLastError() */
   33681 
   33682   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   33683   lowerBits = (LONG)(iOffset & 0xffffffff);
   33684 
   33685   /* API oddity: If successful, SetFilePointer() returns a dword
   33686   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   33687   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   33688   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   33689   ** whether an error has actually occured, it is also necessary to call
   33690   ** GetLastError().
   33691   */
   33692   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   33693 
   33694   if( (dwRet==INVALID_SET_FILE_POINTER
   33695       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
   33696     pFile->lastErrno = lastErrno;
   33697     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
   33698              "seekWinFile", pFile->zPath);
   33699     return 1;
   33700   }
   33701 
   33702   return 0;
   33703 }
   33704 
   33705 /*
   33706 ** Close a file.
   33707 **
   33708 ** It is reported that an attempt to close a handle might sometimes
   33709 ** fail.  This is a very unreasonable result, but Windows is notorious
   33710 ** for being unreasonable so I do not doubt that it might happen.  If
   33711 ** the close fails, we pause for 100 milliseconds and try again.  As
   33712 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   33713 ** giving up and returning an error.
   33714 */
   33715 #define MX_CLOSE_ATTEMPT 3
   33716 static int winClose(sqlite3_file *id){
   33717   int rc, cnt = 0;
   33718   winFile *pFile = (winFile*)id;
   33719 
   33720   assert( id!=0 );
   33721   assert( pFile->pShm==0 );
   33722   OSTRACE(("CLOSE %d\n", pFile->h));
   33723   do{
   33724     rc = osCloseHandle(pFile->h);
   33725     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   33726   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) );
   33727 #if SQLITE_OS_WINCE
   33728 #define WINCE_DELETION_ATTEMPTS 3
   33729   winceDestroyLock(pFile);
   33730   if( pFile->zDeleteOnClose ){
   33731     int cnt = 0;
   33732     while(
   33733            osDeleteFileW(pFile->zDeleteOnClose)==0
   33734         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   33735         && cnt++ < WINCE_DELETION_ATTEMPTS
   33736     ){
   33737        osSleep(100);  /* Wait a little before trying again */
   33738     }
   33739     sqlite3_free(pFile->zDeleteOnClose);
   33740   }
   33741 #endif
   33742   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
   33743   OpenCounter(-1);
   33744   return rc ? SQLITE_OK
   33745             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
   33746                           "winClose", pFile->zPath);
   33747 }
   33748 
   33749 /*
   33750 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   33751 ** bytes were read successfully and SQLITE_IOERR if anything goes
   33752 ** wrong.
   33753 */
   33754 static int winRead(
   33755   sqlite3_file *id,          /* File to read from */
   33756   void *pBuf,                /* Write content into this buffer */
   33757   int amt,                   /* Number of bytes to read */
   33758   sqlite3_int64 offset       /* Begin reading at this offset */
   33759 ){
   33760   winFile *pFile = (winFile*)id;  /* file handle */
   33761   DWORD nRead;                    /* Number of bytes actually read from file */
   33762   int nRetry = 0;                 /* Number of retrys */
   33763 
   33764   assert( id!=0 );
   33765   SimulateIOError(return SQLITE_IOERR_READ);
   33766   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
   33767 
   33768   if( seekWinFile(pFile, offset) ){
   33769     return SQLITE_FULL;
   33770   }
   33771   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   33772     DWORD lastErrno;
   33773     if( retryIoerr(&nRetry, &lastErrno) ) continue;
   33774     pFile->lastErrno = lastErrno;
   33775     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
   33776              "winRead", pFile->zPath);
   33777   }
   33778   logIoerr(nRetry);
   33779   if( nRead<(DWORD)amt ){
   33780     /* Unread parts of the buffer must be zero-filled */
   33781     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   33782     return SQLITE_IOERR_SHORT_READ;
   33783   }
   33784 
   33785   return SQLITE_OK;
   33786 }
   33787 
   33788 /*
   33789 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   33790 ** or some other error code on failure.
   33791 */
   33792 static int winWrite(
   33793   sqlite3_file *id,               /* File to write into */
   33794   const void *pBuf,               /* The bytes to be written */
   33795   int amt,                        /* Number of bytes to write */
   33796   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   33797 ){
   33798   int rc;                         /* True if error has occured, else false */
   33799   winFile *pFile = (winFile*)id;  /* File handle */
   33800   int nRetry = 0;                 /* Number of retries */
   33801 
   33802   assert( amt>0 );
   33803   assert( pFile );
   33804   SimulateIOError(return SQLITE_IOERR_WRITE);
   33805   SimulateDiskfullError(return SQLITE_FULL);
   33806 
   33807   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
   33808 
   33809   rc = seekWinFile(pFile, offset);
   33810   if( rc==0 ){
   33811     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   33812     int nRem = amt;               /* Number of bytes yet to be written */
   33813     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   33814     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
   33815 
   33816     while( nRem>0 ){
   33817       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
   33818         if( retryIoerr(&nRetry, &lastErrno) ) continue;
   33819         break;
   33820       }
   33821       if( nWrite<=0 ) break;
   33822       aRem += nWrite;
   33823       nRem -= nWrite;
   33824     }
   33825     if( nRem>0 ){
   33826       pFile->lastErrno = lastErrno;
   33827       rc = 1;
   33828     }
   33829   }
   33830 
   33831   if( rc ){
   33832     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
   33833        || ( pFile->lastErrno==ERROR_DISK_FULL )){
   33834       return SQLITE_FULL;
   33835     }
   33836     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
   33837              "winWrite", pFile->zPath);
   33838   }else{
   33839     logIoerr(nRetry);
   33840   }
   33841   return SQLITE_OK;
   33842 }
   33843 
   33844 /*
   33845 ** Truncate an open file to a specified size
   33846 */
   33847 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   33848   winFile *pFile = (winFile*)id;  /* File handle object */
   33849   int rc = SQLITE_OK;             /* Return code for this function */
   33850 
   33851   assert( pFile );
   33852 
   33853   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
   33854   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   33855 
   33856   /* If the user has configured a chunk-size for this file, truncate the
   33857   ** file so that it consists of an integer number of chunks (i.e. the
   33858   ** actual file size after the operation may be larger than the requested
   33859   ** size).
   33860   */
   33861   if( pFile->szChunk>0 ){
   33862     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   33863   }
   33864 
   33865   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   33866   if( seekWinFile(pFile, nByte) ){
   33867     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   33868              "winTruncate1", pFile->zPath);
   33869   }else if( 0==osSetEndOfFile(pFile->h) ){
   33870     pFile->lastErrno = osGetLastError();
   33871     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
   33872              "winTruncate2", pFile->zPath);
   33873   }
   33874 
   33875   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
   33876   return rc;
   33877 }
   33878 
   33879 #ifdef SQLITE_TEST
   33880 /*
   33881 ** Count the number of fullsyncs and normal syncs.  This is used to test
   33882 ** that syncs and fullsyncs are occuring at the right times.
   33883 */
   33884 SQLITE_API int sqlite3_sync_count = 0;
   33885 SQLITE_API int sqlite3_fullsync_count = 0;
   33886 #endif
   33887 
   33888 /*
   33889 ** Make sure all writes to a particular file are committed to disk.
   33890 */
   33891 static int winSync(sqlite3_file *id, int flags){
   33892 #ifndef SQLITE_NO_SYNC
   33893   /*
   33894   ** Used only when SQLITE_NO_SYNC is not defined.
   33895    */
   33896   BOOL rc;
   33897 #endif
   33898 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
   33899     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
   33900   /*
   33901   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
   33902   ** OSTRACE() macros.
   33903    */
   33904   winFile *pFile = (winFile*)id;
   33905 #else
   33906   UNUSED_PARAMETER(id);
   33907 #endif
   33908 
   33909   assert( pFile );
   33910   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   33911   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   33912       || (flags&0x0F)==SQLITE_SYNC_FULL
   33913   );
   33914 
   33915   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
   33916 
   33917   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   33918   ** line is to test that doing so does not cause any problems.
   33919   */
   33920   SimulateDiskfullError( return SQLITE_FULL );
   33921 
   33922 #ifndef SQLITE_TEST
   33923   UNUSED_PARAMETER(flags);
   33924 #else
   33925   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
   33926     sqlite3_fullsync_count++;
   33927   }
   33928   sqlite3_sync_count++;
   33929 #endif
   33930 
   33931   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   33932   ** no-op
   33933   */
   33934 #ifdef SQLITE_NO_SYNC
   33935   return SQLITE_OK;
   33936 #else
   33937   rc = osFlushFileBuffers(pFile->h);
   33938   SimulateIOError( rc=FALSE );
   33939   if( rc ){
   33940     return SQLITE_OK;
   33941   }else{
   33942     pFile->lastErrno = osGetLastError();
   33943     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
   33944              "winSync", pFile->zPath);
   33945   }
   33946 #endif
   33947 }
   33948 
   33949 /*
   33950 ** Determine the current size of a file in bytes
   33951 */
   33952 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   33953   DWORD upperBits;
   33954   DWORD lowerBits;
   33955   winFile *pFile = (winFile*)id;
   33956   DWORD lastErrno;
   33957 
   33958   assert( id!=0 );
   33959   SimulateIOError(return SQLITE_IOERR_FSTAT);
   33960   lowerBits = osGetFileSize(pFile->h, &upperBits);
   33961   if(   (lowerBits == INVALID_FILE_SIZE)
   33962      && ((lastErrno = osGetLastError())!=NO_ERROR) )
   33963   {
   33964     pFile->lastErrno = lastErrno;
   33965     return winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
   33966              "winFileSize", pFile->zPath);
   33967   }
   33968   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   33969   return SQLITE_OK;
   33970 }
   33971 
   33972 /*
   33973 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   33974 */
   33975 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   33976 # define LOCKFILE_FAIL_IMMEDIATELY 1
   33977 #endif
   33978 
   33979 /*
   33980 ** Acquire a reader lock.
   33981 ** Different API routines are called depending on whether or not this
   33982 ** is Win9x or WinNT.
   33983 */
   33984 static int getReadLock(winFile *pFile){
   33985   int res;
   33986   if( isNT() ){
   33987     OVERLAPPED ovlp;
   33988     ovlp.Offset = SHARED_FIRST;
   33989     ovlp.OffsetHigh = 0;
   33990     ovlp.hEvent = 0;
   33991     res = osLockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
   33992                        0, SHARED_SIZE, 0, &ovlp);
   33993 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   33994 */
   33995 #if SQLITE_OS_WINCE==0
   33996   }else{
   33997     int lk;
   33998     sqlite3_randomness(sizeof(lk), &lk);
   33999     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   34000     res = osLockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   34001 #endif
   34002   }
   34003   if( res == 0 ){
   34004     pFile->lastErrno = osGetLastError();
   34005     /* No need to log a failure to lock */
   34006   }
   34007   return res;
   34008 }
   34009 
   34010 /*
   34011 ** Undo a readlock
   34012 */
   34013 static int unlockReadLock(winFile *pFile){
   34014   int res;
   34015   DWORD lastErrno;
   34016   if( isNT() ){
   34017     res = osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34018 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   34019 */
   34020 #if SQLITE_OS_WINCE==0
   34021   }else{
   34022     res = osUnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
   34023 #endif
   34024   }
   34025   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
   34026     pFile->lastErrno = lastErrno;
   34027     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
   34028              "unlockReadLock", pFile->zPath);
   34029   }
   34030   return res;
   34031 }
   34032 
   34033 /*
   34034 ** Lock the file with the lock specified by parameter locktype - one
   34035 ** of the following:
   34036 **
   34037 **     (1) SHARED_LOCK
   34038 **     (2) RESERVED_LOCK
   34039 **     (3) PENDING_LOCK
   34040 **     (4) EXCLUSIVE_LOCK
   34041 **
   34042 ** Sometimes when requesting one lock state, additional lock states
   34043 ** are inserted in between.  The locking might fail on one of the later
   34044 ** transitions leaving the lock state different from what it started but
   34045 ** still short of its goal.  The following chart shows the allowed
   34046 ** transitions and the inserted intermediate states:
   34047 **
   34048 **    UNLOCKED -> SHARED
   34049 **    SHARED -> RESERVED
   34050 **    SHARED -> (PENDING) -> EXCLUSIVE
   34051 **    RESERVED -> (PENDING) -> EXCLUSIVE
   34052 **    PENDING -> EXCLUSIVE
   34053 **
   34054 ** This routine will only increase a lock.  The winUnlock() routine
   34055 ** erases all locks at once and returns us immediately to locking level 0.
   34056 ** It is not possible to lower the locking level one step at a time.  You
   34057 ** must go straight to locking level 0.
   34058 */
   34059 static int winLock(sqlite3_file *id, int locktype){
   34060   int rc = SQLITE_OK;    /* Return code from subroutines */
   34061   int res = 1;           /* Result of a Windows lock call */
   34062   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   34063   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   34064   winFile *pFile = (winFile*)id;
   34065   DWORD lastErrno = NO_ERROR;
   34066 
   34067   assert( id!=0 );
   34068   OSTRACE(("LOCK %d %d was %d(%d)\n",
   34069            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
   34070 
   34071   /* If there is already a lock of this type or more restrictive on the
   34072   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   34073   ** sqlite3OsEnterMutex() hasn't been called yet.
   34074   */
   34075   if( pFile->locktype>=locktype ){
   34076     return SQLITE_OK;
   34077   }
   34078 
   34079   /* Make sure the locking sequence is correct
   34080   */
   34081   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   34082   assert( locktype!=PENDING_LOCK );
   34083   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   34084 
   34085   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   34086   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   34087   ** the PENDING_LOCK byte is temporary.
   34088   */
   34089   newLocktype = pFile->locktype;
   34090   if(   (pFile->locktype==NO_LOCK)
   34091      || (   (locktype==EXCLUSIVE_LOCK)
   34092          && (pFile->locktype==RESERVED_LOCK))
   34093   ){
   34094     int cnt = 3;
   34095     while( cnt-->0 && (res = osLockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
   34096       /* Try 3 times to get the pending lock.  This is needed to work
   34097       ** around problems caused by indexing and/or anti-virus software on
   34098       ** Windows systems.
   34099       ** If you are using this code as a model for alternative VFSes, do not
   34100       ** copy this retry logic.  It is a hack intended for Windows only.
   34101       */
   34102       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
   34103       if( cnt ) osSleep(1);
   34104     }
   34105     gotPendingLock = res;
   34106     if( !res ){
   34107       lastErrno = osGetLastError();
   34108     }
   34109   }
   34110 
   34111   /* Acquire a shared lock
   34112   */
   34113   if( locktype==SHARED_LOCK && res ){
   34114     assert( pFile->locktype==NO_LOCK );
   34115     res = getReadLock(pFile);
   34116     if( res ){
   34117       newLocktype = SHARED_LOCK;
   34118     }else{
   34119       lastErrno = osGetLastError();
   34120     }
   34121   }
   34122 
   34123   /* Acquire a RESERVED lock
   34124   */
   34125   if( locktype==RESERVED_LOCK && res ){
   34126     assert( pFile->locktype==SHARED_LOCK );
   34127     res = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34128     if( res ){
   34129       newLocktype = RESERVED_LOCK;
   34130     }else{
   34131       lastErrno = osGetLastError();
   34132     }
   34133   }
   34134 
   34135   /* Acquire a PENDING lock
   34136   */
   34137   if( locktype==EXCLUSIVE_LOCK && res ){
   34138     newLocktype = PENDING_LOCK;
   34139     gotPendingLock = 0;
   34140   }
   34141 
   34142   /* Acquire an EXCLUSIVE lock
   34143   */
   34144   if( locktype==EXCLUSIVE_LOCK && res ){
   34145     assert( pFile->locktype>=SHARED_LOCK );
   34146     res = unlockReadLock(pFile);
   34147     OSTRACE(("unreadlock = %d\n", res));
   34148     res = osLockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34149     if( res ){
   34150       newLocktype = EXCLUSIVE_LOCK;
   34151     }else{
   34152       lastErrno = osGetLastError();
   34153       OSTRACE(("error-code = %d\n", lastErrno));
   34154       getReadLock(pFile);
   34155     }
   34156   }
   34157 
   34158   /* If we are holding a PENDING lock that ought to be released, then
   34159   ** release it now.
   34160   */
   34161   if( gotPendingLock && locktype==SHARED_LOCK ){
   34162     osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   34163   }
   34164 
   34165   /* Update the state of the lock has held in the file descriptor then
   34166   ** return the appropriate result code.
   34167   */
   34168   if( res ){
   34169     rc = SQLITE_OK;
   34170   }else{
   34171     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   34172            locktype, newLocktype));
   34173     pFile->lastErrno = lastErrno;
   34174     rc = SQLITE_BUSY;
   34175   }
   34176   pFile->locktype = (u8)newLocktype;
   34177   return rc;
   34178 }
   34179 
   34180 /*
   34181 ** This routine checks if there is a RESERVED lock held on the specified
   34182 ** file by this or any other process. If such a lock is held, return
   34183 ** non-zero, otherwise zero.
   34184 */
   34185 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   34186   int rc;
   34187   winFile *pFile = (winFile*)id;
   34188 
   34189   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   34190 
   34191   assert( id!=0 );
   34192   if( pFile->locktype>=RESERVED_LOCK ){
   34193     rc = 1;
   34194     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
   34195   }else{
   34196     rc = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34197     if( rc ){
   34198       osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34199     }
   34200     rc = !rc;
   34201     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
   34202   }
   34203   *pResOut = rc;
   34204   return SQLITE_OK;
   34205 }
   34206 
   34207 /*
   34208 ** Lower the locking level on file descriptor id to locktype.  locktype
   34209 ** must be either NO_LOCK or SHARED_LOCK.
   34210 **
   34211 ** If the locking level of the file descriptor is already at or below
   34212 ** the requested locking level, this routine is a no-op.
   34213 **
   34214 ** It is not possible for this routine to fail if the second argument
   34215 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   34216 ** might return SQLITE_IOERR;
   34217 */
   34218 static int winUnlock(sqlite3_file *id, int locktype){
   34219   int type;
   34220   winFile *pFile = (winFile*)id;
   34221   int rc = SQLITE_OK;
   34222   assert( pFile!=0 );
   34223   assert( locktype<=SHARED_LOCK );
   34224   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
   34225           pFile->locktype, pFile->sharedLockByte));
   34226   type = pFile->locktype;
   34227   if( type>=EXCLUSIVE_LOCK ){
   34228     osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   34229     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
   34230       /* This should never happen.  We should always be able to
   34231       ** reacquire the read lock */
   34232       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
   34233                "winUnlock", pFile->zPath);
   34234     }
   34235   }
   34236   if( type>=RESERVED_LOCK ){
   34237     osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   34238   }
   34239   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   34240     unlockReadLock(pFile);
   34241   }
   34242   if( type>=PENDING_LOCK ){
   34243     osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   34244   }
   34245   pFile->locktype = (u8)locktype;
   34246   return rc;
   34247 }
   34248 
   34249 /*
   34250 ** If *pArg is inititially negative then this is a query.  Set *pArg to
   34251 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
   34252 **
   34253 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
   34254 */
   34255 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
   34256   if( *pArg<0 ){
   34257     *pArg = (pFile->ctrlFlags & mask)!=0;
   34258   }else if( (*pArg)==0 ){
   34259     pFile->ctrlFlags &= ~mask;
   34260   }else{
   34261     pFile->ctrlFlags |= mask;
   34262   }
   34263 }
   34264 
   34265 /*
   34266 ** Control and query of the open file handle.
   34267 */
   34268 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   34269   winFile *pFile = (winFile*)id;
   34270   switch( op ){
   34271     case SQLITE_FCNTL_LOCKSTATE: {
   34272       *(int*)pArg = pFile->locktype;
   34273       return SQLITE_OK;
   34274     }
   34275     case SQLITE_LAST_ERRNO: {
   34276       *(int*)pArg = (int)pFile->lastErrno;
   34277       return SQLITE_OK;
   34278     }
   34279     case SQLITE_FCNTL_CHUNK_SIZE: {
   34280       pFile->szChunk = *(int *)pArg;
   34281       return SQLITE_OK;
   34282     }
   34283     case SQLITE_FCNTL_SIZE_HINT: {
   34284       if( pFile->szChunk>0 ){
   34285         sqlite3_int64 oldSz;
   34286         int rc = winFileSize(id, &oldSz);
   34287         if( rc==SQLITE_OK ){
   34288           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
   34289           if( newSz>oldSz ){
   34290             SimulateIOErrorBenign(1);
   34291             rc = winTruncate(id, newSz);
   34292             SimulateIOErrorBenign(0);
   34293           }
   34294         }
   34295         return rc;
   34296       }
   34297       return SQLITE_OK;
   34298     }
   34299     case SQLITE_FCNTL_PERSIST_WAL: {
   34300       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
   34301       return SQLITE_OK;
   34302     }
   34303     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
   34304       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
   34305       return SQLITE_OK;
   34306     }
   34307     case SQLITE_FCNTL_VFSNAME: {
   34308       *(char**)pArg = sqlite3_mprintf("win32");
   34309       return SQLITE_OK;
   34310     }
   34311     case SQLITE_FCNTL_WIN32_AV_RETRY: {
   34312       int *a = (int*)pArg;
   34313       if( a[0]>0 ){
   34314         win32IoerrRetry = a[0];
   34315       }else{
   34316         a[0] = win32IoerrRetry;
   34317       }
   34318       if( a[1]>0 ){
   34319         win32IoerrRetryDelay = a[1];
   34320       }else{
   34321         a[1] = win32IoerrRetryDelay;
   34322       }
   34323       return SQLITE_OK;
   34324     }
   34325   }
   34326   return SQLITE_NOTFOUND;
   34327 }
   34328 
   34329 /*
   34330 ** Return the sector size in bytes of the underlying block device for
   34331 ** the specified file. This is almost always 512 bytes, but may be
   34332 ** larger for some devices.
   34333 **
   34334 ** SQLite code assumes this function cannot fail. It also assumes that
   34335 ** if two files are created in the same file-system directory (i.e.
   34336 ** a database and its journal file) that the sector size will be the
   34337 ** same for both.
   34338 */
   34339 static int winSectorSize(sqlite3_file *id){
   34340   (void)id;
   34341   return SQLITE_DEFAULT_SECTOR_SIZE;
   34342 }
   34343 
   34344 /*
   34345 ** Return a vector of device characteristics.
   34346 */
   34347 static int winDeviceCharacteristics(sqlite3_file *id){
   34348   winFile *p = (winFile*)id;
   34349   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
   34350          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
   34351 }
   34352 
   34353 #ifndef SQLITE_OMIT_WAL
   34354 
   34355 /*
   34356 ** Windows will only let you create file view mappings
   34357 ** on allocation size granularity boundaries.
   34358 ** During sqlite3_os_init() we do a GetSystemInfo()
   34359 ** to get the granularity size.
   34360 */
   34361 SYSTEM_INFO winSysInfo;
   34362 
   34363 /*
   34364 ** Helper functions to obtain and relinquish the global mutex. The
   34365 ** global mutex is used to protect the winLockInfo objects used by
   34366 ** this file, all of which may be shared by multiple threads.
   34367 **
   34368 ** Function winShmMutexHeld() is used to assert() that the global mutex
   34369 ** is held when required. This function is only used as part of assert()
   34370 ** statements. e.g.
   34371 **
   34372 **   winShmEnterMutex()
   34373 **     assert( winShmMutexHeld() );
   34374 **   winShmLeaveMutex()
   34375 */
   34376 static void winShmEnterMutex(void){
   34377   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34378 }
   34379 static void winShmLeaveMutex(void){
   34380   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34381 }
   34382 #ifdef SQLITE_DEBUG
   34383 static int winShmMutexHeld(void) {
   34384   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   34385 }
   34386 #endif
   34387 
   34388 /*
   34389 ** Object used to represent a single file opened and mmapped to provide
   34390 ** shared memory.  When multiple threads all reference the same
   34391 ** log-summary, each thread has its own winFile object, but they all
   34392 ** point to a single instance of this object.  In other words, each
   34393 ** log-summary is opened only once per process.
   34394 **
   34395 ** winShmMutexHeld() must be true when creating or destroying
   34396 ** this object or while reading or writing the following fields:
   34397 **
   34398 **      nRef
   34399 **      pNext
   34400 **
   34401 ** The following fields are read-only after the object is created:
   34402 **
   34403 **      fid
   34404 **      zFilename
   34405 **
   34406 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   34407 ** winShmMutexHeld() is true when reading or writing any other field
   34408 ** in this structure.
   34409 **
   34410 */
   34411 struct winShmNode {
   34412   sqlite3_mutex *mutex;      /* Mutex to access this object */
   34413   char *zFilename;           /* Name of the file */
   34414   winFile hFile;             /* File handle from winOpen */
   34415 
   34416   int szRegion;              /* Size of shared-memory regions */
   34417   int nRegion;               /* Size of array apRegion */
   34418   struct ShmRegion {
   34419     HANDLE hMap;             /* File handle from CreateFileMapping */
   34420     void *pMap;
   34421   } *aRegion;
   34422   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   34423 
   34424   int nRef;                  /* Number of winShm objects pointing to this */
   34425   winShm *pFirst;            /* All winShm objects pointing to this */
   34426   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   34427 #ifdef SQLITE_DEBUG
   34428   u8 nextShmId;              /* Next available winShm.id value */
   34429 #endif
   34430 };
   34431 
   34432 /*
   34433 ** A global array of all winShmNode objects.
   34434 **
   34435 ** The winShmMutexHeld() must be true while reading or writing this list.
   34436 */
   34437 static winShmNode *winShmNodeList = 0;
   34438 
   34439 /*
   34440 ** Structure used internally by this VFS to record the state of an
   34441 ** open shared memory connection.
   34442 **
   34443 ** The following fields are initialized when this object is created and
   34444 ** are read-only thereafter:
   34445 **
   34446 **    winShm.pShmNode
   34447 **    winShm.id
   34448 **
   34449 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   34450 ** while accessing any read/write fields.
   34451 */
   34452 struct winShm {
   34453   winShmNode *pShmNode;      /* The underlying winShmNode object */
   34454   winShm *pNext;             /* Next winShm with the same winShmNode */
   34455   u8 hasMutex;               /* True if holding the winShmNode mutex */
   34456   u16 sharedMask;            /* Mask of shared locks held */
   34457   u16 exclMask;              /* Mask of exclusive locks held */
   34458 #ifdef SQLITE_DEBUG
   34459   u8 id;                     /* Id of this connection with its winShmNode */
   34460 #endif
   34461 };
   34462 
   34463 /*
   34464 ** Constants used for locking
   34465 */
   34466 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   34467 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   34468 
   34469 /*
   34470 ** Apply advisory locks for all n bytes beginning at ofst.
   34471 */
   34472 #define _SHM_UNLCK  1
   34473 #define _SHM_RDLCK  2
   34474 #define _SHM_WRLCK  3
   34475 static int winShmSystemLock(
   34476   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   34477   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
   34478   int ofst,             /* Offset to first byte to be locked/unlocked */
   34479   int nByte             /* Number of bytes to lock or unlock */
   34480 ){
   34481   OVERLAPPED ovlp;
   34482   DWORD dwFlags;
   34483   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   34484 
   34485   /* Access to the winShmNode object is serialized by the caller */
   34486   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
   34487 
   34488   /* Initialize the locking parameters */
   34489   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   34490   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   34491 
   34492   memset(&ovlp, 0, sizeof(OVERLAPPED));
   34493   ovlp.Offset = ofst;
   34494 
   34495   /* Release/Acquire the system-level lock */
   34496   if( lockType==_SHM_UNLCK ){
   34497     rc = osUnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
   34498   }else{
   34499     rc = osLockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
   34500   }
   34501 
   34502   if( rc!= 0 ){
   34503     rc = SQLITE_OK;
   34504   }else{
   34505     pFile->lastErrno =  osGetLastError();
   34506     rc = SQLITE_BUSY;
   34507   }
   34508 
   34509   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
   34510            pFile->hFile.h,
   34511            rc==SQLITE_OK ? "ok" : "failed",
   34512            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
   34513            pFile->lastErrno));
   34514 
   34515   return rc;
   34516 }
   34517 
   34518 /* Forward references to VFS methods */
   34519 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   34520 static int winDelete(sqlite3_vfs *,const char*,int);
   34521 
   34522 /*
   34523 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   34524 **
   34525 ** This is not a VFS shared-memory method; it is a utility function called
   34526 ** by VFS shared-memory methods.
   34527 */
   34528 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   34529   winShmNode **pp;
   34530   winShmNode *p;
   34531   BOOL bRc;
   34532   assert( winShmMutexHeld() );
   34533   pp = &winShmNodeList;
   34534   while( (p = *pp)!=0 ){
   34535     if( p->nRef==0 ){
   34536       int i;
   34537       if( p->mutex ) sqlite3_mutex_free(p->mutex);
   34538       for(i=0; i<p->nRegion; i++){
   34539         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
   34540         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
   34541                  (int)osGetCurrentProcessId(), i,
   34542                  bRc ? "ok" : "failed"));
   34543         bRc = osCloseHandle(p->aRegion[i].hMap);
   34544         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
   34545                  (int)osGetCurrentProcessId(), i,
   34546                  bRc ? "ok" : "failed"));
   34547       }
   34548       if( p->hFile.h != INVALID_HANDLE_VALUE ){
   34549         SimulateIOErrorBenign(1);
   34550         winClose((sqlite3_file *)&p->hFile);
   34551         SimulateIOErrorBenign(0);
   34552       }
   34553       if( deleteFlag ){
   34554         SimulateIOErrorBenign(1);
   34555         sqlite3BeginBenignMalloc();
   34556         winDelete(pVfs, p->zFilename, 0);
   34557         sqlite3EndBenignMalloc();
   34558         SimulateIOErrorBenign(0);
   34559       }
   34560       *pp = p->pNext;
   34561       sqlite3_free(p->aRegion);
   34562       sqlite3_free(p);
   34563     }else{
   34564       pp = &p->pNext;
   34565     }
   34566   }
   34567 }
   34568 
   34569 /*
   34570 ** Open the shared-memory area associated with database file pDbFd.
   34571 **
   34572 ** When opening a new shared-memory file, if no other instances of that
   34573 ** file are currently open, in this process or in other processes, then
   34574 ** the file must be truncated to zero length or have its header cleared.
   34575 */
   34576 static int winOpenSharedMemory(winFile *pDbFd){
   34577   struct winShm *p;                  /* The connection to be opened */
   34578   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
   34579   int rc;                            /* Result code */
   34580   struct winShmNode *pNew;           /* Newly allocated winShmNode */
   34581   int nName;                         /* Size of zName in bytes */
   34582 
   34583   assert( pDbFd->pShm==0 );    /* Not previously opened */
   34584 
   34585   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   34586   ** allocate space for a new winShmNode and filename.
   34587   */
   34588   p = sqlite3_malloc( sizeof(*p) );
   34589   if( p==0 ) return SQLITE_IOERR_NOMEM;
   34590   memset(p, 0, sizeof(*p));
   34591   nName = sqlite3Strlen30(pDbFd->zPath);
   34592   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
   34593   if( pNew==0 ){
   34594     sqlite3_free(p);
   34595     return SQLITE_IOERR_NOMEM;
   34596   }
   34597   memset(pNew, 0, sizeof(*pNew) + nName + 17);
   34598   pNew->zFilename = (char*)&pNew[1];
   34599   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   34600   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
   34601 
   34602   /* Look to see if there is an existing winShmNode that can be used.
   34603   ** If no matching winShmNode currently exists, create a new one.
   34604   */
   34605   winShmEnterMutex();
   34606   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   34607     /* TBD need to come up with better match here.  Perhaps
   34608     ** use FILE_ID_BOTH_DIR_INFO Structure.
   34609     */
   34610     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   34611   }
   34612   if( pShmNode ){
   34613     sqlite3_free(pNew);
   34614   }else{
   34615     pShmNode = pNew;
   34616     pNew = 0;
   34617     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   34618     pShmNode->pNext = winShmNodeList;
   34619     winShmNodeList = pShmNode;
   34620 
   34621     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   34622     if( pShmNode->mutex==0 ){
   34623       rc = SQLITE_IOERR_NOMEM;
   34624       goto shm_open_err;
   34625     }
   34626 
   34627     rc = winOpen(pDbFd->pVfs,
   34628                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
   34629                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
   34630                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
   34631                  0);
   34632     if( SQLITE_OK!=rc ){
   34633       goto shm_open_err;
   34634     }
   34635 
   34636     /* Check to see if another process is holding the dead-man switch.
   34637     ** If not, truncate the file to zero length.
   34638     */
   34639     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
   34640       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
   34641       if( rc!=SQLITE_OK ){
   34642         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
   34643                  "winOpenShm", pDbFd->zPath);
   34644       }
   34645     }
   34646     if( rc==SQLITE_OK ){
   34647       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   34648       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
   34649     }
   34650     if( rc ) goto shm_open_err;
   34651   }
   34652 
   34653   /* Make the new connection a child of the winShmNode */
   34654   p->pShmNode = pShmNode;
   34655 #ifdef SQLITE_DEBUG
   34656   p->id = pShmNode->nextShmId++;
   34657 #endif
   34658   pShmNode->nRef++;
   34659   pDbFd->pShm = p;
   34660   winShmLeaveMutex();
   34661 
   34662   /* The reference count on pShmNode has already been incremented under
   34663   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   34664   ** new (struct winShm) object to the pShmNode has been set. All that is
   34665   ** left to do is to link the new object into the linked list starting
   34666   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   34667   ** mutex.
   34668   */
   34669   sqlite3_mutex_enter(pShmNode->mutex);
   34670   p->pNext = pShmNode->pFirst;
   34671   pShmNode->pFirst = p;
   34672   sqlite3_mutex_leave(pShmNode->mutex);
   34673   return SQLITE_OK;
   34674 
   34675   /* Jump here on any error */
   34676 shm_open_err:
   34677   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   34678   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   34679   sqlite3_free(p);
   34680   sqlite3_free(pNew);
   34681   winShmLeaveMutex();
   34682   return rc;
   34683 }
   34684 
   34685 /*
   34686 ** Close a connection to shared-memory.  Delete the underlying
   34687 ** storage if deleteFlag is true.
   34688 */
   34689 static int winShmUnmap(
   34690   sqlite3_file *fd,          /* Database holding shared memory */
   34691   int deleteFlag             /* Delete after closing if true */
   34692 ){
   34693   winFile *pDbFd;       /* Database holding shared-memory */
   34694   winShm *p;            /* The connection to be closed */
   34695   winShmNode *pShmNode; /* The underlying shared-memory file */
   34696   winShm **pp;          /* For looping over sibling connections */
   34697 
   34698   pDbFd = (winFile*)fd;
   34699   p = pDbFd->pShm;
   34700   if( p==0 ) return SQLITE_OK;
   34701   pShmNode = p->pShmNode;
   34702 
   34703   /* Remove connection p from the set of connections associated
   34704   ** with pShmNode */
   34705   sqlite3_mutex_enter(pShmNode->mutex);
   34706   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   34707   *pp = p->pNext;
   34708 
   34709   /* Free the connection p */
   34710   sqlite3_free(p);
   34711   pDbFd->pShm = 0;
   34712   sqlite3_mutex_leave(pShmNode->mutex);
   34713 
   34714   /* If pShmNode->nRef has reached 0, then close the underlying
   34715   ** shared-memory file, too */
   34716   winShmEnterMutex();
   34717   assert( pShmNode->nRef>0 );
   34718   pShmNode->nRef--;
   34719   if( pShmNode->nRef==0 ){
   34720     winShmPurge(pDbFd->pVfs, deleteFlag);
   34721   }
   34722   winShmLeaveMutex();
   34723 
   34724   return SQLITE_OK;
   34725 }
   34726 
   34727 /*
   34728 ** Change the lock state for a shared-memory segment.
   34729 */
   34730 static int winShmLock(
   34731   sqlite3_file *fd,          /* Database file holding the shared memory */
   34732   int ofst,                  /* First lock to acquire or release */
   34733   int n,                     /* Number of locks to acquire or release */
   34734   int flags                  /* What to do with the lock */
   34735 ){
   34736   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   34737   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   34738   winShm *pX;                           /* For looping over all siblings */
   34739   winShmNode *pShmNode = p->pShmNode;
   34740   int rc = SQLITE_OK;                   /* Result code */
   34741   u16 mask;                             /* Mask of locks to take or release */
   34742 
   34743   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   34744   assert( n>=1 );
   34745   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   34746        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   34747        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   34748        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   34749   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   34750 
   34751   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   34752   assert( n>1 || mask==(1<<ofst) );
   34753   sqlite3_mutex_enter(pShmNode->mutex);
   34754   if( flags & SQLITE_SHM_UNLOCK ){
   34755     u16 allMask = 0; /* Mask of locks held by siblings */
   34756 
   34757     /* See if any siblings hold this same lock */
   34758     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34759       if( pX==p ) continue;
   34760       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   34761       allMask |= pX->sharedMask;
   34762     }
   34763 
   34764     /* Unlock the system-level locks */
   34765     if( (mask & allMask)==0 ){
   34766       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
   34767     }else{
   34768       rc = SQLITE_OK;
   34769     }
   34770 
   34771     /* Undo the local locks */
   34772     if( rc==SQLITE_OK ){
   34773       p->exclMask &= ~mask;
   34774       p->sharedMask &= ~mask;
   34775     }
   34776   }else if( flags & SQLITE_SHM_SHARED ){
   34777     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   34778 
   34779     /* Find out which shared locks are already held by sibling connections.
   34780     ** If any sibling already holds an exclusive lock, go ahead and return
   34781     ** SQLITE_BUSY.
   34782     */
   34783     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34784       if( (pX->exclMask & mask)!=0 ){
   34785         rc = SQLITE_BUSY;
   34786         break;
   34787       }
   34788       allShared |= pX->sharedMask;
   34789     }
   34790 
   34791     /* Get shared locks at the system level, if necessary */
   34792     if( rc==SQLITE_OK ){
   34793       if( (allShared & mask)==0 ){
   34794         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
   34795       }else{
   34796         rc = SQLITE_OK;
   34797       }
   34798     }
   34799 
   34800     /* Get the local shared locks */
   34801     if( rc==SQLITE_OK ){
   34802       p->sharedMask |= mask;
   34803     }
   34804   }else{
   34805     /* Make sure no sibling connections hold locks that will block this
   34806     ** lock.  If any do, return SQLITE_BUSY right away.
   34807     */
   34808     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   34809       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   34810         rc = SQLITE_BUSY;
   34811         break;
   34812       }
   34813     }
   34814 
   34815     /* Get the exclusive locks at the system level.  Then if successful
   34816     ** also mark the local connection as being locked.
   34817     */
   34818     if( rc==SQLITE_OK ){
   34819       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
   34820       if( rc==SQLITE_OK ){
   34821         assert( (p->sharedMask & mask)==0 );
   34822         p->exclMask |= mask;
   34823       }
   34824     }
   34825   }
   34826   sqlite3_mutex_leave(pShmNode->mutex);
   34827   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
   34828            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
   34829            rc ? "failed" : "ok"));
   34830   return rc;
   34831 }
   34832 
   34833 /*
   34834 ** Implement a memory barrier or memory fence on shared memory.
   34835 **
   34836 ** All loads and stores begun before the barrier must complete before
   34837 ** any load or store begun after the barrier.
   34838 */
   34839 static void winShmBarrier(
   34840   sqlite3_file *fd          /* Database holding the shared memory */
   34841 ){
   34842   UNUSED_PARAMETER(fd);
   34843   /* MemoryBarrier(); // does not work -- do not know why not */
   34844   winShmEnterMutex();
   34845   winShmLeaveMutex();
   34846 }
   34847 
   34848 /*
   34849 ** This function is called to obtain a pointer to region iRegion of the
   34850 ** shared-memory associated with the database file fd. Shared-memory regions
   34851 ** are numbered starting from zero. Each shared-memory region is szRegion
   34852 ** bytes in size.
   34853 **
   34854 ** If an error occurs, an error code is returned and *pp is set to NULL.
   34855 **
   34856 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   34857 ** region has not been allocated (by any client, including one running in a
   34858 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   34859 ** isWrite is non-zero and the requested shared-memory region has not yet
   34860 ** been allocated, it is allocated by this function.
   34861 **
   34862 ** If the shared-memory region has already been allocated or is allocated by
   34863 ** this call as described above, then it is mapped into this processes
   34864 ** address space (if it is not already), *pp is set to point to the mapped
   34865 ** memory and SQLITE_OK returned.
   34866 */
   34867 static int winShmMap(
   34868   sqlite3_file *fd,               /* Handle open on database file */
   34869   int iRegion,                    /* Region to retrieve */
   34870   int szRegion,                   /* Size of regions */
   34871   int isWrite,                    /* True to extend file if necessary */
   34872   void volatile **pp              /* OUT: Mapped memory */
   34873 ){
   34874   winFile *pDbFd = (winFile*)fd;
   34875   winShm *p = pDbFd->pShm;
   34876   winShmNode *pShmNode;
   34877   int rc = SQLITE_OK;
   34878 
   34879   if( !p ){
   34880     rc = winOpenSharedMemory(pDbFd);
   34881     if( rc!=SQLITE_OK ) return rc;
   34882     p = pDbFd->pShm;
   34883   }
   34884   pShmNode = p->pShmNode;
   34885 
   34886   sqlite3_mutex_enter(pShmNode->mutex);
   34887   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   34888 
   34889   if( pShmNode->nRegion<=iRegion ){
   34890     struct ShmRegion *apNew;           /* New aRegion[] array */
   34891     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   34892     sqlite3_int64 sz;                  /* Current size of wal-index file */
   34893 
   34894     pShmNode->szRegion = szRegion;
   34895 
   34896     /* The requested region is not mapped into this processes address space.
   34897     ** Check to see if it has been allocated (i.e. if the wal-index file is
   34898     ** large enough to contain the requested region).
   34899     */
   34900     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   34901     if( rc!=SQLITE_OK ){
   34902       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   34903                "winShmMap1", pDbFd->zPath);
   34904       goto shmpage_out;
   34905     }
   34906 
   34907     if( sz<nByte ){
   34908       /* The requested memory region does not exist. If isWrite is set to
   34909       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   34910       **
   34911       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   34912       ** the requested memory region.
   34913       */
   34914       if( !isWrite ) goto shmpage_out;
   34915       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   34916       if( rc!=SQLITE_OK ){
   34917         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
   34918                  "winShmMap2", pDbFd->zPath);
   34919         goto shmpage_out;
   34920       }
   34921     }
   34922 
   34923     /* Map the requested memory region into this processes address space. */
   34924     apNew = (struct ShmRegion *)sqlite3_realloc(
   34925         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   34926     );
   34927     if( !apNew ){
   34928       rc = SQLITE_IOERR_NOMEM;
   34929       goto shmpage_out;
   34930     }
   34931     pShmNode->aRegion = apNew;
   34932 
   34933     while( pShmNode->nRegion<=iRegion ){
   34934       HANDLE hMap;                /* file-mapping handle */
   34935       void *pMap = 0;             /* Mapped memory region */
   34936 
   34937       hMap = osCreateFileMapping(pShmNode->hFile.h,
   34938           NULL, PAGE_READWRITE, 0, nByte, NULL
   34939       );
   34940       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
   34941                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
   34942                hMap ? "ok" : "failed"));
   34943       if( hMap ){
   34944         int iOffset = pShmNode->nRegion*szRegion;
   34945         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   34946         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   34947             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   34948         );
   34949         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
   34950                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
   34951                  szRegion, pMap ? "ok" : "failed"));
   34952       }
   34953       if( !pMap ){
   34954         pShmNode->lastErrno = osGetLastError();
   34955         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
   34956                  "winShmMap3", pDbFd->zPath);
   34957         if( hMap ) osCloseHandle(hMap);
   34958         goto shmpage_out;
   34959       }
   34960 
   34961       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   34962       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   34963       pShmNode->nRegion++;
   34964     }
   34965   }
   34966 
   34967 shmpage_out:
   34968   if( pShmNode->nRegion>iRegion ){
   34969     int iOffset = iRegion*szRegion;
   34970     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   34971     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   34972     *pp = (void *)&p[iOffsetShift];
   34973   }else{
   34974     *pp = 0;
   34975   }
   34976   sqlite3_mutex_leave(pShmNode->mutex);
   34977   return rc;
   34978 }
   34979 
   34980 #else
   34981 # define winShmMap     0
   34982 # define winShmLock    0
   34983 # define winShmBarrier 0
   34984 # define winShmUnmap   0
   34985 #endif /* #ifndef SQLITE_OMIT_WAL */
   34986 
   34987 /*
   34988 ** Here ends the implementation of all sqlite3_file methods.
   34989 **
   34990 ********************** End sqlite3_file Methods *******************************
   34991 ******************************************************************************/
   34992 
   34993 /*
   34994 ** This vector defines all the methods that can operate on an
   34995 ** sqlite3_file for win32.
   34996 */
   34997 static const sqlite3_io_methods winIoMethod = {
   34998   2,                              /* iVersion */
   34999   winClose,                       /* xClose */
   35000   winRead,                        /* xRead */
   35001   winWrite,                       /* xWrite */
   35002   winTruncate,                    /* xTruncate */
   35003   winSync,                        /* xSync */
   35004   winFileSize,                    /* xFileSize */
   35005   winLock,                        /* xLock */
   35006   winUnlock,                      /* xUnlock */
   35007   winCheckReservedLock,           /* xCheckReservedLock */
   35008   winFileControl,                 /* xFileControl */
   35009   winSectorSize,                  /* xSectorSize */
   35010   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   35011   winShmMap,                      /* xShmMap */
   35012   winShmLock,                     /* xShmLock */
   35013   winShmBarrier,                  /* xShmBarrier */
   35014   winShmUnmap                     /* xShmUnmap */
   35015 };
   35016 
   35017 /****************************************************************************
   35018 **************************** sqlite3_vfs methods ****************************
   35019 **
   35020 ** This division contains the implementation of methods on the
   35021 ** sqlite3_vfs object.
   35022 */
   35023 
   35024 /*
   35025 ** Convert a UTF-8 filename into whatever form the underlying
   35026 ** operating system wants filenames in.  Space to hold the result
   35027 ** is obtained from malloc and must be freed by the calling
   35028 ** function.
   35029 */
   35030 static void *convertUtf8Filename(const char *zFilename){
   35031   void *zConverted = 0;
   35032   if( isNT() ){
   35033     zConverted = utf8ToUnicode(zFilename);
   35034 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35035 */
   35036 #if SQLITE_OS_WINCE==0
   35037   }else{
   35038     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
   35039 #endif
   35040   }
   35041   /* caller will handle out of memory */
   35042   return zConverted;
   35043 }
   35044 
   35045 /*
   35046 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   35047 ** hold at pVfs->mxPathname characters.
   35048 */
   35049 static int getTempname(int nBuf, char *zBuf){
   35050   static char zChars[] =
   35051     "abcdefghijklmnopqrstuvwxyz"
   35052     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   35053     "0123456789";
   35054   size_t i, j;
   35055   char zTempPath[MAX_PATH+2];
   35056 
   35057   /* It's odd to simulate an io-error here, but really this is just
   35058   ** using the io-error infrastructure to test that SQLite handles this
   35059   ** function failing.
   35060   */
   35061   SimulateIOError( return SQLITE_IOERR );
   35062 
   35063   if( sqlite3_temp_directory ){
   35064     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
   35065   }else if( isNT() ){
   35066     char *zMulti;
   35067     WCHAR zWidePath[MAX_PATH];
   35068     osGetTempPathW(MAX_PATH-30, zWidePath);
   35069     zMulti = unicodeToUtf8(zWidePath);
   35070     if( zMulti ){
   35071       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
   35072       sqlite3_free(zMulti);
   35073     }else{
   35074       return SQLITE_IOERR_NOMEM;
   35075     }
   35076 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35077 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35078 ** it's important to not reference them for WINCE builds.
   35079 */
   35080 #if SQLITE_OS_WINCE==0
   35081   }else{
   35082     char *zUtf8;
   35083     char zMbcsPath[MAX_PATH];
   35084     osGetTempPathA(MAX_PATH-30, zMbcsPath);
   35085     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   35086     if( zUtf8 ){
   35087       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
   35088       sqlite3_free(zUtf8);
   35089     }else{
   35090       return SQLITE_IOERR_NOMEM;
   35091     }
   35092 #endif
   35093   }
   35094 
   35095   /* Check that the output buffer is large enough for the temporary file
   35096   ** name. If it is not, return SQLITE_ERROR.
   35097   */
   35098   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
   35099     return SQLITE_ERROR;
   35100   }
   35101 
   35102   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
   35103   zTempPath[i] = 0;
   35104 
   35105   sqlite3_snprintf(nBuf-18, zBuf,
   35106                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
   35107   j = sqlite3Strlen30(zBuf);
   35108   sqlite3_randomness(15, &zBuf[j]);
   35109   for(i=0; i<15; i++, j++){
   35110     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   35111   }
   35112   zBuf[j] = 0;
   35113   zBuf[j+1] = 0;
   35114 
   35115   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
   35116   return SQLITE_OK;
   35117 }
   35118 
   35119 /*
   35120 ** Open a file.
   35121 */
   35122 static int winOpen(
   35123   sqlite3_vfs *pVfs,        /* Not used */
   35124   const char *zName,        /* Name of the file (UTF-8) */
   35125   sqlite3_file *id,         /* Write the SQLite file handle here */
   35126   int flags,                /* Open mode flags */
   35127   int *pOutFlags            /* Status return flags */
   35128 ){
   35129   HANDLE h;
   35130   DWORD lastErrno;
   35131   DWORD dwDesiredAccess;
   35132   DWORD dwShareMode;
   35133   DWORD dwCreationDisposition;
   35134   DWORD dwFlagsAndAttributes = 0;
   35135 #if SQLITE_OS_WINCE
   35136   int isTemp = 0;
   35137 #endif
   35138   winFile *pFile = (winFile*)id;
   35139   void *zConverted;              /* Filename in OS encoding */
   35140   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   35141   int cnt = 0;
   35142 
   35143   /* If argument zPath is a NULL pointer, this function is required to open
   35144   ** a temporary file. Use this buffer to store the file name in.
   35145   */
   35146   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
   35147 
   35148   int rc = SQLITE_OK;            /* Function Return Code */
   35149 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   35150   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   35151 #endif
   35152 
   35153   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   35154   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   35155   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   35156 #ifndef NDEBUG
   35157   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   35158 #endif
   35159   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   35160 
   35161 #ifndef NDEBUG
   35162   int isOpenJournal = (isCreate && (
   35163         eType==SQLITE_OPEN_MASTER_JOURNAL
   35164      || eType==SQLITE_OPEN_MAIN_JOURNAL
   35165      || eType==SQLITE_OPEN_WAL
   35166   ));
   35167 #endif
   35168 
   35169   /* Check the following statements are true:
   35170   **
   35171   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   35172   **   (b) if CREATE is set, then READWRITE must also be set, and
   35173   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   35174   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   35175   */
   35176   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   35177   assert(isCreate==0 || isReadWrite);
   35178   assert(isExclusive==0 || isCreate);
   35179   assert(isDelete==0 || isCreate);
   35180 
   35181   /* The main DB, main journal, WAL file and master journal are never
   35182   ** automatically deleted. Nor are they ever temporary files.  */
   35183   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   35184   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   35185   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   35186   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   35187 
   35188   /* Assert that the upper layer has set one of the "file-type" flags. */
   35189   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   35190        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   35191        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   35192        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   35193   );
   35194 
   35195   assert( id!=0 );
   35196   UNUSED_PARAMETER(pVfs);
   35197 
   35198   pFile->h = INVALID_HANDLE_VALUE;
   35199 
   35200   /* If the second argument to this function is NULL, generate a
   35201   ** temporary file name to use
   35202   */
   35203   if( !zUtf8Name ){
   35204     assert(isDelete && !isOpenJournal);
   35205     rc = getTempname(MAX_PATH+2, zTmpname);
   35206     if( rc!=SQLITE_OK ){
   35207       return rc;
   35208     }
   35209     zUtf8Name = zTmpname;
   35210   }
   35211 
   35212   /* Database filenames are double-zero terminated if they are not
   35213   ** URIs with parameters.  Hence, they can always be passed into
   35214   ** sqlite3_uri_parameter().
   35215   */
   35216   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
   35217         zUtf8Name[strlen(zUtf8Name)+1]==0 );
   35218 
   35219   /* Convert the filename to the system encoding. */
   35220   zConverted = convertUtf8Filename(zUtf8Name);
   35221   if( zConverted==0 ){
   35222     return SQLITE_IOERR_NOMEM;
   35223   }
   35224 
   35225   if( isReadWrite ){
   35226     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   35227   }else{
   35228     dwDesiredAccess = GENERIC_READ;
   35229   }
   35230 
   35231   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   35232   ** created. SQLite doesn't use it to indicate "exclusive access"
   35233   ** as it is usually understood.
   35234   */
   35235   if( isExclusive ){
   35236     /* Creates a new file, only if it does not already exist. */
   35237     /* If the file exists, it fails. */
   35238     dwCreationDisposition = CREATE_NEW;
   35239   }else if( isCreate ){
   35240     /* Open existing file, or create if it doesn't exist */
   35241     dwCreationDisposition = OPEN_ALWAYS;
   35242   }else{
   35243     /* Opens a file, only if it exists. */
   35244     dwCreationDisposition = OPEN_EXISTING;
   35245   }
   35246 
   35247   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   35248 
   35249   if( isDelete ){
   35250 #if SQLITE_OS_WINCE
   35251     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   35252     isTemp = 1;
   35253 #else
   35254     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   35255                                | FILE_ATTRIBUTE_HIDDEN
   35256                                | FILE_FLAG_DELETE_ON_CLOSE;
   35257 #endif
   35258   }else{
   35259     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   35260   }
   35261   /* Reports from the internet are that performance is always
   35262   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   35263 #if SQLITE_OS_WINCE
   35264   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   35265 #endif
   35266 
   35267   if( isNT() ){
   35268     while( (h = osCreateFileW((LPCWSTR)zConverted,
   35269                               dwDesiredAccess,
   35270                               dwShareMode, NULL,
   35271                               dwCreationDisposition,
   35272                               dwFlagsAndAttributes,
   35273                               NULL))==INVALID_HANDLE_VALUE &&
   35274                               retryIoerr(&cnt, &lastErrno) ){}
   35275 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35276 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35277 ** it's important to not reference them for WINCE builds.
   35278 */
   35279 #if SQLITE_OS_WINCE==0
   35280   }else{
   35281     while( (h = osCreateFileA((LPCSTR)zConverted,
   35282                               dwDesiredAccess,
   35283                               dwShareMode, NULL,
   35284                               dwCreationDisposition,
   35285                               dwFlagsAndAttributes,
   35286                               NULL))==INVALID_HANDLE_VALUE &&
   35287                               retryIoerr(&cnt, &lastErrno) ){}
   35288 #endif
   35289   }
   35290 
   35291   logIoerr(cnt);
   35292 
   35293   OSTRACE(("OPEN %d %s 0x%lx %s\n",
   35294            h, zName, dwDesiredAccess,
   35295            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
   35296 
   35297   if( h==INVALID_HANDLE_VALUE ){
   35298     pFile->lastErrno = lastErrno;
   35299     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
   35300     sqlite3_free(zConverted);
   35301     if( isReadWrite && !isExclusive ){
   35302       return winOpen(pVfs, zName, id,
   35303              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
   35304     }else{
   35305       return SQLITE_CANTOPEN_BKPT;
   35306     }
   35307   }
   35308 
   35309   if( pOutFlags ){
   35310     if( isReadWrite ){
   35311       *pOutFlags = SQLITE_OPEN_READWRITE;
   35312     }else{
   35313       *pOutFlags = SQLITE_OPEN_READONLY;
   35314     }
   35315   }
   35316 
   35317   memset(pFile, 0, sizeof(*pFile));
   35318   pFile->pMethod = &winIoMethod;
   35319   pFile->h = h;
   35320   pFile->lastErrno = NO_ERROR;
   35321   pFile->pVfs = pVfs;
   35322   pFile->pShm = 0;
   35323   pFile->zPath = zName;
   35324   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
   35325     pFile->ctrlFlags |= WINFILE_PSOW;
   35326   }
   35327 
   35328 #if SQLITE_OS_WINCE
   35329   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   35330        && !winceCreateLock(zName, pFile)
   35331   ){
   35332     osCloseHandle(h);
   35333     sqlite3_free(zConverted);
   35334     return SQLITE_CANTOPEN_BKPT;
   35335   }
   35336   if( isTemp ){
   35337     pFile->zDeleteOnClose = zConverted;
   35338   }else
   35339 #endif
   35340   {
   35341     sqlite3_free(zConverted);
   35342   }
   35343 
   35344   OpenCounter(+1);
   35345   return rc;
   35346 }
   35347 
   35348 /*
   35349 ** Delete the named file.
   35350 **
   35351 ** Note that Windows does not allow a file to be deleted if some other
   35352 ** process has it open.  Sometimes a virus scanner or indexing program
   35353 ** will open a journal file shortly after it is created in order to do
   35354 ** whatever it does.  While this other process is holding the
   35355 ** file open, we will be unable to delete it.  To work around this
   35356 ** problem, we delay 100 milliseconds and try to delete again.  Up
   35357 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   35358 ** up and returning an error.
   35359 */
   35360 static int winDelete(
   35361   sqlite3_vfs *pVfs,          /* Not used on win32 */
   35362   const char *zFilename,      /* Name of file to delete */
   35363   int syncDir                 /* Not used on win32 */
   35364 ){
   35365   int cnt = 0;
   35366   int rc;
   35367   DWORD lastErrno;
   35368   void *zConverted;
   35369   UNUSED_PARAMETER(pVfs);
   35370   UNUSED_PARAMETER(syncDir);
   35371 
   35372   SimulateIOError(return SQLITE_IOERR_DELETE);
   35373   zConverted = convertUtf8Filename(zFilename);
   35374   if( zConverted==0 ){
   35375     return SQLITE_IOERR_NOMEM;
   35376   }
   35377   if( isNT() ){
   35378     rc = 1;
   35379     while( osGetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
   35380          (rc = osDeleteFileW(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
   35381     rc = rc ? SQLITE_OK : SQLITE_ERROR;
   35382 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35383 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35384 ** it's important to not reference them for WINCE builds.
   35385 */
   35386 #if SQLITE_OS_WINCE==0
   35387   }else{
   35388     rc = 1;
   35389     while( osGetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
   35390          (rc = osDeleteFileA(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
   35391     rc = rc ? SQLITE_OK : SQLITE_ERROR;
   35392 #endif
   35393   }
   35394   if( rc ){
   35395     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
   35396              "winDelete", zFilename);
   35397   }else{
   35398     logIoerr(cnt);
   35399   }
   35400   sqlite3_free(zConverted);
   35401   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
   35402   return rc;
   35403 }
   35404 
   35405 /*
   35406 ** Check the existance and status of a file.
   35407 */
   35408 static int winAccess(
   35409   sqlite3_vfs *pVfs,         /* Not used on win32 */
   35410   const char *zFilename,     /* Name of file to check */
   35411   int flags,                 /* Type of test to make on this file */
   35412   int *pResOut               /* OUT: Result */
   35413 ){
   35414   DWORD attr;
   35415   int rc = 0;
   35416   DWORD lastErrno;
   35417   void *zConverted;
   35418   UNUSED_PARAMETER(pVfs);
   35419 
   35420   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   35421   zConverted = convertUtf8Filename(zFilename);
   35422   if( zConverted==0 ){
   35423     return SQLITE_IOERR_NOMEM;
   35424   }
   35425   if( isNT() ){
   35426     int cnt = 0;
   35427     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   35428     memset(&sAttrData, 0, sizeof(sAttrData));
   35429     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
   35430                              GetFileExInfoStandard,
   35431                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
   35432     if( rc ){
   35433       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   35434       ** as if it does not exist.
   35435       */
   35436       if(    flags==SQLITE_ACCESS_EXISTS
   35437           && sAttrData.nFileSizeHigh==0
   35438           && sAttrData.nFileSizeLow==0 ){
   35439         attr = INVALID_FILE_ATTRIBUTES;
   35440       }else{
   35441         attr = sAttrData.dwFileAttributes;
   35442       }
   35443     }else{
   35444       logIoerr(cnt);
   35445       if( lastErrno!=ERROR_FILE_NOT_FOUND ){
   35446         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
   35447         sqlite3_free(zConverted);
   35448         return SQLITE_IOERR_ACCESS;
   35449       }else{
   35450         attr = INVALID_FILE_ATTRIBUTES;
   35451       }
   35452     }
   35453 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35454 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35455 ** it's important to not reference them for WINCE builds.
   35456 */
   35457 #if SQLITE_OS_WINCE==0
   35458   }else{
   35459     attr = osGetFileAttributesA((char*)zConverted);
   35460 #endif
   35461   }
   35462   sqlite3_free(zConverted);
   35463   switch( flags ){
   35464     case SQLITE_ACCESS_READ:
   35465     case SQLITE_ACCESS_EXISTS:
   35466       rc = attr!=INVALID_FILE_ATTRIBUTES;
   35467       break;
   35468     case SQLITE_ACCESS_READWRITE:
   35469       rc = attr!=INVALID_FILE_ATTRIBUTES &&
   35470              (attr & FILE_ATTRIBUTE_READONLY)==0;
   35471       break;
   35472     default:
   35473       assert(!"Invalid flags argument");
   35474   }
   35475   *pResOut = rc;
   35476   return SQLITE_OK;
   35477 }
   35478 
   35479 
   35480 /*
   35481 ** Turn a relative pathname into a full pathname.  Write the full
   35482 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   35483 ** bytes in size.
   35484 */
   35485 static int winFullPathname(
   35486   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   35487   const char *zRelative,        /* Possibly relative input path */
   35488   int nFull,                    /* Size of output buffer in bytes */
   35489   char *zFull                   /* Output buffer */
   35490 ){
   35491 
   35492 #if defined(__CYGWIN__)
   35493   SimulateIOError( return SQLITE_ERROR );
   35494   UNUSED_PARAMETER(nFull);
   35495   cygwin_conv_to_full_win32_path(zRelative, zFull);
   35496   return SQLITE_OK;
   35497 #endif
   35498 
   35499 #if SQLITE_OS_WINCE
   35500   SimulateIOError( return SQLITE_ERROR );
   35501   UNUSED_PARAMETER(nFull);
   35502   /* WinCE has no concept of a relative pathname, or so I am told. */
   35503   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
   35504   return SQLITE_OK;
   35505 #endif
   35506 
   35507 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
   35508   int nByte;
   35509   void *zConverted;
   35510   char *zOut;
   35511 
   35512   /* If this path name begins with "/X:", where "X" is any alphabetic
   35513   ** character, discard the initial "/" from the pathname.
   35514   */
   35515   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
   35516     zRelative++;
   35517   }
   35518 
   35519   /* It's odd to simulate an io-error here, but really this is just
   35520   ** using the io-error infrastructure to test that SQLite handles this
   35521   ** function failing. This function could fail if, for example, the
   35522   ** current working directory has been unlinked.
   35523   */
   35524   SimulateIOError( return SQLITE_ERROR );
   35525   UNUSED_PARAMETER(nFull);
   35526   zConverted = convertUtf8Filename(zRelative);
   35527   if( zConverted==0 ){
   35528     return SQLITE_IOERR_NOMEM;
   35529   }
   35530   if( isNT() ){
   35531     LPWSTR zTemp;
   35532     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
   35533     zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
   35534     if( zTemp==0 ){
   35535       sqlite3_free(zConverted);
   35536       return SQLITE_IOERR_NOMEM;
   35537     }
   35538     osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
   35539     sqlite3_free(zConverted);
   35540     zOut = unicodeToUtf8(zTemp);
   35541     sqlite3_free(zTemp);
   35542 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35543 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35544 ** it's important to not reference them for WINCE builds.
   35545 */
   35546 #if SQLITE_OS_WINCE==0
   35547   }else{
   35548     char *zTemp;
   35549     nByte = osGetFullPathNameA((char*)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     osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   35556     sqlite3_free(zConverted);
   35557     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   35558     sqlite3_free(zTemp);
   35559 #endif
   35560   }
   35561   if( zOut ){
   35562     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
   35563     sqlite3_free(zOut);
   35564     return SQLITE_OK;
   35565   }else{
   35566     return SQLITE_IOERR_NOMEM;
   35567   }
   35568 #endif
   35569 }
   35570 
   35571 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   35572 /*
   35573 ** Interfaces for opening a shared library, finding entry points
   35574 ** within the shared library, and closing the shared library.
   35575 */
   35576 /*
   35577 ** Interfaces for opening a shared library, finding entry points
   35578 ** within the shared library, and closing the shared library.
   35579 */
   35580 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   35581   HANDLE h;
   35582   void *zConverted = convertUtf8Filename(zFilename);
   35583   UNUSED_PARAMETER(pVfs);
   35584   if( zConverted==0 ){
   35585     return 0;
   35586   }
   35587   if( isNT() ){
   35588     h = osLoadLibraryW((LPCWSTR)zConverted);
   35589 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   35590 ** Since the ANSI version of these Windows API do not exist for WINCE,
   35591 ** it's important to not reference them for WINCE builds.
   35592 */
   35593 #if SQLITE_OS_WINCE==0
   35594   }else{
   35595     h = osLoadLibraryA((char*)zConverted);
   35596 #endif
   35597   }
   35598   sqlite3_free(zConverted);
   35599   return (void*)h;
   35600 }
   35601 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   35602   UNUSED_PARAMETER(pVfs);
   35603   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
   35604 }
   35605 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
   35606   UNUSED_PARAMETER(pVfs);
   35607   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
   35608 }
   35609 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   35610   UNUSED_PARAMETER(pVfs);
   35611   osFreeLibrary((HANDLE)pHandle);
   35612 }
   35613 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   35614   #define winDlOpen  0
   35615   #define winDlError 0
   35616   #define winDlSym   0
   35617   #define winDlClose 0
   35618 #endif
   35619 
   35620 
   35621 /*
   35622 ** Write up to nBuf bytes of randomness into zBuf.
   35623 */
   35624 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35625   int n = 0;
   35626   UNUSED_PARAMETER(pVfs);
   35627 #if defined(SQLITE_TEST)
   35628   n = nBuf;
   35629   memset(zBuf, 0, nBuf);
   35630 #else
   35631   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   35632     SYSTEMTIME x;
   35633     osGetSystemTime(&x);
   35634     memcpy(&zBuf[n], &x, sizeof(x));
   35635     n += sizeof(x);
   35636   }
   35637   if( sizeof(DWORD)<=nBuf-n ){
   35638     DWORD pid = osGetCurrentProcessId();
   35639     memcpy(&zBuf[n], &pid, sizeof(pid));
   35640     n += sizeof(pid);
   35641   }
   35642   if( sizeof(DWORD)<=nBuf-n ){
   35643     DWORD cnt = osGetTickCount();
   35644     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   35645     n += sizeof(cnt);
   35646   }
   35647   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   35648     LARGE_INTEGER i;
   35649     osQueryPerformanceCounter(&i);
   35650     memcpy(&zBuf[n], &i, sizeof(i));
   35651     n += sizeof(i);
   35652   }
   35653 #endif
   35654   return n;
   35655 }
   35656 
   35657 
   35658 /*
   35659 ** Sleep for a little while.  Return the amount of time slept.
   35660 */
   35661 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   35662   osSleep((microsec+999)/1000);
   35663   UNUSED_PARAMETER(pVfs);
   35664   return ((microsec+999)/1000)*1000;
   35665 }
   35666 
   35667 /*
   35668 ** The following variable, if set to a non-zero value, is interpreted as
   35669 ** the number of seconds since 1970 and is used to set the result of
   35670 ** sqlite3OsCurrentTime() during testing.
   35671 */
   35672 #ifdef SQLITE_TEST
   35673 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   35674 #endif
   35675 
   35676 /*
   35677 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   35678 ** the current time and date as a Julian Day number times 86_400_000.  In
   35679 ** other words, write into *piNow the number of milliseconds since the Julian
   35680 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   35681 ** proleptic Gregorian calendar.
   35682 **
   35683 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
   35684 ** cannot be found.
   35685 */
   35686 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   35687   /* FILETIME structure is a 64-bit value representing the number of
   35688      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   35689   */
   35690   FILETIME ft;
   35691   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   35692 #ifdef SQLITE_TEST
   35693   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   35694 #endif
   35695   /* 2^32 - to avoid use of LL and warnings in gcc */
   35696   static const sqlite3_int64 max32BitValue =
   35697       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
   35698 
   35699 #if SQLITE_OS_WINCE
   35700   SYSTEMTIME time;
   35701   osGetSystemTime(&time);
   35702   /* if SystemTimeToFileTime() fails, it returns zero. */
   35703   if (!osSystemTimeToFileTime(&time,&ft)){
   35704     return SQLITE_ERROR;
   35705   }
   35706 #else
   35707   osGetSystemTimeAsFileTime( &ft );
   35708 #endif
   35709 
   35710   *piNow = winFiletimeEpoch +
   35711             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   35712                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   35713 
   35714 #ifdef SQLITE_TEST
   35715   if( sqlite3_current_time ){
   35716     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   35717   }
   35718 #endif
   35719   UNUSED_PARAMETER(pVfs);
   35720   return SQLITE_OK;
   35721 }
   35722 
   35723 /*
   35724 ** Find the current time (in Universal Coordinated Time).  Write the
   35725 ** current time and date as a Julian Day number into *prNow and
   35726 ** return 0.  Return 1 if the time and date cannot be found.
   35727 */
   35728 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   35729   int rc;
   35730   sqlite3_int64 i;
   35731   rc = winCurrentTimeInt64(pVfs, &i);
   35732   if( !rc ){
   35733     *prNow = i/86400000.0;
   35734   }
   35735   return rc;
   35736 }
   35737 
   35738 /*
   35739 ** The idea is that this function works like a combination of
   35740 ** GetLastError() and FormatMessage() on Windows (or errno and
   35741 ** strerror_r() on Unix). After an error is returned by an OS
   35742 ** function, SQLite calls this function with zBuf pointing to
   35743 ** a buffer of nBuf bytes. The OS layer should populate the
   35744 ** buffer with a nul-terminated UTF-8 encoded error message
   35745 ** describing the last IO error to have occurred within the calling
   35746 ** thread.
   35747 **
   35748 ** If the error message is too large for the supplied buffer,
   35749 ** it should be truncated. The return value of xGetLastError
   35750 ** is zero if the error message fits in the buffer, or non-zero
   35751 ** otherwise (if the message was truncated). If non-zero is returned,
   35752 ** then it is not necessary to include the nul-terminator character
   35753 ** in the output buffer.
   35754 **
   35755 ** Not supplying an error message will have no adverse effect
   35756 ** on SQLite. It is fine to have an implementation that never
   35757 ** returns an error message:
   35758 **
   35759 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35760 **     assert(zBuf[0]=='\0');
   35761 **     return 0;
   35762 **   }
   35763 **
   35764 ** However if an error message is supplied, it will be incorporated
   35765 ** by sqlite into the error message available to the user using
   35766 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   35767 */
   35768 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   35769   UNUSED_PARAMETER(pVfs);
   35770   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
   35771 }
   35772 
   35773 /*
   35774 ** Initialize and deinitialize the operating system interface.
   35775 */
   35776 SQLITE_API int sqlite3_os_init(void){
   35777   static sqlite3_vfs winVfs = {
   35778     3,                   /* iVersion */
   35779     sizeof(winFile),     /* szOsFile */
   35780     MAX_PATH,            /* mxPathname */
   35781     0,                   /* pNext */
   35782     "win32",             /* zName */
   35783     0,                   /* pAppData */
   35784     winOpen,             /* xOpen */
   35785     winDelete,           /* xDelete */
   35786     winAccess,           /* xAccess */
   35787     winFullPathname,     /* xFullPathname */
   35788     winDlOpen,           /* xDlOpen */
   35789     winDlError,          /* xDlError */
   35790     winDlSym,            /* xDlSym */
   35791     winDlClose,          /* xDlClose */
   35792     winRandomness,       /* xRandomness */
   35793     winSleep,            /* xSleep */
   35794     winCurrentTime,      /* xCurrentTime */
   35795     winGetLastError,     /* xGetLastError */
   35796     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   35797     winSetSystemCall,    /* xSetSystemCall */
   35798     winGetSystemCall,    /* xGetSystemCall */
   35799     winNextSystemCall,   /* xNextSystemCall */
   35800   };
   35801 
   35802   /* Double-check that the aSyscall[] array has been constructed
   35803   ** correctly.  See ticket [bb3a86e890c8e96ab] */
   35804   assert( ArraySize(aSyscall)==60 );
   35805 
   35806 #ifndef SQLITE_OMIT_WAL
   35807   /* get memory map allocation granularity */
   35808   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   35809   osGetSystemInfo(&winSysInfo);
   35810   assert(winSysInfo.dwAllocationGranularity > 0);
   35811 #endif
   35812 
   35813   sqlite3_vfs_register(&winVfs, 1);
   35814   return SQLITE_OK;
   35815 }
   35816 
   35817 SQLITE_API int sqlite3_os_end(void){
   35818   return SQLITE_OK;
   35819 }
   35820 
   35821 #endif /* SQLITE_OS_WIN */
   35822 
   35823 /************** End of os_win.c **********************************************/
   35824 /************** Begin file bitvec.c ******************************************/
   35825 /*
   35826 ** 2008 February 16
   35827 **
   35828 ** The author disclaims copyright to this source code.  In place of
   35829 ** a legal notice, here is a blessing:
   35830 **
   35831 **    May you do good and not evil.
   35832 **    May you find forgiveness for yourself and forgive others.
   35833 **    May you share freely, never taking more than you give.
   35834 **
   35835 *************************************************************************
   35836 ** This file implements an object that represents a fixed-length
   35837 ** bitmap.  Bits are numbered starting with 1.
   35838 **
   35839 ** A bitmap is used to record which pages of a database file have been
   35840 ** journalled during a transaction, or which pages have the "dont-write"
   35841 ** property.  Usually only a few pages are meet either condition.
   35842 ** So the bitmap is usually sparse and has low cardinality.
   35843 ** But sometimes (for example when during a DROP of a large table) most
   35844 ** or all of the pages in a database can get journalled.  In those cases,
   35845 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   35846 ** to handle both cases well.
   35847 **
   35848 ** The size of the bitmap is fixed when the object is created.
   35849 **
   35850 ** All bits are clear when the bitmap is created.  Individual bits
   35851 ** may be set or cleared one at a time.
   35852 **
   35853 ** Test operations are about 100 times more common that set operations.
   35854 ** Clear operations are exceedingly rare.  There are usually between
   35855 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   35856 ** sometimes grow into tens of thousands or larger.  The size of the
   35857 ** Bitvec object is the number of pages in the database file at the
   35858 ** start of a transaction, and is thus usually less than a few thousand,
   35859 ** but can be as large as 2 billion for a really big database.
   35860 */
   35861 
   35862 /* Size of the Bitvec structure in bytes. */
   35863 #define BITVEC_SZ        512
   35864 
   35865 /* Round the union size down to the nearest pointer boundary, since that's how
   35866 ** it will be aligned within the Bitvec struct. */
   35867 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   35868 
   35869 /* Type of the array "element" for the bitmap representation.
   35870 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   35871 ** Setting this to the "natural word" size of your CPU may improve
   35872 ** performance. */
   35873 #define BITVEC_TELEM     u8
   35874 /* Size, in bits, of the bitmap element. */
   35875 #define BITVEC_SZELEM    8
   35876 /* Number of elements in a bitmap array. */
   35877 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   35878 /* Number of bits in the bitmap array. */
   35879 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   35880 
   35881 /* Number of u32 values in hash table. */
   35882 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   35883 /* Maximum number of entries in hash table before
   35884 ** sub-dividing and re-hashing. */
   35885 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   35886 /* Hashing function for the aHash representation.
   35887 ** Empirical testing showed that the *37 multiplier
   35888 ** (an arbitrary prime)in the hash function provided
   35889 ** no fewer collisions than the no-op *1. */
   35890 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   35891 
   35892 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   35893 
   35894 
   35895 /*
   35896 ** A bitmap is an instance of the following structure.
   35897 **
   35898 ** This bitmap records the existance of zero or more bits
   35899 ** with values between 1 and iSize, inclusive.
   35900 **
   35901 ** There are three possible representations of the bitmap.
   35902 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   35903 ** bitmap.  The least significant bit is bit 1.
   35904 **
   35905 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   35906 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   35907 **
   35908 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   35909 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   35910 ** handles up to iDivisor separate values of i.  apSub[0] holds
   35911 ** values between 1 and iDivisor.  apSub[1] holds values between
   35912 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   35913 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   35914 ** to hold deal with values between 1 and iDivisor.
   35915 */
   35916 struct Bitvec {
   35917   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   35918   u32 nSet;       /* Number of bits that are set - only valid for aHash
   35919                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   35920                   ** this would be 125. */
   35921   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   35922                   /* Should >=0 for apSub element. */
   35923                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   35924                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   35925   union {
   35926     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   35927     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   35928     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   35929   } u;
   35930 };
   35931 
   35932 /*
   35933 ** Create a new bitmap object able to handle bits between 0 and iSize,
   35934 ** inclusive.  Return a pointer to the new object.  Return NULL if
   35935 ** malloc fails.
   35936 */
   35937 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   35938   Bitvec *p;
   35939   assert( sizeof(*p)==BITVEC_SZ );
   35940   p = sqlite3MallocZero( sizeof(*p) );
   35941   if( p ){
   35942     p->iSize = iSize;
   35943   }
   35944   return p;
   35945 }
   35946 
   35947 /*
   35948 ** Check to see if the i-th bit is set.  Return true or false.
   35949 ** If p is NULL (if the bitmap has not been created) or if
   35950 ** i is out of range, then return false.
   35951 */
   35952 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   35953   if( p==0 ) return 0;
   35954   if( i>p->iSize || i==0 ) return 0;
   35955   i--;
   35956   while( p->iDivisor ){
   35957     u32 bin = i/p->iDivisor;
   35958     i = i%p->iDivisor;
   35959     p = p->u.apSub[bin];
   35960     if (!p) {
   35961       return 0;
   35962     }
   35963   }
   35964   if( p->iSize<=BITVEC_NBIT ){
   35965     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   35966   } else{
   35967     u32 h = BITVEC_HASH(i++);
   35968     while( p->u.aHash[h] ){
   35969       if( p->u.aHash[h]==i ) return 1;
   35970       h = (h+1) % BITVEC_NINT;
   35971     }
   35972     return 0;
   35973   }
   35974 }
   35975 
   35976 /*
   35977 ** Set the i-th bit.  Return 0 on success and an error code if
   35978 ** anything goes wrong.
   35979 **
   35980 ** This routine might cause sub-bitmaps to be allocated.  Failing
   35981 ** to get the memory needed to hold the sub-bitmap is the only
   35982 ** that can go wrong with an insert, assuming p and i are valid.
   35983 **
   35984 ** The calling function must ensure that p is a valid Bitvec object
   35985 ** and that the value for "i" is within range of the Bitvec object.
   35986 ** Otherwise the behavior is undefined.
   35987 */
   35988 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   35989   u32 h;
   35990   if( p==0 ) return SQLITE_OK;
   35991   assert( i>0 );
   35992   assert( i<=p->iSize );
   35993   i--;
   35994   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   35995     u32 bin = i/p->iDivisor;
   35996     i = i%p->iDivisor;
   35997     if( p->u.apSub[bin]==0 ){
   35998       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   35999       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   36000     }
   36001     p = p->u.apSub[bin];
   36002   }
   36003   if( p->iSize<=BITVEC_NBIT ){
   36004     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   36005     return SQLITE_OK;
   36006   }
   36007   h = BITVEC_HASH(i++);
   36008   /* if there wasn't a hash collision, and this doesn't */
   36009   /* completely fill the hash, then just add it without */
   36010   /* worring about sub-dividing and re-hashing. */
   36011   if( !p->u.aHash[h] ){
   36012     if (p->nSet<(BITVEC_NINT-1)) {
   36013       goto bitvec_set_end;
   36014     } else {
   36015       goto bitvec_set_rehash;
   36016     }
   36017   }
   36018   /* there was a collision, check to see if it's already */
   36019   /* in hash, if not, try to find a spot for it */
   36020   do {
   36021     if( p->u.aHash[h]==i ) return SQLITE_OK;
   36022     h++;
   36023     if( h>=BITVEC_NINT ) h = 0;
   36024   } while( p->u.aHash[h] );
   36025   /* we didn't find it in the hash.  h points to the first */
   36026   /* available free spot. check to see if this is going to */
   36027   /* make our hash too "full".  */
   36028 bitvec_set_rehash:
   36029   if( p->nSet>=BITVEC_MXHASH ){
   36030     unsigned int j;
   36031     int rc;
   36032     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   36033     if( aiValues==0 ){
   36034       return SQLITE_NOMEM;
   36035     }else{
   36036       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   36037       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   36038       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   36039       rc = sqlite3BitvecSet(p, i);
   36040       for(j=0; j<BITVEC_NINT; j++){
   36041         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   36042       }
   36043       sqlite3StackFree(0, aiValues);
   36044       return rc;
   36045     }
   36046   }
   36047 bitvec_set_end:
   36048   p->nSet++;
   36049   p->u.aHash[h] = i;
   36050   return SQLITE_OK;
   36051 }
   36052 
   36053 /*
   36054 ** Clear the i-th bit.
   36055 **
   36056 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   36057 ** that BitvecClear can use to rebuilt its hash table.
   36058 */
   36059 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   36060   if( p==0 ) return;
   36061   assert( i>0 );
   36062   i--;
   36063   while( p->iDivisor ){
   36064     u32 bin = i/p->iDivisor;
   36065     i = i%p->iDivisor;
   36066     p = p->u.apSub[bin];
   36067     if (!p) {
   36068       return;
   36069     }
   36070   }
   36071   if( p->iSize<=BITVEC_NBIT ){
   36072     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   36073   }else{
   36074     unsigned int j;
   36075     u32 *aiValues = pBuf;
   36076     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   36077     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   36078     p->nSet = 0;
   36079     for(j=0; j<BITVEC_NINT; j++){
   36080       if( aiValues[j] && aiValues[j]!=(i+1) ){
   36081         u32 h = BITVEC_HASH(aiValues[j]-1);
   36082         p->nSet++;
   36083         while( p->u.aHash[h] ){
   36084           h++;
   36085           if( h>=BITVEC_NINT ) h = 0;
   36086         }
   36087         p->u.aHash[h] = aiValues[j];
   36088       }
   36089     }
   36090   }
   36091 }
   36092 
   36093 /*
   36094 ** Destroy a bitmap object.  Reclaim all memory used.
   36095 */
   36096 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   36097   if( p==0 ) return;
   36098   if( p->iDivisor ){
   36099     unsigned int i;
   36100     for(i=0; i<BITVEC_NPTR; i++){
   36101       sqlite3BitvecDestroy(p->u.apSub[i]);
   36102     }
   36103   }
   36104   sqlite3_free(p);
   36105 }
   36106 
   36107 /*
   36108 ** Return the value of the iSize parameter specified when Bitvec *p
   36109 ** was created.
   36110 */
   36111 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   36112   return p->iSize;
   36113 }
   36114 
   36115 #ifndef SQLITE_OMIT_BUILTIN_TEST
   36116 /*
   36117 ** Let V[] be an array of unsigned characters sufficient to hold
   36118 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   36119 ** Then the following macros can be used to set, clear, or test
   36120 ** individual bits within V.
   36121 */
   36122 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   36123 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   36124 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   36125 
   36126 /*
   36127 ** This routine runs an extensive test of the Bitvec code.
   36128 **
   36129 ** The input is an array of integers that acts as a program
   36130 ** to test the Bitvec.  The integers are opcodes followed
   36131 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   36132 ** opcode follows immediately after the last operand.
   36133 **
   36134 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   36135 ** "halt" opcode and causes the test to end.
   36136 **
   36137 **    0          Halt and return the number of errors
   36138 **    1 N S X    Set N bits beginning with S and incrementing by X
   36139 **    2 N S X    Clear N bits beginning with S and incrementing by X
   36140 **    3 N        Set N randomly chosen bits
   36141 **    4 N        Clear N randomly chosen bits
   36142 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   36143 **
   36144 ** The opcodes 1 through 4 perform set and clear operations are performed
   36145 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   36146 ** Opcode 5 works on the linear array only, not on the Bitvec.
   36147 ** Opcode 5 is used to deliberately induce a fault in order to
   36148 ** confirm that error detection works.
   36149 **
   36150 ** At the conclusion of the test the linear array is compared
   36151 ** against the Bitvec object.  If there are any differences,
   36152 ** an error is returned.  If they are the same, zero is returned.
   36153 **
   36154 ** If a memory allocation error occurs, return -1.
   36155 */
   36156 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   36157   Bitvec *pBitvec = 0;
   36158   unsigned char *pV = 0;
   36159   int rc = -1;
   36160   int i, nx, pc, op;
   36161   void *pTmpSpace;
   36162 
   36163   /* Allocate the Bitvec to be tested and a linear array of
   36164   ** bits to act as the reference */
   36165   pBitvec = sqlite3BitvecCreate( sz );
   36166   pV = sqlite3_malloc( (sz+7)/8 + 1 );
   36167   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   36168   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   36169   memset(pV, 0, (sz+7)/8 + 1);
   36170 
   36171   /* NULL pBitvec tests */
   36172   sqlite3BitvecSet(0, 1);
   36173   sqlite3BitvecClear(0, 1, pTmpSpace);
   36174 
   36175   /* Run the program */
   36176   pc = 0;
   36177   while( (op = aOp[pc])!=0 ){
   36178     switch( op ){
   36179       case 1:
   36180       case 2:
   36181       case 5: {
   36182         nx = 4;
   36183         i = aOp[pc+2] - 1;
   36184         aOp[pc+2] += aOp[pc+3];
   36185         break;
   36186       }
   36187       case 3:
   36188       case 4:
   36189       default: {
   36190         nx = 2;
   36191         sqlite3_randomness(sizeof(i), &i);
   36192         break;
   36193       }
   36194     }
   36195     if( (--aOp[pc+1]) > 0 ) nx = 0;
   36196     pc += nx;
   36197     i = (i & 0x7fffffff)%sz;
   36198     if( (op & 1)!=0 ){
   36199       SETBIT(pV, (i+1));
   36200       if( op!=5 ){
   36201         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   36202       }
   36203     }else{
   36204       CLEARBIT(pV, (i+1));
   36205       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   36206     }
   36207   }
   36208 
   36209   /* Test to make sure the linear array exactly matches the
   36210   ** Bitvec object.  Start with the assumption that they do
   36211   ** match (rc==0).  Change rc to non-zero if a discrepancy
   36212   ** is found.
   36213   */
   36214   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   36215           + sqlite3BitvecTest(pBitvec, 0)
   36216           + (sqlite3BitvecSize(pBitvec) - sz);
   36217   for(i=1; i<=sz; i++){
   36218     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   36219       rc = i;
   36220       break;
   36221     }
   36222   }
   36223 
   36224   /* Free allocated structure */
   36225 bitvec_end:
   36226   sqlite3_free(pTmpSpace);
   36227   sqlite3_free(pV);
   36228   sqlite3BitvecDestroy(pBitvec);
   36229   return rc;
   36230 }
   36231 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   36232 
   36233 /************** End of bitvec.c **********************************************/
   36234 /************** Begin file pcache.c ******************************************/
   36235 /*
   36236 ** 2008 August 05
   36237 **
   36238 ** The author disclaims copyright to this source code.  In place of
   36239 ** a legal notice, here is a blessing:
   36240 **
   36241 **    May you do good and not evil.
   36242 **    May you find forgiveness for yourself and forgive others.
   36243 **    May you share freely, never taking more than you give.
   36244 **
   36245 *************************************************************************
   36246 ** This file implements that page cache.
   36247 */
   36248 
   36249 /*
   36250 ** A complete page cache is an instance of this structure.
   36251 */
   36252 struct PCache {
   36253   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   36254   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   36255   int nRef;                           /* Number of referenced pages */
   36256   int szCache;                        /* Configured cache size */
   36257   int szPage;                         /* Size of every page in this cache */
   36258   int szExtra;                        /* Size of extra space for each page */
   36259   int bPurgeable;                     /* True if pages are on backing store */
   36260   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   36261   void *pStress;                      /* Argument to xStress */
   36262   sqlite3_pcache *pCache;             /* Pluggable cache module */
   36263   PgHdr *pPage1;                      /* Reference to page 1 */
   36264 };
   36265 
   36266 /*
   36267 ** Some of the assert() macros in this code are too expensive to run
   36268 ** even during normal debugging.  Use them only rarely on long-running
   36269 ** tests.  Enable the expensive asserts using the
   36270 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   36271 */
   36272 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   36273 # define expensive_assert(X)  assert(X)
   36274 #else
   36275 # define expensive_assert(X)
   36276 #endif
   36277 
   36278 /********************************** Linked List Management ********************/
   36279 
   36280 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   36281 /*
   36282 ** Check that the pCache->pSynced variable is set correctly. If it
   36283 ** is not, either fail an assert or return zero. Otherwise, return
   36284 ** non-zero. This is only used in debugging builds, as follows:
   36285 **
   36286 **   expensive_assert( pcacheCheckSynced(pCache) );
   36287 */
   36288 static int pcacheCheckSynced(PCache *pCache){
   36289   PgHdr *p;
   36290   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   36291     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   36292   }
   36293   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   36294 }
   36295 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   36296 
   36297 /*
   36298 ** Remove page pPage from the list of dirty pages.
   36299 */
   36300 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   36301   PCache *p = pPage->pCache;
   36302 
   36303   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   36304   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   36305 
   36306   /* Update the PCache1.pSynced variable if necessary. */
   36307   if( p->pSynced==pPage ){
   36308     PgHdr *pSynced = pPage->pDirtyPrev;
   36309     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   36310       pSynced = pSynced->pDirtyPrev;
   36311     }
   36312     p->pSynced = pSynced;
   36313   }
   36314 
   36315   if( pPage->pDirtyNext ){
   36316     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   36317   }else{
   36318     assert( pPage==p->pDirtyTail );
   36319     p->pDirtyTail = pPage->pDirtyPrev;
   36320   }
   36321   if( pPage->pDirtyPrev ){
   36322     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   36323   }else{
   36324     assert( pPage==p->pDirty );
   36325     p->pDirty = pPage->pDirtyNext;
   36326   }
   36327   pPage->pDirtyNext = 0;
   36328   pPage->pDirtyPrev = 0;
   36329 
   36330   expensive_assert( pcacheCheckSynced(p) );
   36331 }
   36332 
   36333 /*
   36334 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   36335 ** pPage).
   36336 */
   36337 static void pcacheAddToDirtyList(PgHdr *pPage){
   36338   PCache *p = pPage->pCache;
   36339 
   36340   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   36341 
   36342   pPage->pDirtyNext = p->pDirty;
   36343   if( pPage->pDirtyNext ){
   36344     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   36345     pPage->pDirtyNext->pDirtyPrev = pPage;
   36346   }
   36347   p->pDirty = pPage;
   36348   if( !p->pDirtyTail ){
   36349     p->pDirtyTail = pPage;
   36350   }
   36351   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   36352     p->pSynced = pPage;
   36353   }
   36354   expensive_assert( pcacheCheckSynced(p) );
   36355 }
   36356 
   36357 /*
   36358 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   36359 ** being used for an in-memory database, this function is a no-op.
   36360 */
   36361 static void pcacheUnpin(PgHdr *p){
   36362   PCache *pCache = p->pCache;
   36363   if( pCache->bPurgeable ){
   36364     if( p->pgno==1 ){
   36365       pCache->pPage1 = 0;
   36366     }
   36367     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
   36368   }
   36369 }
   36370 
   36371 /*************************************************** General Interfaces ******
   36372 **
   36373 ** Initialize and shutdown the page cache subsystem. Neither of these
   36374 ** functions are threadsafe.
   36375 */
   36376 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   36377   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   36378     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   36379     ** built-in default page cache is used instead of the application defined
   36380     ** page cache. */
   36381     sqlite3PCacheSetDefault();
   36382   }
   36383   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   36384 }
   36385 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   36386   if( sqlite3GlobalConfig.pcache2.xShutdown ){
   36387     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   36388     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   36389   }
   36390 }
   36391 
   36392 /*
   36393 ** Return the size in bytes of a PCache object.
   36394 */
   36395 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   36396 
   36397 /*
   36398 ** Create a new PCache object. Storage space to hold the object
   36399 ** has already been allocated and is passed in as the p pointer.
   36400 ** The caller discovers how much space needs to be allocated by
   36401 ** calling sqlite3PcacheSize().
   36402 */
   36403 SQLITE_PRIVATE void sqlite3PcacheOpen(
   36404   int szPage,                  /* Size of every page */
   36405   int szExtra,                 /* Extra space associated with each page */
   36406   int bPurgeable,              /* True if pages are on backing store */
   36407   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   36408   void *pStress,               /* Argument to xStress */
   36409   PCache *p                    /* Preallocated space for the PCache */
   36410 ){
   36411   memset(p, 0, sizeof(PCache));
   36412   p->szPage = szPage;
   36413   p->szExtra = szExtra;
   36414   p->bPurgeable = bPurgeable;
   36415   p->xStress = xStress;
   36416   p->pStress = pStress;
   36417   p->szCache = 100;
   36418 }
   36419 
   36420 /*
   36421 ** Change the page size for PCache object. The caller must ensure that there
   36422 ** are no outstanding page references when this function is called.
   36423 */
   36424 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   36425   assert( pCache->nRef==0 && pCache->pDirty==0 );
   36426   if( pCache->pCache ){
   36427     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   36428     pCache->pCache = 0;
   36429     pCache->pPage1 = 0;
   36430   }
   36431   pCache->szPage = szPage;
   36432 }
   36433 
   36434 /*
   36435 ** Compute the number of pages of cache requested.
   36436 */
   36437 static int numberOfCachePages(PCache *p){
   36438   if( p->szCache>=0 ){
   36439     return p->szCache;
   36440   }else{
   36441     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
   36442   }
   36443 }
   36444 
   36445 /*
   36446 ** Try to obtain a page from the cache.
   36447 */
   36448 SQLITE_PRIVATE int sqlite3PcacheFetch(
   36449   PCache *pCache,       /* Obtain the page from this cache */
   36450   Pgno pgno,            /* Page number to obtain */
   36451   int createFlag,       /* If true, create page if it does not exist already */
   36452   PgHdr **ppPage        /* Write the page here */
   36453 ){
   36454   sqlite3_pcache_page *pPage = 0;
   36455   PgHdr *pPgHdr = 0;
   36456   int eCreate;
   36457 
   36458   assert( pCache!=0 );
   36459   assert( createFlag==1 || createFlag==0 );
   36460   assert( pgno>0 );
   36461 
   36462   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   36463   ** allocate it now.
   36464   */
   36465   if( !pCache->pCache && createFlag ){
   36466     sqlite3_pcache *p;
   36467     p = sqlite3GlobalConfig.pcache2.xCreate(
   36468         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
   36469     );
   36470     if( !p ){
   36471       return SQLITE_NOMEM;
   36472     }
   36473     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
   36474     pCache->pCache = p;
   36475   }
   36476 
   36477   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
   36478   if( pCache->pCache ){
   36479     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   36480   }
   36481 
   36482   if( !pPage && eCreate==1 ){
   36483     PgHdr *pPg;
   36484 
   36485     /* Find a dirty page to write-out and recycle. First try to find a
   36486     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   36487     ** cleared), but if that is not possible settle for any other
   36488     ** unreferenced dirty page.
   36489     */
   36490     expensive_assert( pcacheCheckSynced(pCache) );
   36491     for(pPg=pCache->pSynced;
   36492         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   36493         pPg=pPg->pDirtyPrev
   36494     );
   36495     pCache->pSynced = pPg;
   36496     if( !pPg ){
   36497       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   36498     }
   36499     if( pPg ){
   36500       int rc;
   36501 #ifdef SQLITE_LOG_CACHE_SPILL
   36502       sqlite3_log(SQLITE_FULL,
   36503                   "spill page %d making room for %d - cache used: %d/%d",
   36504                   pPg->pgno, pgno,
   36505                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   36506                   numberOfCachePages(pCache));
   36507 #endif
   36508       rc = pCache->xStress(pCache->pStress, pPg);
   36509       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   36510         return rc;
   36511       }
   36512     }
   36513 
   36514     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   36515   }
   36516 
   36517   if( pPage ){
   36518     pPgHdr = (PgHdr *)pPage->pExtra;
   36519 
   36520     if( !pPgHdr->pPage ){
   36521       memset(pPgHdr, 0, sizeof(PgHdr));
   36522       pPgHdr->pPage = pPage;
   36523       pPgHdr->pData = pPage->pBuf;
   36524       pPgHdr->pExtra = (void *)&pPgHdr[1];
   36525       memset(pPgHdr->pExtra, 0, pCache->szExtra);
   36526       pPgHdr->pCache = pCache;
   36527       pPgHdr->pgno = pgno;
   36528     }
   36529     assert( pPgHdr->pCache==pCache );
   36530     assert( pPgHdr->pgno==pgno );
   36531     assert( pPgHdr->pData==pPage->pBuf );
   36532     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
   36533 
   36534     if( 0==pPgHdr->nRef ){
   36535       pCache->nRef++;
   36536     }
   36537     pPgHdr->nRef++;
   36538     if( pgno==1 ){
   36539       pCache->pPage1 = pPgHdr;
   36540     }
   36541   }
   36542   *ppPage = pPgHdr;
   36543   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   36544 }
   36545 
   36546 /*
   36547 ** Decrement the reference count on a page. If the page is clean and the
   36548 ** reference count drops to 0, then it is made elible for recycling.
   36549 */
   36550 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   36551   assert( p->nRef>0 );
   36552   p->nRef--;
   36553   if( p->nRef==0 ){
   36554     PCache *pCache = p->pCache;
   36555     pCache->nRef--;
   36556     if( (p->flags&PGHDR_DIRTY)==0 ){
   36557       pcacheUnpin(p);
   36558     }else{
   36559       /* Move the page to the head of the dirty list. */
   36560       pcacheRemoveFromDirtyList(p);
   36561       pcacheAddToDirtyList(p);
   36562     }
   36563   }
   36564 }
   36565 
   36566 /*
   36567 ** Increase the reference count of a supplied page by 1.
   36568 */
   36569 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   36570   assert(p->nRef>0);
   36571   p->nRef++;
   36572 }
   36573 
   36574 /*
   36575 ** Drop a page from the cache. There must be exactly one reference to the
   36576 ** page. This function deletes that reference, so after it returns the
   36577 ** page pointed to by p is invalid.
   36578 */
   36579 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   36580   PCache *pCache;
   36581   assert( p->nRef==1 );
   36582   if( p->flags&PGHDR_DIRTY ){
   36583     pcacheRemoveFromDirtyList(p);
   36584   }
   36585   pCache = p->pCache;
   36586   pCache->nRef--;
   36587   if( p->pgno==1 ){
   36588     pCache->pPage1 = 0;
   36589   }
   36590   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
   36591 }
   36592 
   36593 /*
   36594 ** Make sure the page is marked as dirty. If it isn't dirty already,
   36595 ** make it so.
   36596 */
   36597 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   36598   p->flags &= ~PGHDR_DONT_WRITE;
   36599   assert( p->nRef>0 );
   36600   if( 0==(p->flags & PGHDR_DIRTY) ){
   36601     p->flags |= PGHDR_DIRTY;
   36602     pcacheAddToDirtyList( p);
   36603   }
   36604 }
   36605 
   36606 /*
   36607 ** Make sure the page is marked as clean. If it isn't clean already,
   36608 ** make it so.
   36609 */
   36610 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   36611   if( (p->flags & PGHDR_DIRTY) ){
   36612     pcacheRemoveFromDirtyList(p);
   36613     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   36614     if( p->nRef==0 ){
   36615       pcacheUnpin(p);
   36616     }
   36617   }
   36618 }
   36619 
   36620 /*
   36621 ** Make every page in the cache clean.
   36622 */
   36623 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   36624   PgHdr *p;
   36625   while( (p = pCache->pDirty)!=0 ){
   36626     sqlite3PcacheMakeClean(p);
   36627   }
   36628 }
   36629 
   36630 /*
   36631 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   36632 */
   36633 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   36634   PgHdr *p;
   36635   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   36636     p->flags &= ~PGHDR_NEED_SYNC;
   36637   }
   36638   pCache->pSynced = pCache->pDirtyTail;
   36639 }
   36640 
   36641 /*
   36642 ** Change the page number of page p to newPgno.
   36643 */
   36644 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   36645   PCache *pCache = p->pCache;
   36646   assert( p->nRef>0 );
   36647   assert( newPgno>0 );
   36648   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   36649   p->pgno = newPgno;
   36650   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   36651     pcacheRemoveFromDirtyList(p);
   36652     pcacheAddToDirtyList(p);
   36653   }
   36654 }
   36655 
   36656 /*
   36657 ** Drop every cache entry whose page number is greater than "pgno". The
   36658 ** caller must ensure that there are no outstanding references to any pages
   36659 ** other than page 1 with a page number greater than pgno.
   36660 **
   36661 ** If there is a reference to page 1 and the pgno parameter passed to this
   36662 ** function is 0, then the data area associated with page 1 is zeroed, but
   36663 ** the page object is not dropped.
   36664 */
   36665 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   36666   if( pCache->pCache ){
   36667     PgHdr *p;
   36668     PgHdr *pNext;
   36669     for(p=pCache->pDirty; p; p=pNext){
   36670       pNext = p->pDirtyNext;
   36671       /* This routine never gets call with a positive pgno except right
   36672       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   36673       ** it must be that pgno==0.
   36674       */
   36675       assert( p->pgno>0 );
   36676       if( ALWAYS(p->pgno>pgno) ){
   36677         assert( p->flags&PGHDR_DIRTY );
   36678         sqlite3PcacheMakeClean(p);
   36679       }
   36680     }
   36681     if( pgno==0 && pCache->pPage1 ){
   36682       memset(pCache->pPage1->pData, 0, pCache->szPage);
   36683       pgno = 1;
   36684     }
   36685     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   36686   }
   36687 }
   36688 
   36689 /*
   36690 ** Close a cache.
   36691 */
   36692 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   36693   if( pCache->pCache ){
   36694     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   36695   }
   36696 }
   36697 
   36698 /*
   36699 ** Discard the contents of the cache.
   36700 */
   36701 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   36702   sqlite3PcacheTruncate(pCache, 0);
   36703 }
   36704 
   36705 /*
   36706 ** Merge two lists of pages connected by pDirty and in pgno order.
   36707 ** Do not both fixing the pDirtyPrev pointers.
   36708 */
   36709 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   36710   PgHdr result, *pTail;
   36711   pTail = &result;
   36712   while( pA && pB ){
   36713     if( pA->pgno<pB->pgno ){
   36714       pTail->pDirty = pA;
   36715       pTail = pA;
   36716       pA = pA->pDirty;
   36717     }else{
   36718       pTail->pDirty = pB;
   36719       pTail = pB;
   36720       pB = pB->pDirty;
   36721     }
   36722   }
   36723   if( pA ){
   36724     pTail->pDirty = pA;
   36725   }else if( pB ){
   36726     pTail->pDirty = pB;
   36727   }else{
   36728     pTail->pDirty = 0;
   36729   }
   36730   return result.pDirty;
   36731 }
   36732 
   36733 /*
   36734 ** Sort the list of pages in accending order by pgno.  Pages are
   36735 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   36736 ** corrupted by this sort.
   36737 **
   36738 ** Since there cannot be more than 2^31 distinct pages in a database,
   36739 ** there cannot be more than 31 buckets required by the merge sorter.
   36740 ** One extra bucket is added to catch overflow in case something
   36741 ** ever changes to make the previous sentence incorrect.
   36742 */
   36743 #define N_SORT_BUCKET  32
   36744 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   36745   PgHdr *a[N_SORT_BUCKET], *p;
   36746   int i;
   36747   memset(a, 0, sizeof(a));
   36748   while( pIn ){
   36749     p = pIn;
   36750     pIn = p->pDirty;
   36751     p->pDirty = 0;
   36752     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   36753       if( a[i]==0 ){
   36754         a[i] = p;
   36755         break;
   36756       }else{
   36757         p = pcacheMergeDirtyList(a[i], p);
   36758         a[i] = 0;
   36759       }
   36760     }
   36761     if( NEVER(i==N_SORT_BUCKET-1) ){
   36762       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   36763       ** the input list.  But that is impossible.
   36764       */
   36765       a[i] = pcacheMergeDirtyList(a[i], p);
   36766     }
   36767   }
   36768   p = a[0];
   36769   for(i=1; i<N_SORT_BUCKET; i++){
   36770     p = pcacheMergeDirtyList(p, a[i]);
   36771   }
   36772   return p;
   36773 }
   36774 
   36775 /*
   36776 ** Return a list of all dirty pages in the cache, sorted by page number.
   36777 */
   36778 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   36779   PgHdr *p;
   36780   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   36781     p->pDirty = p->pDirtyNext;
   36782   }
   36783   return pcacheSortDirtyList(pCache->pDirty);
   36784 }
   36785 
   36786 /*
   36787 ** Return the total number of referenced pages held by the cache.
   36788 */
   36789 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   36790   return pCache->nRef;
   36791 }
   36792 
   36793 /*
   36794 ** Return the number of references to the page supplied as an argument.
   36795 */
   36796 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   36797   return p->nRef;
   36798 }
   36799 
   36800 /*
   36801 ** Return the total number of pages in the cache.
   36802 */
   36803 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   36804   int nPage = 0;
   36805   if( pCache->pCache ){
   36806     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   36807   }
   36808   return nPage;
   36809 }
   36810 
   36811 #ifdef SQLITE_TEST
   36812 /*
   36813 ** Get the suggested cache-size value.
   36814 */
   36815 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   36816   return numberOfCachePages(pCache);
   36817 }
   36818 #endif
   36819 
   36820 /*
   36821 ** Set the suggested cache-size value.
   36822 */
   36823 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   36824   pCache->szCache = mxPage;
   36825   if( pCache->pCache ){
   36826     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
   36827                                            numberOfCachePages(pCache));
   36828   }
   36829 }
   36830 
   36831 /*
   36832 ** Free up as much memory as possible from the page cache.
   36833 */
   36834 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
   36835   if( pCache->pCache ){
   36836     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   36837   }
   36838 }
   36839 
   36840 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   36841 /*
   36842 ** For all dirty pages currently in the cache, invoke the specified
   36843 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   36844 ** defined.
   36845 */
   36846 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   36847   PgHdr *pDirty;
   36848   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   36849     xIter(pDirty);
   36850   }
   36851 }
   36852 #endif
   36853 
   36854 /************** End of pcache.c **********************************************/
   36855 /************** Begin file pcache1.c *****************************************/
   36856 /*
   36857 ** 2008 November 05
   36858 **
   36859 ** The author disclaims copyright to this source code.  In place of
   36860 ** a legal notice, here is a blessing:
   36861 **
   36862 **    May you do good and not evil.
   36863 **    May you find forgiveness for yourself and forgive others.
   36864 **    May you share freely, never taking more than you give.
   36865 **
   36866 *************************************************************************
   36867 **
   36868 ** This file implements the default page cache implementation (the
   36869 ** sqlite3_pcache interface). It also contains part of the implementation
   36870 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   36871 ** If the default page cache implementation is overriden, then neither of
   36872 ** these two features are available.
   36873 */
   36874 
   36875 
   36876 typedef struct PCache1 PCache1;
   36877 typedef struct PgHdr1 PgHdr1;
   36878 typedef struct PgFreeslot PgFreeslot;
   36879 typedef struct PGroup PGroup;
   36880 
   36881 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
   36882 ** of one or more PCaches that are able to recycle each others unpinned
   36883 ** pages when they are under memory pressure.  A PGroup is an instance of
   36884 ** the following object.
   36885 **
   36886 ** This page cache implementation works in one of two modes:
   36887 **
   36888 **   (1)  Every PCache is the sole member of its own PGroup.  There is
   36889 **        one PGroup per PCache.
   36890 **
   36891 **   (2)  There is a single global PGroup that all PCaches are a member
   36892 **        of.
   36893 **
   36894 ** Mode 1 uses more memory (since PCache instances are not able to rob
   36895 ** unused pages from other PCaches) but it also operates without a mutex,
   36896 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
   36897 ** threadsafe, but recycles pages more efficiently.
   36898 **
   36899 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
   36900 ** PGroup which is the pcache1.grp global variable and its mutex is
   36901 ** SQLITE_MUTEX_STATIC_LRU.
   36902 */
   36903 struct PGroup {
   36904   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
   36905   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
   36906   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
   36907   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
   36908   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
   36909   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
   36910 };
   36911 
   36912 /* Each page cache is an instance of the following object.  Every
   36913 ** open database file (including each in-memory database and each
   36914 ** temporary or transient database) has a single page cache which
   36915 ** is an instance of this object.
   36916 **
   36917 ** Pointers to structures of this type are cast and returned as
   36918 ** opaque sqlite3_pcache* handles.
   36919 */
   36920 struct PCache1 {
   36921   /* Cache configuration parameters. Page size (szPage) and the purgeable
   36922   ** flag (bPurgeable) are set when the cache is created. nMax may be
   36923   ** modified at any time by a call to the pcache1Cachesize() method.
   36924   ** The PGroup mutex must be held when accessing nMax.
   36925   */
   36926   PGroup *pGroup;                     /* PGroup this cache belongs to */
   36927   int szPage;                         /* Size of allocated pages in bytes */
   36928   int szExtra;                        /* Size of extra space in bytes */
   36929   int bPurgeable;                     /* True if cache is purgeable */
   36930   unsigned int nMin;                  /* Minimum number of pages reserved */
   36931   unsigned int nMax;                  /* Configured "cache_size" value */
   36932   unsigned int n90pct;                /* nMax*9/10 */
   36933   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   36934 
   36935   /* Hash table of all pages. The following variables may only be accessed
   36936   ** when the accessor is holding the PGroup mutex.
   36937   */
   36938   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   36939   unsigned int nPage;                 /* Total number of pages in apHash */
   36940   unsigned int nHash;                 /* Number of slots in apHash[] */
   36941   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   36942 };
   36943 
   36944 /*
   36945 ** Each cache entry is represented by an instance of the following
   36946 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
   36947 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
   36948 ** in memory.
   36949 */
   36950 struct PgHdr1 {
   36951   sqlite3_pcache_page page;
   36952   unsigned int iKey;             /* Key value (page number) */
   36953   PgHdr1 *pNext;                 /* Next in hash table chain */
   36954   PCache1 *pCache;               /* Cache that currently owns this page */
   36955   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   36956   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   36957 };
   36958 
   36959 /*
   36960 ** Free slots in the allocator used to divide up the buffer provided using
   36961 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   36962 */
   36963 struct PgFreeslot {
   36964   PgFreeslot *pNext;  /* Next free slot */
   36965 };
   36966 
   36967 /*
   36968 ** Global data used by this cache.
   36969 */
   36970 static SQLITE_WSD struct PCacheGlobal {
   36971   PGroup grp;                    /* The global PGroup for mode (2) */
   36972 
   36973   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
   36974   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
   36975   ** fixed at sqlite3_initialize() time and do not require mutex protection.
   36976   ** The nFreeSlot and pFree values do require mutex protection.
   36977   */
   36978   int isInit;                    /* True if initialized */
   36979   int szSlot;                    /* Size of each free slot */
   36980   int nSlot;                     /* The number of pcache slots */
   36981   int nReserve;                  /* Try to keep nFreeSlot above this */
   36982   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
   36983   /* Above requires no mutex.  Use mutex below for variable that follow. */
   36984   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
   36985   PgFreeslot *pFree;             /* Free page blocks */
   36986   int nFreeSlot;                 /* Number of unused pcache slots */
   36987   /* The following value requires a mutex to change.  We skip the mutex on
   36988   ** reading because (1) most platforms read a 32-bit integer atomically and
   36989   ** (2) even if an incorrect value is read, no great harm is done since this
   36990   ** is really just an optimization. */
   36991   int bUnderPressure;            /* True if low on PAGECACHE memory */
   36992 } pcache1_g;
   36993 
   36994 /*
   36995 ** All code in this file should access the global structure above via the
   36996 ** alias "pcache1". This ensures that the WSD emulation is used when
   36997 ** compiling for systems that do not support real WSD.
   36998 */
   36999 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   37000 
   37001 /*
   37002 ** Macros to enter and leave the PCache LRU mutex.
   37003 */
   37004 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   37005 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   37006 
   37007 /******************************************************************************/
   37008 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   37009 
   37010 /*
   37011 ** This function is called during initialization if a static buffer is
   37012 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   37013 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   37014 ** enough to contain 'n' buffers of 'sz' bytes each.
   37015 **
   37016 ** This routine is called from sqlite3_initialize() and so it is guaranteed
   37017 ** to be serialized already.  There is no need for further mutexing.
   37018 */
   37019 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   37020   if( pcache1.isInit ){
   37021     PgFreeslot *p;
   37022     sz = ROUNDDOWN8(sz);
   37023     pcache1.szSlot = sz;
   37024     pcache1.nSlot = pcache1.nFreeSlot = n;
   37025     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   37026     pcache1.pStart = pBuf;
   37027     pcache1.pFree = 0;
   37028     pcache1.bUnderPressure = 0;
   37029     while( n-- ){
   37030       p = (PgFreeslot*)pBuf;
   37031       p->pNext = pcache1.pFree;
   37032       pcache1.pFree = p;
   37033       pBuf = (void*)&((char*)pBuf)[sz];
   37034     }
   37035     pcache1.pEnd = pBuf;
   37036   }
   37037 }
   37038 
   37039 /*
   37040 ** Malloc function used within this file to allocate space from the buffer
   37041 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   37042 ** such buffer exists or there is no space left in it, this function falls
   37043 ** back to sqlite3Malloc().
   37044 **
   37045 ** Multiple threads can run this routine at the same time.  Global variables
   37046 ** in pcache1 need to be protected via mutex.
   37047 */
   37048 static void *pcache1Alloc(int nByte){
   37049   void *p = 0;
   37050   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   37051   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   37052   if( nByte<=pcache1.szSlot ){
   37053     sqlite3_mutex_enter(pcache1.mutex);
   37054     p = (PgHdr1 *)pcache1.pFree;
   37055     if( p ){
   37056       pcache1.pFree = pcache1.pFree->pNext;
   37057       pcache1.nFreeSlot--;
   37058       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   37059       assert( pcache1.nFreeSlot>=0 );
   37060       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   37061     }
   37062     sqlite3_mutex_leave(pcache1.mutex);
   37063   }
   37064   if( p==0 ){
   37065     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
   37066     ** it from sqlite3Malloc instead.
   37067     */
   37068     p = sqlite3Malloc(nByte);
   37069     if( p ){
   37070       int sz = sqlite3MallocSize(p);
   37071       sqlite3_mutex_enter(pcache1.mutex);
   37072       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   37073       sqlite3_mutex_leave(pcache1.mutex);
   37074     }
   37075     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   37076   }
   37077   return p;
   37078 }
   37079 
   37080 /*
   37081 ** Free an allocated buffer obtained from pcache1Alloc().
   37082 */
   37083 static int pcache1Free(void *p){
   37084   int nFreed = 0;
   37085   if( p==0 ) return 0;
   37086   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   37087     PgFreeslot *pSlot;
   37088     sqlite3_mutex_enter(pcache1.mutex);
   37089     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   37090     pSlot = (PgFreeslot*)p;
   37091     pSlot->pNext = pcache1.pFree;
   37092     pcache1.pFree = pSlot;
   37093     pcache1.nFreeSlot++;
   37094     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   37095     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   37096     sqlite3_mutex_leave(pcache1.mutex);
   37097   }else{
   37098     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   37099     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   37100     nFreed = sqlite3MallocSize(p);
   37101     sqlite3_mutex_enter(pcache1.mutex);
   37102     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
   37103     sqlite3_mutex_leave(pcache1.mutex);
   37104     sqlite3_free(p);
   37105   }
   37106   return nFreed;
   37107 }
   37108 
   37109 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   37110 /*
   37111 ** Return the size of a pcache allocation
   37112 */
   37113 static int pcache1MemSize(void *p){
   37114   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   37115     return pcache1.szSlot;
   37116   }else{
   37117     int iSize;
   37118     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   37119     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   37120     iSize = sqlite3MallocSize(p);
   37121     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   37122     return iSize;
   37123   }
   37124 }
   37125 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   37126 
   37127 /*
   37128 ** Allocate a new page object initially associated with cache pCache.
   37129 */
   37130 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   37131   PgHdr1 *p = 0;
   37132   void *pPg;
   37133 
   37134   /* The group mutex must be released before pcache1Alloc() is called. This
   37135   ** is because it may call sqlite3_release_memory(), which assumes that
   37136   ** this mutex is not held. */
   37137   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37138   pcache1LeaveMutex(pCache->pGroup);
   37139 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37140   pPg = pcache1Alloc(pCache->szPage);
   37141   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
   37142   if( !pPg || !p ){
   37143     pcache1Free(pPg);
   37144     sqlite3_free(p);
   37145     pPg = 0;
   37146   }
   37147 #else
   37148   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
   37149   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
   37150 #endif
   37151   pcache1EnterMutex(pCache->pGroup);
   37152 
   37153   if( pPg ){
   37154     p->page.pBuf = pPg;
   37155     p->page.pExtra = &p[1];
   37156     if( pCache->bPurgeable ){
   37157       pCache->pGroup->nCurrentPage++;
   37158     }
   37159     return p;
   37160   }
   37161   return 0;
   37162 }
   37163 
   37164 /*
   37165 ** Free a page object allocated by pcache1AllocPage().
   37166 **
   37167 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   37168 ** that the current implementation happens to never call this routine
   37169 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   37170 */
   37171 static void pcache1FreePage(PgHdr1 *p){
   37172   if( ALWAYS(p) ){
   37173     PCache1 *pCache = p->pCache;
   37174     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   37175     pcache1Free(p->page.pBuf);
   37176 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37177     sqlite3_free(p);
   37178 #endif
   37179     if( pCache->bPurgeable ){
   37180       pCache->pGroup->nCurrentPage--;
   37181     }
   37182   }
   37183 }
   37184 
   37185 /*
   37186 ** Malloc function used by SQLite to obtain space from the buffer configured
   37187 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   37188 ** exists, this function falls back to sqlite3Malloc().
   37189 */
   37190 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   37191   return pcache1Alloc(sz);
   37192 }
   37193 
   37194 /*
   37195 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   37196 */
   37197 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   37198   pcache1Free(p);
   37199 }
   37200 
   37201 
   37202 /*
   37203 ** Return true if it desirable to avoid allocating a new page cache
   37204 ** entry.
   37205 **
   37206 ** If memory was allocated specifically to the page cache using
   37207 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   37208 ** it is desirable to avoid allocating a new page cache entry because
   37209 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   37210 ** for all page cache needs and we should not need to spill the
   37211 ** allocation onto the heap.
   37212 **
   37213 ** Or, the heap is used for all page cache memory but the heap is
   37214 ** under memory pressure, then again it is desirable to avoid
   37215 ** allocating a new page cache entry in order to avoid stressing
   37216 ** the heap even further.
   37217 */
   37218 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   37219   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   37220     return pcache1.bUnderPressure;
   37221   }else{
   37222     return sqlite3HeapNearlyFull();
   37223   }
   37224 }
   37225 
   37226 /******************************************************************************/
   37227 /******** General Implementation Functions ************************************/
   37228 
   37229 /*
   37230 ** This function is used to resize the hash table used by the cache passed
   37231 ** as the first argument.
   37232 **
   37233 ** The PCache mutex must be held when this function is called.
   37234 */
   37235 static int pcache1ResizeHash(PCache1 *p){
   37236   PgHdr1 **apNew;
   37237   unsigned int nNew;
   37238   unsigned int i;
   37239 
   37240   assert( sqlite3_mutex_held(p->pGroup->mutex) );
   37241 
   37242   nNew = p->nHash*2;
   37243   if( nNew<256 ){
   37244     nNew = 256;
   37245   }
   37246 
   37247   pcache1LeaveMutex(p->pGroup);
   37248   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   37249   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
   37250   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   37251   pcache1EnterMutex(p->pGroup);
   37252   if( apNew ){
   37253     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
   37254     for(i=0; i<p->nHash; i++){
   37255       PgHdr1 *pPage;
   37256       PgHdr1 *pNext = p->apHash[i];
   37257       while( (pPage = pNext)!=0 ){
   37258         unsigned int h = pPage->iKey % nNew;
   37259         pNext = pPage->pNext;
   37260         pPage->pNext = apNew[h];
   37261         apNew[h] = pPage;
   37262       }
   37263     }
   37264     sqlite3_free(p->apHash);
   37265     p->apHash = apNew;
   37266     p->nHash = nNew;
   37267   }
   37268 
   37269   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   37270 }
   37271 
   37272 /*
   37273 ** This function is used internally to remove the page pPage from the
   37274 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
   37275 ** LRU list, then this function is a no-op.
   37276 **
   37277 ** The PGroup mutex must be held when this function is called.
   37278 **
   37279 ** If pPage is NULL then this routine is a no-op.
   37280 */
   37281 static void pcache1PinPage(PgHdr1 *pPage){
   37282   PCache1 *pCache;
   37283   PGroup *pGroup;
   37284 
   37285   if( pPage==0 ) return;
   37286   pCache = pPage->pCache;
   37287   pGroup = pCache->pGroup;
   37288   assert( sqlite3_mutex_held(pGroup->mutex) );
   37289   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
   37290     if( pPage->pLruPrev ){
   37291       pPage->pLruPrev->pLruNext = pPage->pLruNext;
   37292     }
   37293     if( pPage->pLruNext ){
   37294       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   37295     }
   37296     if( pGroup->pLruHead==pPage ){
   37297       pGroup->pLruHead = pPage->pLruNext;
   37298     }
   37299     if( pGroup->pLruTail==pPage ){
   37300       pGroup->pLruTail = pPage->pLruPrev;
   37301     }
   37302     pPage->pLruNext = 0;
   37303     pPage->pLruPrev = 0;
   37304     pPage->pCache->nRecyclable--;
   37305   }
   37306 }
   37307 
   37308 
   37309 /*
   37310 ** Remove the page supplied as an argument from the hash table
   37311 ** (PCache1.apHash structure) that it is currently stored in.
   37312 **
   37313 ** The PGroup mutex must be held when this function is called.
   37314 */
   37315 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   37316   unsigned int h;
   37317   PCache1 *pCache = pPage->pCache;
   37318   PgHdr1 **pp;
   37319 
   37320   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37321   h = pPage->iKey % pCache->nHash;
   37322   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   37323   *pp = (*pp)->pNext;
   37324 
   37325   pCache->nPage--;
   37326 }
   37327 
   37328 /*
   37329 ** If there are currently more than nMaxPage pages allocated, try
   37330 ** to recycle pages to reduce the number allocated to nMaxPage.
   37331 */
   37332 static void pcache1EnforceMaxPage(PGroup *pGroup){
   37333   assert( sqlite3_mutex_held(pGroup->mutex) );
   37334   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
   37335     PgHdr1 *p = pGroup->pLruTail;
   37336     assert( p->pCache->pGroup==pGroup );
   37337     pcache1PinPage(p);
   37338     pcache1RemoveFromHash(p);
   37339     pcache1FreePage(p);
   37340   }
   37341 }
   37342 
   37343 /*
   37344 ** Discard all pages from cache pCache with a page number (key value)
   37345 ** greater than or equal to iLimit. Any pinned pages that meet this
   37346 ** criteria are unpinned before they are discarded.
   37347 **
   37348 ** The PCache mutex must be held when this function is called.
   37349 */
   37350 static void pcache1TruncateUnsafe(
   37351   PCache1 *pCache,             /* The cache to truncate */
   37352   unsigned int iLimit          /* Drop pages with this pgno or larger */
   37353 ){
   37354   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
   37355   unsigned int h;
   37356   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   37357   for(h=0; h<pCache->nHash; h++){
   37358     PgHdr1 **pp = &pCache->apHash[h];
   37359     PgHdr1 *pPage;
   37360     while( (pPage = *pp)!=0 ){
   37361       if( pPage->iKey>=iLimit ){
   37362         pCache->nPage--;
   37363         *pp = pPage->pNext;
   37364         pcache1PinPage(pPage);
   37365         pcache1FreePage(pPage);
   37366       }else{
   37367         pp = &pPage->pNext;
   37368         TESTONLY( nPage++; )
   37369       }
   37370     }
   37371   }
   37372   assert( pCache->nPage==nPage );
   37373 }
   37374 
   37375 /******************************************************************************/
   37376 /******** sqlite3_pcache Methods **********************************************/
   37377 
   37378 /*
   37379 ** Implementation of the sqlite3_pcache.xInit method.
   37380 */
   37381 static int pcache1Init(void *NotUsed){
   37382   UNUSED_PARAMETER(NotUsed);
   37383   assert( pcache1.isInit==0 );
   37384   memset(&pcache1, 0, sizeof(pcache1));
   37385   if( sqlite3GlobalConfig.bCoreMutex ){
   37386     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   37387     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
   37388   }
   37389   pcache1.grp.mxPinned = 10;
   37390   pcache1.isInit = 1;
   37391   return SQLITE_OK;
   37392 }
   37393 
   37394 /*
   37395 ** Implementation of the sqlite3_pcache.xShutdown method.
   37396 ** Note that the static mutex allocated in xInit does
   37397 ** not need to be freed.
   37398 */
   37399 static void pcache1Shutdown(void *NotUsed){
   37400   UNUSED_PARAMETER(NotUsed);
   37401   assert( pcache1.isInit!=0 );
   37402   memset(&pcache1, 0, sizeof(pcache1));
   37403 }
   37404 
   37405 /*
   37406 ** Implementation of the sqlite3_pcache.xCreate method.
   37407 **
   37408 ** Allocate a new cache.
   37409 */
   37410 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   37411   PCache1 *pCache;      /* The newly created page cache */
   37412   PGroup *pGroup;       /* The group the new page cache will belong to */
   37413   int sz;               /* Bytes of memory required to allocate the new cache */
   37414 
   37415   /*
   37416   ** The seperateCache variable is true if each PCache has its own private
   37417   ** PGroup.  In other words, separateCache is true for mode (1) where no
   37418   ** mutexing is required.
   37419   **
   37420   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
   37421   **
   37422   **   *  Always use a unified cache in single-threaded applications
   37423   **
   37424   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
   37425   **      use separate caches (mode-1)
   37426   */
   37427 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   37428   const int separateCache = 0;
   37429 #else
   37430   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
   37431 #endif
   37432 
   37433   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
   37434   assert( szExtra < 300 );
   37435 
   37436   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
   37437   pCache = (PCache1 *)sqlite3_malloc(sz);
   37438   if( pCache ){
   37439     memset(pCache, 0, sz);
   37440     if( separateCache ){
   37441       pGroup = (PGroup*)&pCache[1];
   37442       pGroup->mxPinned = 10;
   37443     }else{
   37444       pGroup = &pcache1.grp;
   37445     }
   37446     pCache->pGroup = pGroup;
   37447     pCache->szPage = szPage;
   37448     pCache->szExtra = szExtra;
   37449     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   37450     if( bPurgeable ){
   37451       pCache->nMin = 10;
   37452       pcache1EnterMutex(pGroup);
   37453       pGroup->nMinPage += pCache->nMin;
   37454       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37455       pcache1LeaveMutex(pGroup);
   37456     }
   37457   }
   37458   return (sqlite3_pcache *)pCache;
   37459 }
   37460 
   37461 /*
   37462 ** Implementation of the sqlite3_pcache.xCachesize method.
   37463 **
   37464 ** Configure the cache_size limit for a cache.
   37465 */
   37466 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   37467   PCache1 *pCache = (PCache1 *)p;
   37468   if( pCache->bPurgeable ){
   37469     PGroup *pGroup = pCache->pGroup;
   37470     pcache1EnterMutex(pGroup);
   37471     pGroup->nMaxPage += (nMax - pCache->nMax);
   37472     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37473     pCache->nMax = nMax;
   37474     pCache->n90pct = pCache->nMax*9/10;
   37475     pcache1EnforceMaxPage(pGroup);
   37476     pcache1LeaveMutex(pGroup);
   37477   }
   37478 }
   37479 
   37480 /*
   37481 ** Implementation of the sqlite3_pcache.xShrink method.
   37482 **
   37483 ** Free up as much memory as possible.
   37484 */
   37485 static void pcache1Shrink(sqlite3_pcache *p){
   37486   PCache1 *pCache = (PCache1*)p;
   37487   if( pCache->bPurgeable ){
   37488     PGroup *pGroup = pCache->pGroup;
   37489     int savedMaxPage;
   37490     pcache1EnterMutex(pGroup);
   37491     savedMaxPage = pGroup->nMaxPage;
   37492     pGroup->nMaxPage = 0;
   37493     pcache1EnforceMaxPage(pGroup);
   37494     pGroup->nMaxPage = savedMaxPage;
   37495     pcache1LeaveMutex(pGroup);
   37496   }
   37497 }
   37498 
   37499 /*
   37500 ** Implementation of the sqlite3_pcache.xPagecount method.
   37501 */
   37502 static int pcache1Pagecount(sqlite3_pcache *p){
   37503   int n;
   37504   PCache1 *pCache = (PCache1*)p;
   37505   pcache1EnterMutex(pCache->pGroup);
   37506   n = pCache->nPage;
   37507   pcache1LeaveMutex(pCache->pGroup);
   37508   return n;
   37509 }
   37510 
   37511 /*
   37512 ** Implementation of the sqlite3_pcache.xFetch method.
   37513 **
   37514 ** Fetch a page by key value.
   37515 **
   37516 ** Whether or not a new page may be allocated by this function depends on
   37517 ** the value of the createFlag argument.  0 means do not allocate a new
   37518 ** page.  1 means allocate a new page if space is easily available.  2
   37519 ** means to try really hard to allocate a new page.
   37520 **
   37521 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   37522 ** database) there is really no difference between createFlag 1 and 2.  So
   37523 ** the calling function (pcache.c) will never have a createFlag of 1 on
   37524 ** a non-purgeable cache.
   37525 **
   37526 ** There are three different approaches to obtaining space for a page,
   37527 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   37528 **
   37529 **   1. Regardless of the value of createFlag, the cache is searched for a
   37530 **      copy of the requested page. If one is found, it is returned.
   37531 **
   37532 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   37533 **      returned.
   37534 **
   37535 **   3. If createFlag is 1, and the page is not already in the cache, then
   37536 **      return NULL (do not allocate a new page) if any of the following
   37537 **      conditions are true:
   37538 **
   37539 **       (a) the number of pages pinned by the cache is greater than
   37540 **           PCache1.nMax, or
   37541 **
   37542 **       (b) the number of pages pinned by the cache is greater than
   37543 **           the sum of nMax for all purgeable caches, less the sum of
   37544 **           nMin for all other purgeable caches, or
   37545 **
   37546 **   4. If none of the first three conditions apply and the cache is marked
   37547 **      as purgeable, and if one of the following is true:
   37548 **
   37549 **       (a) The number of pages allocated for the cache is already
   37550 **           PCache1.nMax, or
   37551 **
   37552 **       (b) The number of pages allocated for all purgeable caches is
   37553 **           already equal to or greater than the sum of nMax for all
   37554 **           purgeable caches,
   37555 **
   37556 **       (c) The system is under memory pressure and wants to avoid
   37557 **           unnecessary pages cache entry allocations
   37558 **
   37559 **      then attempt to recycle a page from the LRU list. If it is the right
   37560 **      size, return the recycled buffer. Otherwise, free the buffer and
   37561 **      proceed to step 5.
   37562 **
   37563 **   5. Otherwise, allocate and return a new page buffer.
   37564 */
   37565 static sqlite3_pcache_page *pcache1Fetch(
   37566   sqlite3_pcache *p,
   37567   unsigned int iKey,
   37568   int createFlag
   37569 ){
   37570   unsigned int nPinned;
   37571   PCache1 *pCache = (PCache1 *)p;
   37572   PGroup *pGroup;
   37573   PgHdr1 *pPage = 0;
   37574 
   37575   assert( pCache->bPurgeable || createFlag!=1 );
   37576   assert( pCache->bPurgeable || pCache->nMin==0 );
   37577   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
   37578   assert( pCache->nMin==0 || pCache->bPurgeable );
   37579   pcache1EnterMutex(pGroup = pCache->pGroup);
   37580 
   37581   /* Step 1: Search the hash table for an existing entry. */
   37582   if( pCache->nHash>0 ){
   37583     unsigned int h = iKey % pCache->nHash;
   37584     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   37585   }
   37586 
   37587   /* Step 2: Abort if no existing page is found and createFlag is 0 */
   37588   if( pPage || createFlag==0 ){
   37589     pcache1PinPage(pPage);
   37590     goto fetch_out;
   37591   }
   37592 
   37593   /* The pGroup local variable will normally be initialized by the
   37594   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
   37595   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
   37596   ** local variable here.  Delaying the initialization of pGroup is an
   37597   ** optimization:  The common case is to exit the module before reaching
   37598   ** this point.
   37599   */
   37600 #ifdef SQLITE_MUTEX_OMIT
   37601   pGroup = pCache->pGroup;
   37602 #endif
   37603 
   37604   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
   37605   assert( pCache->nPage >= pCache->nRecyclable );
   37606   nPinned = pCache->nPage - pCache->nRecyclable;
   37607   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   37608   assert( pCache->n90pct == pCache->nMax*9/10 );
   37609   if( createFlag==1 && (
   37610         nPinned>=pGroup->mxPinned
   37611      || nPinned>=pCache->n90pct
   37612      || pcache1UnderMemoryPressure(pCache)
   37613   )){
   37614     goto fetch_out;
   37615   }
   37616 
   37617   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   37618     goto fetch_out;
   37619   }
   37620 
   37621   /* Step 4. Try to recycle a page. */
   37622   if( pCache->bPurgeable && pGroup->pLruTail && (
   37623          (pCache->nPage+1>=pCache->nMax)
   37624       || pGroup->nCurrentPage>=pGroup->nMaxPage
   37625       || pcache1UnderMemoryPressure(pCache)
   37626   )){
   37627     PCache1 *pOther;
   37628     pPage = pGroup->pLruTail;
   37629     pcache1RemoveFromHash(pPage);
   37630     pcache1PinPage(pPage);
   37631     pOther = pPage->pCache;
   37632 
   37633     /* We want to verify that szPage and szExtra are the same for pOther
   37634     ** and pCache.  Assert that we can verify this by comparing sums. */
   37635     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
   37636     assert( pCache->szExtra<512 );
   37637     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
   37638     assert( pOther->szExtra<512 );
   37639 
   37640     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
   37641       pcache1FreePage(pPage);
   37642       pPage = 0;
   37643     }else{
   37644       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
   37645     }
   37646   }
   37647 
   37648   /* Step 5. If a usable page buffer has still not been found,
   37649   ** attempt to allocate a new one.
   37650   */
   37651   if( !pPage ){
   37652     if( createFlag==1 ) sqlite3BeginBenignMalloc();
   37653     pPage = pcache1AllocPage(pCache);
   37654     if( createFlag==1 ) sqlite3EndBenignMalloc();
   37655   }
   37656 
   37657   if( pPage ){
   37658     unsigned int h = iKey % pCache->nHash;
   37659     pCache->nPage++;
   37660     pPage->iKey = iKey;
   37661     pPage->pNext = pCache->apHash[h];
   37662     pPage->pCache = pCache;
   37663     pPage->pLruPrev = 0;
   37664     pPage->pLruNext = 0;
   37665     *(void **)pPage->page.pExtra = 0;
   37666     pCache->apHash[h] = pPage;
   37667   }
   37668 
   37669 fetch_out:
   37670   if( pPage && iKey>pCache->iMaxKey ){
   37671     pCache->iMaxKey = iKey;
   37672   }
   37673   pcache1LeaveMutex(pGroup);
   37674   return &pPage->page;
   37675 }
   37676 
   37677 
   37678 /*
   37679 ** Implementation of the sqlite3_pcache.xUnpin method.
   37680 **
   37681 ** Mark a page as unpinned (eligible for asynchronous recycling).
   37682 */
   37683 static void pcache1Unpin(
   37684   sqlite3_pcache *p,
   37685   sqlite3_pcache_page *pPg,
   37686   int reuseUnlikely
   37687 ){
   37688   PCache1 *pCache = (PCache1 *)p;
   37689   PgHdr1 *pPage = (PgHdr1 *)pPg;
   37690   PGroup *pGroup = pCache->pGroup;
   37691 
   37692   assert( pPage->pCache==pCache );
   37693   pcache1EnterMutex(pGroup);
   37694 
   37695   /* It is an error to call this function if the page is already
   37696   ** part of the PGroup LRU list.
   37697   */
   37698   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   37699   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
   37700 
   37701   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
   37702     pcache1RemoveFromHash(pPage);
   37703     pcache1FreePage(pPage);
   37704   }else{
   37705     /* Add the page to the PGroup LRU list. */
   37706     if( pGroup->pLruHead ){
   37707       pGroup->pLruHead->pLruPrev = pPage;
   37708       pPage->pLruNext = pGroup->pLruHead;
   37709       pGroup->pLruHead = pPage;
   37710     }else{
   37711       pGroup->pLruTail = pPage;
   37712       pGroup->pLruHead = pPage;
   37713     }
   37714     pCache->nRecyclable++;
   37715   }
   37716 
   37717   pcache1LeaveMutex(pCache->pGroup);
   37718 }
   37719 
   37720 /*
   37721 ** Implementation of the sqlite3_pcache.xRekey method.
   37722 */
   37723 static void pcache1Rekey(
   37724   sqlite3_pcache *p,
   37725   sqlite3_pcache_page *pPg,
   37726   unsigned int iOld,
   37727   unsigned int iNew
   37728 ){
   37729   PCache1 *pCache = (PCache1 *)p;
   37730   PgHdr1 *pPage = (PgHdr1 *)pPg;
   37731   PgHdr1 **pp;
   37732   unsigned int h;
   37733   assert( pPage->iKey==iOld );
   37734   assert( pPage->pCache==pCache );
   37735 
   37736   pcache1EnterMutex(pCache->pGroup);
   37737 
   37738   h = iOld%pCache->nHash;
   37739   pp = &pCache->apHash[h];
   37740   while( (*pp)!=pPage ){
   37741     pp = &(*pp)->pNext;
   37742   }
   37743   *pp = pPage->pNext;
   37744 
   37745   h = iNew%pCache->nHash;
   37746   pPage->iKey = iNew;
   37747   pPage->pNext = pCache->apHash[h];
   37748   pCache->apHash[h] = pPage;
   37749   if( iNew>pCache->iMaxKey ){
   37750     pCache->iMaxKey = iNew;
   37751   }
   37752 
   37753   pcache1LeaveMutex(pCache->pGroup);
   37754 }
   37755 
   37756 /*
   37757 ** Implementation of the sqlite3_pcache.xTruncate method.
   37758 **
   37759 ** Discard all unpinned pages in the cache with a page number equal to
   37760 ** or greater than parameter iLimit. Any pinned pages with a page number
   37761 ** equal to or greater than iLimit are implicitly unpinned.
   37762 */
   37763 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   37764   PCache1 *pCache = (PCache1 *)p;
   37765   pcache1EnterMutex(pCache->pGroup);
   37766   if( iLimit<=pCache->iMaxKey ){
   37767     pcache1TruncateUnsafe(pCache, iLimit);
   37768     pCache->iMaxKey = iLimit-1;
   37769   }
   37770   pcache1LeaveMutex(pCache->pGroup);
   37771 }
   37772 
   37773 /*
   37774 ** Implementation of the sqlite3_pcache.xDestroy method.
   37775 **
   37776 ** Destroy a cache allocated using pcache1Create().
   37777 */
   37778 static void pcache1Destroy(sqlite3_pcache *p){
   37779   PCache1 *pCache = (PCache1 *)p;
   37780   PGroup *pGroup = pCache->pGroup;
   37781   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   37782   pcache1EnterMutex(pGroup);
   37783   pcache1TruncateUnsafe(pCache, 0);
   37784   assert( pGroup->nMaxPage >= pCache->nMax );
   37785   pGroup->nMaxPage -= pCache->nMax;
   37786   assert( pGroup->nMinPage >= pCache->nMin );
   37787   pGroup->nMinPage -= pCache->nMin;
   37788   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   37789   pcache1EnforceMaxPage(pGroup);
   37790   pcache1LeaveMutex(pGroup);
   37791   sqlite3_free(pCache->apHash);
   37792   sqlite3_free(pCache);
   37793 }
   37794 
   37795 /*
   37796 ** This function is called during initialization (sqlite3_initialize()) to
   37797 ** install the default pluggable cache module, assuming the user has not
   37798 ** already provided an alternative.
   37799 */
   37800 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   37801   static const sqlite3_pcache_methods2 defaultMethods = {
   37802     1,                       /* iVersion */
   37803     0,                       /* pArg */
   37804     pcache1Init,             /* xInit */
   37805     pcache1Shutdown,         /* xShutdown */
   37806     pcache1Create,           /* xCreate */
   37807     pcache1Cachesize,        /* xCachesize */
   37808     pcache1Pagecount,        /* xPagecount */
   37809     pcache1Fetch,            /* xFetch */
   37810     pcache1Unpin,            /* xUnpin */
   37811     pcache1Rekey,            /* xRekey */
   37812     pcache1Truncate,         /* xTruncate */
   37813     pcache1Destroy,          /* xDestroy */
   37814     pcache1Shrink            /* xShrink */
   37815   };
   37816   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   37817 }
   37818 
   37819 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   37820 /*
   37821 ** This function is called to free superfluous dynamically allocated memory
   37822 ** held by the pager system. Memory in use by any SQLite pager allocated
   37823 ** by the current thread may be sqlite3_free()ed.
   37824 **
   37825 ** nReq is the number of bytes of memory required. Once this much has
   37826 ** been released, the function returns. The return value is the total number
   37827 ** of bytes of memory released.
   37828 */
   37829 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   37830   int nFree = 0;
   37831   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   37832   assert( sqlite3_mutex_notheld(pcache1.mutex) );
   37833   if( pcache1.pStart==0 ){
   37834     PgHdr1 *p;
   37835     pcache1EnterMutex(&pcache1.grp);
   37836     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
   37837       nFree += pcache1MemSize(p->page.pBuf);
   37838 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
   37839       nFree += sqlite3MemSize(p);
   37840 #endif
   37841       pcache1PinPage(p);
   37842       pcache1RemoveFromHash(p);
   37843       pcache1FreePage(p);
   37844     }
   37845     pcache1LeaveMutex(&pcache1.grp);
   37846   }
   37847   return nFree;
   37848 }
   37849 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   37850 
   37851 #ifdef SQLITE_TEST
   37852 /*
   37853 ** This function is used by test procedures to inspect the internal state
   37854 ** of the global cache.
   37855 */
   37856 SQLITE_PRIVATE void sqlite3PcacheStats(
   37857   int *pnCurrent,      /* OUT: Total number of pages cached */
   37858   int *pnMax,          /* OUT: Global maximum cache size */
   37859   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   37860   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   37861 ){
   37862   PgHdr1 *p;
   37863   int nRecyclable = 0;
   37864   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
   37865     nRecyclable++;
   37866   }
   37867   *pnCurrent = pcache1.grp.nCurrentPage;
   37868   *pnMax = (int)pcache1.grp.nMaxPage;
   37869   *pnMin = (int)pcache1.grp.nMinPage;
   37870   *pnRecyclable = nRecyclable;
   37871 }
   37872 #endif
   37873 
   37874 /************** End of pcache1.c *********************************************/
   37875 /************** Begin file rowset.c ******************************************/
   37876 /*
   37877 ** 2008 December 3
   37878 **
   37879 ** The author disclaims copyright to this source code.  In place of
   37880 ** a legal notice, here is a blessing:
   37881 **
   37882 **    May you do good and not evil.
   37883 **    May you find forgiveness for yourself and forgive others.
   37884 **    May you share freely, never taking more than you give.
   37885 **
   37886 *************************************************************************
   37887 **
   37888 ** This module implements an object we call a "RowSet".
   37889 **
   37890 ** The RowSet object is a collection of rowids.  Rowids
   37891 ** are inserted into the RowSet in an arbitrary order.  Inserts
   37892 ** can be intermixed with tests to see if a given rowid has been
   37893 ** previously inserted into the RowSet.
   37894 **
   37895 ** After all inserts are finished, it is possible to extract the
   37896 ** elements of the RowSet in sorted order.  Once this extraction
   37897 ** process has started, no new elements may be inserted.
   37898 **
   37899 ** Hence, the primitive operations for a RowSet are:
   37900 **
   37901 **    CREATE
   37902 **    INSERT
   37903 **    TEST
   37904 **    SMALLEST
   37905 **    DESTROY
   37906 **
   37907 ** The CREATE and DESTROY primitives are the constructor and destructor,
   37908 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   37909 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   37910 ** extracts the least value from the RowSet.
   37911 **
   37912 ** The INSERT primitive might allocate additional memory.  Memory is
   37913 ** allocated in chunks so most INSERTs do no allocation.  There is an
   37914 ** upper bound on the size of allocated memory.  No memory is freed
   37915 ** until DESTROY.
   37916 **
   37917 ** The TEST primitive includes a "batch" number.  The TEST primitive
   37918 ** will only see elements that were inserted before the last change
   37919 ** in the batch number.  In other words, if an INSERT occurs between
   37920 ** two TESTs where the TESTs have the same batch nubmer, then the
   37921 ** value added by the INSERT will not be visible to the second TEST.
   37922 ** The initial batch number is zero, so if the very first TEST contains
   37923 ** a non-zero batch number, it will see all prior INSERTs.
   37924 **
   37925 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   37926 ** that is attempted.
   37927 **
   37928 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   37929 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   37930 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   37931 ** The cost of a TEST using the same batch number is O(logN).  The cost
   37932 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   37933 ** primitives are constant time.  The cost of DESTROY is O(N).
   37934 **
   37935 ** There is an added cost of O(N) when switching between TEST and
   37936 ** SMALLEST primitives.
   37937 */
   37938 
   37939 
   37940 /*
   37941 ** Target size for allocation chunks.
   37942 */
   37943 #define ROWSET_ALLOCATION_SIZE 1024
   37944 
   37945 /*
   37946 ** The number of rowset entries per allocation chunk.
   37947 */
   37948 #define ROWSET_ENTRY_PER_CHUNK  \
   37949                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   37950 
   37951 /*
   37952 ** Each entry in a RowSet is an instance of the following object.
   37953 */
   37954 struct RowSetEntry {
   37955   i64 v;                        /* ROWID value for this entry */
   37956   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   37957   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   37958 };
   37959 
   37960 /*
   37961 ** RowSetEntry objects are allocated in large chunks (instances of the
   37962 ** following structure) to reduce memory allocation overhead.  The
   37963 ** chunks are kept on a linked list so that they can be deallocated
   37964 ** when the RowSet is destroyed.
   37965 */
   37966 struct RowSetChunk {
   37967   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   37968   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   37969 };
   37970 
   37971 /*
   37972 ** A RowSet in an instance of the following structure.
   37973 **
   37974 ** A typedef of this structure if found in sqliteInt.h.
   37975 */
   37976 struct RowSet {
   37977   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   37978   sqlite3 *db;                   /* The database connection */
   37979   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   37980   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   37981   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   37982   struct RowSetEntry *pTree;     /* Binary tree of entries */
   37983   u16 nFresh;                    /* Number of objects on pFresh */
   37984   u8 isSorted;                   /* True if pEntry is sorted */
   37985   u8 iBatch;                     /* Current insert batch */
   37986 };
   37987 
   37988 /*
   37989 ** Turn bulk memory into a RowSet object.  N bytes of memory
   37990 ** are available at pSpace.  The db pointer is used as a memory context
   37991 ** for any subsequent allocations that need to occur.
   37992 ** Return a pointer to the new RowSet object.
   37993 **
   37994 ** It must be the case that N is sufficient to make a Rowset.  If not
   37995 ** an assertion fault occurs.
   37996 **
   37997 ** If N is larger than the minimum, use the surplus as an initial
   37998 ** allocation of entries available to be filled.
   37999 */
   38000 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   38001   RowSet *p;
   38002   assert( N >= ROUND8(sizeof(*p)) );
   38003   p = pSpace;
   38004   p->pChunk = 0;
   38005   p->db = db;
   38006   p->pEntry = 0;
   38007   p->pLast = 0;
   38008   p->pTree = 0;
   38009   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   38010   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   38011   p->isSorted = 1;
   38012   p->iBatch = 0;
   38013   return p;
   38014 }
   38015 
   38016 /*
   38017 ** Deallocate all chunks from a RowSet.  This frees all memory that
   38018 ** the RowSet has allocated over its lifetime.  This routine is
   38019 ** the destructor for the RowSet.
   38020 */
   38021 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   38022   struct RowSetChunk *pChunk, *pNextChunk;
   38023   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   38024     pNextChunk = pChunk->pNextChunk;
   38025     sqlite3DbFree(p->db, pChunk);
   38026   }
   38027   p->pChunk = 0;
   38028   p->nFresh = 0;
   38029   p->pEntry = 0;
   38030   p->pLast = 0;
   38031   p->pTree = 0;
   38032   p->isSorted = 1;
   38033 }
   38034 
   38035 /*
   38036 ** Insert a new value into a RowSet.
   38037 **
   38038 ** The mallocFailed flag of the database connection is set if a
   38039 ** memory allocation fails.
   38040 */
   38041 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   38042   struct RowSetEntry *pEntry;  /* The new entry */
   38043   struct RowSetEntry *pLast;   /* The last prior entry */
   38044   assert( p!=0 );
   38045   if( p->nFresh==0 ){
   38046     struct RowSetChunk *pNew;
   38047     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   38048     if( pNew==0 ){
   38049       return;
   38050     }
   38051     pNew->pNextChunk = p->pChunk;
   38052     p->pChunk = pNew;
   38053     p->pFresh = pNew->aEntry;
   38054     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   38055   }
   38056   pEntry = p->pFresh++;
   38057   p->nFresh--;
   38058   pEntry->v = rowid;
   38059   pEntry->pRight = 0;
   38060   pLast = p->pLast;
   38061   if( pLast ){
   38062     if( p->isSorted && rowid<=pLast->v ){
   38063       p->isSorted = 0;
   38064     }
   38065     pLast->pRight = pEntry;
   38066   }else{
   38067     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
   38068     p->pEntry = pEntry;
   38069   }
   38070   p->pLast = pEntry;
   38071 }
   38072 
   38073 /*
   38074 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   38075 **
   38076 ** The input lists are connected via pRight pointers and are
   38077 ** assumed to each already be in sorted order.
   38078 */
   38079 static struct RowSetEntry *rowSetMerge(
   38080   struct RowSetEntry *pA,    /* First sorted list to be merged */
   38081   struct RowSetEntry *pB     /* Second sorted list to be merged */
   38082 ){
   38083   struct RowSetEntry head;
   38084   struct RowSetEntry *pTail;
   38085 
   38086   pTail = &head;
   38087   while( pA && pB ){
   38088     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   38089     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   38090     if( pA->v<pB->v ){
   38091       pTail->pRight = pA;
   38092       pA = pA->pRight;
   38093       pTail = pTail->pRight;
   38094     }else if( pB->v<pA->v ){
   38095       pTail->pRight = pB;
   38096       pB = pB->pRight;
   38097       pTail = pTail->pRight;
   38098     }else{
   38099       pA = pA->pRight;
   38100     }
   38101   }
   38102   if( pA ){
   38103     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   38104     pTail->pRight = pA;
   38105   }else{
   38106     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   38107     pTail->pRight = pB;
   38108   }
   38109   return head.pRight;
   38110 }
   38111 
   38112 /*
   38113 ** Sort all elements on the pEntry list of the RowSet into ascending order.
   38114 */
   38115 static void rowSetSort(RowSet *p){
   38116   unsigned int i;
   38117   struct RowSetEntry *pEntry;
   38118   struct RowSetEntry *aBucket[40];
   38119 
   38120   assert( p->isSorted==0 );
   38121   memset(aBucket, 0, sizeof(aBucket));
   38122   while( p->pEntry ){
   38123     pEntry = p->pEntry;
   38124     p->pEntry = pEntry->pRight;
   38125     pEntry->pRight = 0;
   38126     for(i=0; aBucket[i]; i++){
   38127       pEntry = rowSetMerge(aBucket[i], pEntry);
   38128       aBucket[i] = 0;
   38129     }
   38130     aBucket[i] = pEntry;
   38131   }
   38132   pEntry = 0;
   38133   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   38134     pEntry = rowSetMerge(pEntry, aBucket[i]);
   38135   }
   38136   p->pEntry = pEntry;
   38137   p->pLast = 0;
   38138   p->isSorted = 1;
   38139 }
   38140 
   38141 
   38142 /*
   38143 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   38144 ** Convert this tree into a linked list connected by the pRight pointers
   38145 ** and return pointers to the first and last elements of the new list.
   38146 */
   38147 static void rowSetTreeToList(
   38148   struct RowSetEntry *pIn,         /* Root of the input tree */
   38149   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   38150   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   38151 ){
   38152   assert( pIn!=0 );
   38153   if( pIn->pLeft ){
   38154     struct RowSetEntry *p;
   38155     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   38156     p->pRight = pIn;
   38157   }else{
   38158     *ppFirst = pIn;
   38159   }
   38160   if( pIn->pRight ){
   38161     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   38162   }else{
   38163     *ppLast = pIn;
   38164   }
   38165   assert( (*ppLast)->pRight==0 );
   38166 }
   38167 
   38168 
   38169 /*
   38170 ** Convert a sorted list of elements (connected by pRight) into a binary
   38171 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   38172 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   38173 ** three nodes.  And so forth.
   38174 **
   38175 ** Use as many entries from the input list as required and update the
   38176 ** *ppList to point to the unused elements of the list.  If the input
   38177 ** list contains too few elements, then construct an incomplete tree
   38178 ** and leave *ppList set to NULL.
   38179 **
   38180 ** Return a pointer to the root of the constructed binary tree.
   38181 */
   38182 static struct RowSetEntry *rowSetNDeepTree(
   38183   struct RowSetEntry **ppList,
   38184   int iDepth
   38185 ){
   38186   struct RowSetEntry *p;         /* Root of the new tree */
   38187   struct RowSetEntry *pLeft;     /* Left subtree */
   38188   if( *ppList==0 ){
   38189     return 0;
   38190   }
   38191   if( iDepth==1 ){
   38192     p = *ppList;
   38193     *ppList = p->pRight;
   38194     p->pLeft = p->pRight = 0;
   38195     return p;
   38196   }
   38197   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   38198   p = *ppList;
   38199   if( p==0 ){
   38200     return pLeft;
   38201   }
   38202   p->pLeft = pLeft;
   38203   *ppList = p->pRight;
   38204   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   38205   return p;
   38206 }
   38207 
   38208 /*
   38209 ** Convert a sorted list of elements into a binary tree. Make the tree
   38210 ** as deep as it needs to be in order to contain the entire list.
   38211 */
   38212 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   38213   int iDepth;           /* Depth of the tree so far */
   38214   struct RowSetEntry *p;       /* Current tree root */
   38215   struct RowSetEntry *pLeft;   /* Left subtree */
   38216 
   38217   assert( pList!=0 );
   38218   p = pList;
   38219   pList = p->pRight;
   38220   p->pLeft = p->pRight = 0;
   38221   for(iDepth=1; pList; iDepth++){
   38222     pLeft = p;
   38223     p = pList;
   38224     pList = p->pRight;
   38225     p->pLeft = pLeft;
   38226     p->pRight = rowSetNDeepTree(&pList, iDepth);
   38227   }
   38228   return p;
   38229 }
   38230 
   38231 /*
   38232 ** Convert the list in p->pEntry into a sorted list if it is not
   38233 ** sorted already.  If there is a binary tree on p->pTree, then
   38234 ** convert it into a list too and merge it into the p->pEntry list.
   38235 */
   38236 static void rowSetToList(RowSet *p){
   38237   if( !p->isSorted ){
   38238     rowSetSort(p);
   38239   }
   38240   if( p->pTree ){
   38241     struct RowSetEntry *pHead, *pTail;
   38242     rowSetTreeToList(p->pTree, &pHead, &pTail);
   38243     p->pTree = 0;
   38244     p->pEntry = rowSetMerge(p->pEntry, pHead);
   38245   }
   38246 }
   38247 
   38248 /*
   38249 ** Extract the smallest element from the RowSet.
   38250 ** Write the element into *pRowid.  Return 1 on success.  Return
   38251 ** 0 if the RowSet is already empty.
   38252 **
   38253 ** After this routine has been called, the sqlite3RowSetInsert()
   38254 ** routine may not be called again.
   38255 */
   38256 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   38257   rowSetToList(p);
   38258   if( p->pEntry ){
   38259     *pRowid = p->pEntry->v;
   38260     p->pEntry = p->pEntry->pRight;
   38261     if( p->pEntry==0 ){
   38262       sqlite3RowSetClear(p);
   38263     }
   38264     return 1;
   38265   }else{
   38266     return 0;
   38267   }
   38268 }
   38269 
   38270 /*
   38271 ** Check to see if element iRowid was inserted into the the rowset as
   38272 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   38273 */
   38274 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
   38275   struct RowSetEntry *p;
   38276   if( iBatch!=pRowSet->iBatch ){
   38277     if( pRowSet->pEntry ){
   38278       rowSetToList(pRowSet);
   38279       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
   38280       pRowSet->pEntry = 0;
   38281       pRowSet->pLast = 0;
   38282     }
   38283     pRowSet->iBatch = iBatch;
   38284   }
   38285   p = pRowSet->pTree;
   38286   while( p ){
   38287     if( p->v<iRowid ){
   38288       p = p->pRight;
   38289     }else if( p->v>iRowid ){
   38290       p = p->pLeft;
   38291     }else{
   38292       return 1;
   38293     }
   38294   }
   38295   return 0;
   38296 }
   38297 
   38298 /************** End of rowset.c **********************************************/
   38299 /************** Begin file pager.c *******************************************/
   38300 /*
   38301 ** 2001 September 15
   38302 **
   38303 ** The author disclaims copyright to this source code.  In place of
   38304 ** a legal notice, here is a blessing:
   38305 **
   38306 **    May you do good and not evil.
   38307 **    May you find forgiveness for yourself and forgive others.
   38308 **    May you share freely, never taking more than you give.
   38309 **
   38310 *************************************************************************
   38311 ** This is the implementation of the page cache subsystem or "pager".
   38312 **
   38313 ** The pager is used to access a database disk file.  It implements
   38314 ** atomic commit and rollback through the use of a journal file that
   38315 ** is separate from the database file.  The pager also implements file
   38316 ** locking to prevent two processes from writing the same database
   38317 ** file simultaneously, or one process from reading the database while
   38318 ** another is writing.
   38319 */
   38320 #ifndef SQLITE_OMIT_DISKIO
   38321 /************** Include wal.h in the middle of pager.c ***********************/
   38322 /************** Begin file wal.h *********************************************/
   38323 /*
   38324 ** 2010 February 1
   38325 **
   38326 ** The author disclaims copyright to this source code.  In place of
   38327 ** a legal notice, here is a blessing:
   38328 **
   38329 **    May you do good and not evil.
   38330 **    May you find forgiveness for yourself and forgive others.
   38331 **    May you share freely, never taking more than you give.
   38332 **
   38333 *************************************************************************
   38334 ** This header file defines the interface to the write-ahead logging
   38335 ** system. Refer to the comments below and the header comment attached to
   38336 ** the implementation of each function in log.c for further details.
   38337 */
   38338 
   38339 #ifndef _WAL_H_
   38340 #define _WAL_H_
   38341 
   38342 
   38343 /* Additional values that can be added to the sync_flags argument of
   38344 ** sqlite3WalFrames():
   38345 */
   38346 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
   38347 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
   38348 
   38349 #ifdef SQLITE_OMIT_WAL
   38350 # define sqlite3WalOpen(x,y,z)                   0
   38351 # define sqlite3WalLimit(x,y)
   38352 # define sqlite3WalClose(w,x,y,z)                0
   38353 # define sqlite3WalBeginReadTransaction(y,z)     0
   38354 # define sqlite3WalEndReadTransaction(z)
   38355 # define sqlite3WalRead(v,w,x,y,z)               0
   38356 # define sqlite3WalDbsize(y)                     0
   38357 # define sqlite3WalBeginWriteTransaction(y)      0
   38358 # define sqlite3WalEndWriteTransaction(x)        0
   38359 # define sqlite3WalUndo(x,y,z)                   0
   38360 # define sqlite3WalSavepoint(y,z)
   38361 # define sqlite3WalSavepointUndo(y,z)            0
   38362 # define sqlite3WalFrames(u,v,w,x,y,z)           0
   38363 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
   38364 # define sqlite3WalCallback(z)                   0
   38365 # define sqlite3WalExclusiveMode(y,z)            0
   38366 # define sqlite3WalHeapMemory(z)                 0
   38367 # define sqlite3WalFramesize(z)                  0
   38368 #else
   38369 
   38370 #define WAL_SAVEPOINT_NDATA 4
   38371 
   38372 /* Connection to a write-ahead log (WAL) file.
   38373 ** There is one object of this type for each pager.
   38374 */
   38375 typedef struct Wal Wal;
   38376 
   38377 /* Open and close a connection to a write-ahead log. */
   38378 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
   38379 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
   38380 
   38381 /* Set the limiting size of a WAL file. */
   38382 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
   38383 
   38384 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   38385 ** snapshot is like a read-transaction.  It is the state of the database
   38386 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   38387 ** preserves the current state even if the other threads or processes
   38388 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   38389 ** transaction and releases the lock.
   38390 */
   38391 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   38392 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   38393 
   38394 /* Read a page from the write-ahead log, if it is present. */
   38395 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
   38396 
   38397 /* If the WAL is not empty, return the size of the database. */
   38398 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   38399 
   38400 /* Obtain or release the WRITER lock. */
   38401 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   38402 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   38403 
   38404 /* Undo any frames written (but not committed) to the log */
   38405 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   38406 
   38407 /* Return an integer that records the current (uncommitted) write
   38408 ** position in the WAL */
   38409 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   38410 
   38411 /* Move the write position of the WAL back to iFrame.  Called in
   38412 ** response to a ROLLBACK TO command. */
   38413 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   38414 
   38415 /* Write a frame or frames to the log. */
   38416 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   38417 
   38418 /* Copy pages from the log to the database file */
   38419 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   38420   Wal *pWal,                      /* Write-ahead log connection */
   38421   int eMode,                      /* One of PASSIVE, FULL and RESTART */
   38422   int (*xBusy)(void*),            /* Function to call when busy */
   38423   void *pBusyArg,                 /* Context argument for xBusyHandler */
   38424   int sync_flags,                 /* Flags to sync db file with (or 0) */
   38425   int nBuf,                       /* Size of buffer nBuf */
   38426   u8 *zBuf,                       /* Temporary buffer to use */
   38427   int *pnLog,                     /* OUT: Number of frames in WAL */
   38428   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   38429 );
   38430 
   38431 /* Return the value to pass to a sqlite3_wal_hook callback, the
   38432 ** number of frames in the WAL at the point of the last commit since
   38433 ** sqlite3WalCallback() was called.  If no commits have occurred since
   38434 ** the last call, then return 0.
   38435 */
   38436 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   38437 
   38438 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   38439 ** by the pager layer on the database file.
   38440 */
   38441 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   38442 
   38443 /* Return true if the argument is non-NULL and the WAL module is using
   38444 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   38445 ** WAL module is using shared-memory, return false.
   38446 */
   38447 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   38448 
   38449 #ifdef SQLITE_ENABLE_ZIPVFS
   38450 /* If the WAL file is not empty, return the number of bytes of content
   38451 ** stored in each frame (i.e. the db page-size when the WAL was created).
   38452 */
   38453 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
   38454 #endif
   38455 
   38456 #endif /* ifndef SQLITE_OMIT_WAL */
   38457 #endif /* _WAL_H_ */
   38458 
   38459 /************** End of wal.h *************************************************/
   38460 /************** Continuing where we left off in pager.c **********************/
   38461 
   38462 
   38463 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   38464 **
   38465 ** This comment block describes invariants that hold when using a rollback
   38466 ** journal.  These invariants do not apply for journal_mode=WAL,
   38467 ** journal_mode=MEMORY, or journal_mode=OFF.
   38468 **
   38469 ** Within this comment block, a page is deemed to have been synced
   38470 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   38471 ** Otherwise, the page is not synced until the xSync method of the VFS
   38472 ** is called successfully on the file containing the page.
   38473 **
   38474 ** Definition:  A page of the database file is said to be "overwriteable" if
   38475 ** one or more of the following are true about the page:
   38476 **
   38477 **     (a)  The original content of the page as it was at the beginning of
   38478 **          the transaction has been written into the rollback journal and
   38479 **          synced.
   38480 **
   38481 **     (b)  The page was a freelist leaf page at the start of the transaction.
   38482 **
   38483 **     (c)  The page number is greater than the largest page that existed in
   38484 **          the database file at the start of the transaction.
   38485 **
   38486 ** (1) A page of the database file is never overwritten unless one of the
   38487 **     following are true:
   38488 **
   38489 **     (a) The page and all other pages on the same sector are overwriteable.
   38490 **
   38491 **     (b) The atomic page write optimization is enabled, and the entire
   38492 **         transaction other than the update of the transaction sequence
   38493 **         number consists of a single page change.
   38494 **
   38495 ** (2) The content of a page written into the rollback journal exactly matches
   38496 **     both the content in the database when the rollback journal was written
   38497 **     and the content in the database at the beginning of the current
   38498 **     transaction.
   38499 **
   38500 ** (3) Writes to the database file are an integer multiple of the page size
   38501 **     in length and are aligned on a page boundary.
   38502 **
   38503 ** (4) Reads from the database file are either aligned on a page boundary and
   38504 **     an integer multiple of the page size in length or are taken from the
   38505 **     first 100 bytes of the database file.
   38506 **
   38507 ** (5) All writes to the database file are synced prior to the rollback journal
   38508 **     being deleted, truncated, or zeroed.
   38509 **
   38510 ** (6) If a master journal file is used, then all writes to the database file
   38511 **     are synced prior to the master journal being deleted.
   38512 **
   38513 ** Definition: Two databases (or the same database at two points it time)
   38514 ** are said to be "logically equivalent" if they give the same answer to
   38515 ** all queries.  Note in particular the the content of freelist leaf
   38516 ** pages can be changed arbitarily without effecting the logical equivalence
   38517 ** of the database.
   38518 **
   38519 ** (7) At any time, if any subset, including the empty set and the total set,
   38520 **     of the unsynced changes to a rollback journal are removed and the
   38521 **     journal is rolled back, the resulting database file will be logical
   38522 **     equivalent to the database file at the beginning of the transaction.
   38523 **
   38524 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   38525 **     is called to restore the database file to the same size it was at
   38526 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   38527 **     method is a no-op, but that does not change the fact the SQLite will
   38528 **     invoke it.)
   38529 **
   38530 ** (9) Whenever the database file is modified, at least one bit in the range
   38531 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   38532 **     the EXCLUSIVE lock, thus signaling other connections on the same
   38533 **     database to flush their caches.
   38534 **
   38535 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   38536 **      than one billion transactions.
   38537 **
   38538 ** (11) A database file is well-formed at the beginning and at the conclusion
   38539 **      of every transaction.
   38540 **
   38541 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   38542 **      the database file.
   38543 **
   38544 ** (13) A SHARED lock is held on the database file while reading any
   38545 **      content out of the database file.
   38546 **
   38547 ******************************************************************************/
   38548 
   38549 /*
   38550 ** Macros for troubleshooting.  Normally turned off
   38551 */
   38552 #if 0
   38553 int sqlite3PagerTrace=1;  /* True to enable tracing */
   38554 #define sqlite3DebugPrintf printf
   38555 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   38556 #else
   38557 #define PAGERTRACE(X)
   38558 #endif
   38559 
   38560 /*
   38561 ** The following two macros are used within the PAGERTRACE() macros above
   38562 ** to print out file-descriptors.
   38563 **
   38564 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   38565 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   38566 ** struct as its argument.
   38567 */
   38568 #define PAGERID(p) ((int)(p->fd))
   38569 #define FILEHANDLEID(fd) ((int)fd)
   38570 
   38571 /*
   38572 ** The Pager.eState variable stores the current 'state' of a pager. A
   38573 ** pager may be in any one of the seven states shown in the following
   38574 ** state diagram.
   38575 **
   38576 **                            OPEN <------+------+
   38577 **                              |         |      |
   38578 **                              V         |      |
   38579 **               +---------> READER-------+      |
   38580 **               |              |                |
   38581 **               |              V                |
   38582 **               |<-------WRITER_LOCKED------> ERROR
   38583 **               |              |                ^
   38584 **               |              V                |
   38585 **               |<------WRITER_CACHEMOD-------->|
   38586 **               |              |                |
   38587 **               |              V                |
   38588 **               |<-------WRITER_DBMOD---------->|
   38589 **               |              |                |
   38590 **               |              V                |
   38591 **               +<------WRITER_FINISHED-------->+
   38592 **
   38593 **
   38594 ** List of state transitions and the C [function] that performs each:
   38595 **
   38596 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   38597 **   READER            -> OPEN                [pager_unlock]
   38598 **
   38599 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   38600 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   38601 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   38602 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   38603 **   WRITER_***        -> READER              [pager_end_transaction]
   38604 **
   38605 **   WRITER_***        -> ERROR               [pager_error]
   38606 **   ERROR             -> OPEN                [pager_unlock]
   38607 **
   38608 **
   38609 **  OPEN:
   38610 **
   38611 **    The pager starts up in this state. Nothing is guaranteed in this
   38612 **    state - the file may or may not be locked and the database size is
   38613 **    unknown. The database may not be read or written.
   38614 **
   38615 **    * No read or write transaction is active.
   38616 **    * Any lock, or no lock at all, may be held on the database file.
   38617 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   38618 **
   38619 **  READER:
   38620 **
   38621 **    In this state all the requirements for reading the database in
   38622 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   38623 **    was) in exclusive-locking mode, a user-level read transaction is
   38624 **    open. The database size is known in this state.
   38625 **
   38626 **    A connection running with locking_mode=normal enters this state when
   38627 **    it opens a read-transaction on the database and returns to state
   38628 **    OPEN after the read-transaction is completed. However a connection
   38629 **    running in locking_mode=exclusive (including temp databases) remains in
   38630 **    this state even after the read-transaction is closed. The only way
   38631 **    a locking_mode=exclusive connection can transition from READER to OPEN
   38632 **    is via the ERROR state (see below).
   38633 **
   38634 **    * A read transaction may be active (but a write-transaction cannot).
   38635 **    * A SHARED or greater lock is held on the database file.
   38636 **    * The dbSize variable may be trusted (even if a user-level read
   38637 **      transaction is not active). The dbOrigSize and dbFileSize variables
   38638 **      may not be trusted at this point.
   38639 **    * If the database is a WAL database, then the WAL connection is open.
   38640 **    * Even if a read-transaction is not open, it is guaranteed that
   38641 **      there is no hot-journal in the file-system.
   38642 **
   38643 **  WRITER_LOCKED:
   38644 **
   38645 **    The pager moves to this state from READER when a write-transaction
   38646 **    is first opened on the database. In WRITER_LOCKED state, all locks
   38647 **    required to start a write-transaction are held, but no actual
   38648 **    modifications to the cache or database have taken place.
   38649 **
   38650 **    In rollback mode, a RESERVED or (if the transaction was opened with
   38651 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   38652 **    moving to this state, but the journal file is not written to or opened
   38653 **    to in this state. If the transaction is committed or rolled back while
   38654 **    in WRITER_LOCKED state, all that is required is to unlock the database
   38655 **    file.
   38656 **
   38657 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   38658 **    If the connection is running with locking_mode=exclusive, an attempt
   38659 **    is made to obtain an EXCLUSIVE lock on the database file.
   38660 **
   38661 **    * A write transaction is active.
   38662 **    * If the connection is open in rollback-mode, a RESERVED or greater
   38663 **      lock is held on the database file.
   38664 **    * If the connection is open in WAL-mode, a WAL write transaction
   38665 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   38666 **      called).
   38667 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   38668 **    * The contents of the pager cache have not been modified.
   38669 **    * The journal file may or may not be open.
   38670 **    * Nothing (not even the first header) has been written to the journal.
   38671 **
   38672 **  WRITER_CACHEMOD:
   38673 **
   38674 **    A pager moves from WRITER_LOCKED state to this state when a page is
   38675 **    first modified by the upper layer. In rollback mode the journal file
   38676 **    is opened (if it is not already open) and a header written to the
   38677 **    start of it. The database file on disk has not been modified.
   38678 **
   38679 **    * A write transaction is active.
   38680 **    * A RESERVED or greater lock is held on the database file.
   38681 **    * The journal file is open and the first header has been written
   38682 **      to it, but the header has not been synced to disk.
   38683 **    * The contents of the page cache have been modified.
   38684 **
   38685 **  WRITER_DBMOD:
   38686 **
   38687 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   38688 **    when it modifies the contents of the database file. WAL connections
   38689 **    never enter this state (since they do not modify the database file,
   38690 **    just the log file).
   38691 **
   38692 **    * A write transaction is active.
   38693 **    * An EXCLUSIVE or greater lock is held on the database file.
   38694 **    * The journal file is open and the first header has been written
   38695 **      and synced to disk.
   38696 **    * The contents of the page cache have been modified (and possibly
   38697 **      written to disk).
   38698 **
   38699 **  WRITER_FINISHED:
   38700 **
   38701 **    It is not possible for a WAL connection to enter this state.
   38702 **
   38703 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   38704 **    state after the entire transaction has been successfully written into the
   38705 **    database file. In this state the transaction may be committed simply
   38706 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   38707 **    not possible to modify the database further. At this point, the upper
   38708 **    layer must either commit or rollback the transaction.
   38709 **
   38710 **    * A write transaction is active.
   38711 **    * An EXCLUSIVE or greater lock is held on the database file.
   38712 **    * All writing and syncing of journal and database data has finished.
   38713 **      If no error occured, all that remains is to finalize the journal to
   38714 **      commit the transaction. If an error did occur, the caller will need
   38715 **      to rollback the transaction.
   38716 **
   38717 **  ERROR:
   38718 **
   38719 **    The ERROR state is entered when an IO or disk-full error (including
   38720 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   38721 **    difficult to be sure that the in-memory pager state (cache contents,
   38722 **    db size etc.) are consistent with the contents of the file-system.
   38723 **
   38724 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   38725 **    cannot.
   38726 **
   38727 **    For example, if an IO error occurs while performing a rollback,
   38728 **    the contents of the page-cache may be left in an inconsistent state.
   38729 **    At this point it would be dangerous to change back to READER state
   38730 **    (as usually happens after a rollback). Any subsequent readers might
   38731 **    report database corruption (due to the inconsistent cache), and if
   38732 **    they upgrade to writers, they may inadvertently corrupt the database
   38733 **    file. To avoid this hazard, the pager switches into the ERROR state
   38734 **    instead of READER following such an error.
   38735 **
   38736 **    Once it has entered the ERROR state, any attempt to use the pager
   38737 **    to read or write data returns an error. Eventually, once all
   38738 **    outstanding transactions have been abandoned, the pager is able to
   38739 **    transition back to OPEN state, discarding the contents of the
   38740 **    page-cache and any other in-memory state at the same time. Everything
   38741 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   38742 **    when a read-transaction is next opened on the pager (transitioning
   38743 **    the pager into READER state). At that point the system has recovered
   38744 **    from the error.
   38745 **
   38746 **    Specifically, the pager jumps into the ERROR state if:
   38747 **
   38748 **      1. An error occurs while attempting a rollback. This happens in
   38749 **         function sqlite3PagerRollback().
   38750 **
   38751 **      2. An error occurs while attempting to finalize a journal file
   38752 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   38753 **
   38754 **      3. An error occurs while attempting to write to the journal or
   38755 **         database file in function pagerStress() in order to free up
   38756 **         memory.
   38757 **
   38758 **    In other cases, the error is returned to the b-tree layer. The b-tree
   38759 **    layer then attempts a rollback operation. If the error condition
   38760 **    persists, the pager enters the ERROR state via condition (1) above.
   38761 **
   38762 **    Condition (3) is necessary because it can be triggered by a read-only
   38763 **    statement executed within a transaction. In this case, if the error
   38764 **    code were simply returned to the user, the b-tree layer would not
   38765 **    automatically attempt a rollback, as it assumes that an error in a
   38766 **    read-only statement cannot leave the pager in an internally inconsistent
   38767 **    state.
   38768 **
   38769 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   38770 **    * There are one or more outstanding references to pages (after the
   38771 **      last reference is dropped the pager should move back to OPEN state).
   38772 **    * The pager is not an in-memory pager.
   38773 **
   38774 **
   38775 ** Notes:
   38776 **
   38777 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   38778 **     connection is open in WAL mode. A WAL connection is always in one
   38779 **     of the first four states.
   38780 **
   38781 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   38782 **     state. There are two exceptions: immediately after exclusive-mode has
   38783 **     been turned on (and before any read or write transactions are
   38784 **     executed), and when the pager is leaving the "error state".
   38785 **
   38786 **   * See also: assert_pager_state().
   38787 */
   38788 #define PAGER_OPEN                  0
   38789 #define PAGER_READER                1
   38790 #define PAGER_WRITER_LOCKED         2
   38791 #define PAGER_WRITER_CACHEMOD       3
   38792 #define PAGER_WRITER_DBMOD          4
   38793 #define PAGER_WRITER_FINISHED       5
   38794 #define PAGER_ERROR                 6
   38795 
   38796 /*
   38797 ** The Pager.eLock variable is almost always set to one of the
   38798 ** following locking-states, according to the lock currently held on
   38799 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   38800 ** This variable is kept up to date as locks are taken and released by
   38801 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   38802 **
   38803 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   38804 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   38805 ** the operation was successful. In these circumstances pagerLockDb() and
   38806 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   38807 ** when unlocking the file, and only updated when locking the file if the
   38808 ** VFS call is successful. This way, the Pager.eLock variable may be set
   38809 ** to a less exclusive (lower) value than the lock that is actually held
   38810 ** at the system level, but it is never set to a more exclusive value.
   38811 **
   38812 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   38813 ** be a few redundant xLock() calls or a lock may be held for longer than
   38814 ** required, but nothing really goes wrong.
   38815 **
   38816 ** The exception is when the database file is unlocked as the pager moves
   38817 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   38818 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
   38819 ** transition, by the same pager or any other). If the call to xUnlock()
   38820 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   38821 ** can confuse the call to xCheckReservedLock() call made later as part
   38822 ** of hot-journal detection.
   38823 **
   38824 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   38825 ** lock held by this process or any others". So xCheckReservedLock may
   38826 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   38827 ** doesn't know it because of a previous error in xUnlock). If this happens
   38828 ** a hot-journal may be mistaken for a journal being created by an active
   38829 ** transaction in another process, causing SQLite to read from the database
   38830 ** without rolling it back.
   38831 **
   38832 ** To work around this, if a call to xUnlock() fails when unlocking the
   38833 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   38834 ** is only changed back to a real locking state after a successful call
   38835 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   38836 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   38837 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   38838 ** lock on the database file before attempting to roll it back. See function
   38839 ** PagerSharedLock() for more detail.
   38840 **
   38841 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   38842 ** PAGER_OPEN state.
   38843 */
   38844 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   38845 
   38846 /*
   38847 ** A macro used for invoking the codec if there is one
   38848 */
   38849 #ifdef SQLITE_HAS_CODEC
   38850 # define CODEC1(P,D,N,X,E) \
   38851     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   38852 # define CODEC2(P,D,N,X,E,O) \
   38853     if( P->xCodec==0 ){ O=(char*)D; }else \
   38854     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   38855 #else
   38856 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   38857 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   38858 #endif
   38859 
   38860 /*
   38861 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   38862 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   38863 ** This could conceivably cause corruption following a power failure on
   38864 ** such a system. This is currently an undocumented limit.
   38865 */
   38866 #define MAX_SECTOR_SIZE 0x10000
   38867 
   38868 /*
   38869 ** An instance of the following structure is allocated for each active
   38870 ** savepoint and statement transaction in the system. All such structures
   38871 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   38872 ** resized using sqlite3Realloc().
   38873 **
   38874 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   38875 ** set to 0. If a journal-header is written into the main journal while
   38876 ** the savepoint is active, then iHdrOffset is set to the byte offset
   38877 ** immediately following the last journal record written into the main
   38878 ** journal before the journal-header. This is required during savepoint
   38879 ** rollback (see pagerPlaybackSavepoint()).
   38880 */
   38881 typedef struct PagerSavepoint PagerSavepoint;
   38882 struct PagerSavepoint {
   38883   i64 iOffset;                 /* Starting offset in main journal */
   38884   i64 iHdrOffset;              /* See above */
   38885   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   38886   Pgno nOrig;                  /* Original number of pages in file */
   38887   Pgno iSubRec;                /* Index of first record in sub-journal */
   38888 #ifndef SQLITE_OMIT_WAL
   38889   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   38890 #endif
   38891 };
   38892 
   38893 /*
   38894 ** A open page cache is an instance of struct Pager. A description of
   38895 ** some of the more important member variables follows:
   38896 **
   38897 ** eState
   38898 **
   38899 **   The current 'state' of the pager object. See the comment and state
   38900 **   diagram above for a description of the pager state.
   38901 **
   38902 ** eLock
   38903 **
   38904 **   For a real on-disk database, the current lock held on the database file -
   38905 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   38906 **
   38907 **   For a temporary or in-memory database (neither of which require any
   38908 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   38909 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   38910 **   logic into thinking that it already has all the locks it will ever
   38911 **   need (and no reason to release them).
   38912 **
   38913 **   In some (obscure) circumstances, this variable may also be set to
   38914 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   38915 **   details.
   38916 **
   38917 ** changeCountDone
   38918 **
   38919 **   This boolean variable is used to make sure that the change-counter
   38920 **   (the 4-byte header field at byte offset 24 of the database file) is
   38921 **   not updated more often than necessary.
   38922 **
   38923 **   It is set to true when the change-counter field is updated, which
   38924 **   can only happen if an exclusive lock is held on the database file.
   38925 **   It is cleared (set to false) whenever an exclusive lock is
   38926 **   relinquished on the database file. Each time a transaction is committed,
   38927 **   The changeCountDone flag is inspected. If it is true, the work of
   38928 **   updating the change-counter is omitted for the current transaction.
   38929 **
   38930 **   This mechanism means that when running in exclusive mode, a connection
   38931 **   need only update the change-counter once, for the first transaction
   38932 **   committed.
   38933 **
   38934 ** setMaster
   38935 **
   38936 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   38937 **   (or may not) specify a master-journal name to be written into the
   38938 **   journal file before it is synced to disk.
   38939 **
   38940 **   Whether or not a journal file contains a master-journal pointer affects
   38941 **   the way in which the journal file is finalized after the transaction is
   38942 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   38943 **   If a journal file does not contain a master-journal pointer, it is
   38944 **   finalized by overwriting the first journal header with zeroes. If
   38945 **   it does contain a master-journal pointer the journal file is finalized
   38946 **   by truncating it to zero bytes, just as if the connection were
   38947 **   running in "journal_mode=truncate" mode.
   38948 **
   38949 **   Journal files that contain master journal pointers cannot be finalized
   38950 **   simply by overwriting the first journal-header with zeroes, as the
   38951 **   master journal pointer could interfere with hot-journal rollback of any
   38952 **   subsequently interrupted transaction that reuses the journal file.
   38953 **
   38954 **   The flag is cleared as soon as the journal file is finalized (either
   38955 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   38956 **   journal file from being successfully finalized, the setMaster flag
   38957 **   is cleared anyway (and the pager will move to ERROR state).
   38958 **
   38959 ** doNotSpill, doNotSyncSpill
   38960 **
   38961 **   These two boolean variables control the behaviour of cache-spills
   38962 **   (calls made by the pcache module to the pagerStress() routine to
   38963 **   write cached data to the file-system in order to free up memory).
   38964 **
   38965 **   When doNotSpill is non-zero, writing to the database from pagerStress()
   38966 **   is disabled altogether. This is done in a very obscure case that
   38967 **   comes up during savepoint rollback that requires the pcache module
   38968 **   to allocate a new page to prevent the journal file from being written
   38969 **   while it is being traversed by code in pager_playback().
   38970 **
   38971 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
   38972 **   is permitted, but syncing the journal file is not. This flag is set
   38973 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
   38974 **   the database page-size in order to prevent a journal sync from happening
   38975 **   in between the journalling of two pages on the same sector.
   38976 **
   38977 ** subjInMemory
   38978 **
   38979 **   This is a boolean variable. If true, then any required sub-journal
   38980 **   is opened as an in-memory journal file. If false, then in-memory
   38981 **   sub-journals are only used for in-memory pager files.
   38982 **
   38983 **   This variable is updated by the upper layer each time a new
   38984 **   write-transaction is opened.
   38985 **
   38986 ** dbSize, dbOrigSize, dbFileSize
   38987 **
   38988 **   Variable dbSize is set to the number of pages in the database file.
   38989 **   It is valid in PAGER_READER and higher states (all states except for
   38990 **   OPEN and ERROR).
   38991 **
   38992 **   dbSize is set based on the size of the database file, which may be
   38993 **   larger than the size of the database (the value stored at offset
   38994 **   28 of the database header by the btree). If the size of the file
   38995 **   is not an integer multiple of the page-size, the value stored in
   38996 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   38997 **   Except, any file that is greater than 0 bytes in size is considered
   38998 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   38999 **   to dbSize==1).
   39000 **
   39001 **   During a write-transaction, if pages with page-numbers greater than
   39002 **   dbSize are modified in the cache, dbSize is updated accordingly.
   39003 **   Similarly, if the database is truncated using PagerTruncateImage(),
   39004 **   dbSize is updated.
   39005 **
   39006 **   Variables dbOrigSize and dbFileSize are valid in states
   39007 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   39008 **   variable at the start of the transaction. It is used during rollback,
   39009 **   and to determine whether or not pages need to be journalled before
   39010 **   being modified.
   39011 **
   39012 **   Throughout a write-transaction, dbFileSize contains the size of
   39013 **   the file on disk in pages. It is set to a copy of dbSize when the
   39014 **   write-transaction is first opened, and updated when VFS calls are made
   39015 **   to write or truncate the database file on disk.
   39016 **
   39017 **   The only reason the dbFileSize variable is required is to suppress
   39018 **   unnecessary calls to xTruncate() after committing a transaction. If,
   39019 **   when a transaction is committed, the dbFileSize variable indicates
   39020 **   that the database file is larger than the database image (Pager.dbSize),
   39021 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   39022 **   to measure the database file on disk, and then truncates it if required.
   39023 **   dbFileSize is not used when rolling back a transaction. In this case
   39024 **   pager_truncate() is called unconditionally (which means there may be
   39025 **   a call to xFilesize() that is not strictly required). In either case,
   39026 **   pager_truncate() may cause the file to become smaller or larger.
   39027 **
   39028 ** dbHintSize
   39029 **
   39030 **   The dbHintSize variable is used to limit the number of calls made to
   39031 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   39032 **
   39033 **   dbHintSize is set to a copy of the dbSize variable when a
   39034 **   write-transaction is opened (at the same time as dbFileSize and
   39035 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   39036 **   dbHintSize is increased to the number of pages that correspond to the
   39037 **   size-hint passed to the method call. See pager_write_pagelist() for
   39038 **   details.
   39039 **
   39040 ** errCode
   39041 **
   39042 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   39043 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   39044 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   39045 **   sub-codes.
   39046 */
   39047 struct Pager {
   39048   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   39049   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   39050   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   39051   u8 useJournal;              /* Use a rollback journal on this file */
   39052   u8 noSync;                  /* Do not sync the journal if true */
   39053   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   39054   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
   39055   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
   39056   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   39057   u8 tempFile;                /* zFilename is a temporary file */
   39058   u8 readOnly;                /* True for a read-only database */
   39059   u8 memDb;                   /* True to inhibit all file I/O */
   39060 
   39061   /**************************************************************************
   39062   ** The following block contains those class members that change during
   39063   ** routine opertion.  Class members not in this block are either fixed
   39064   ** when the pager is first created or else only change when there is a
   39065   ** significant mode change (such as changing the page_size, locking_mode,
   39066   ** or the journal_mode).  From another view, these class members describe
   39067   ** the "state" of the pager, while other class members describe the
   39068   ** "configuration" of the pager.
   39069   */
   39070   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   39071   u8 eLock;                   /* Current lock held on database file */
   39072   u8 changeCountDone;         /* Set after incrementing the change-counter */
   39073   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   39074   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   39075   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
   39076   u8 subjInMemory;            /* True to use in-memory sub-journals */
   39077   Pgno dbSize;                /* Number of pages in the database */
   39078   Pgno dbOrigSize;            /* dbSize before the current transaction */
   39079   Pgno dbFileSize;            /* Number of pages in the database file */
   39080   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   39081   int errCode;                /* One of several kinds of errors */
   39082   int nRec;                   /* Pages journalled since last j-header written */
   39083   u32 cksumInit;              /* Quasi-random value added to every checksum */
   39084   u32 nSubRec;                /* Number of records written to sub-journal */
   39085   Bitvec *pInJournal;         /* One bit for each page in the database file */
   39086   sqlite3_file *fd;           /* File descriptor for database */
   39087   sqlite3_file *jfd;          /* File descriptor for main journal */
   39088   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   39089   i64 journalOff;             /* Current write offset in the journal file */
   39090   i64 journalHdr;             /* Byte offset to previous journal header */
   39091   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   39092   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   39093   int nSavepoint;             /* Number of elements in aSavepoint[] */
   39094   char dbFileVers[16];        /* Changes whenever database file changes */
   39095   /*
   39096   ** End of the routinely-changing class members
   39097   ***************************************************************************/
   39098 
   39099   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   39100   i16 nReserve;               /* Number of unused bytes at end of each page */
   39101   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   39102   u32 sectorSize;             /* Assumed sector size during rollback */
   39103   int pageSize;               /* Number of bytes in a page */
   39104   Pgno mxPgno;                /* Maximum allowed size of the database */
   39105   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   39106   char *zFilename;            /* Name of the database file */
   39107   char *zJournal;             /* Name of the journal file */
   39108   int (*xBusyHandler)(void*); /* Function to call when busy */
   39109   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   39110   int nHit, nMiss;            /* Total cache hits and misses */
   39111 #ifdef SQLITE_TEST
   39112   int nRead, nWrite;          /* Database pages read/written */
   39113 #endif
   39114   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   39115 #ifdef SQLITE_HAS_CODEC
   39116   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   39117   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   39118   void (*xCodecFree)(void*);             /* Destructor for the codec */
   39119   void *pCodec;               /* First argument to xCodec... methods */
   39120 #endif
   39121   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   39122   PCache *pPCache;            /* Pointer to page cache object */
   39123 #ifndef SQLITE_OMIT_WAL
   39124   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   39125   char *zWal;                 /* File name for write-ahead log */
   39126 #endif
   39127 };
   39128 
   39129 /*
   39130 ** The following global variables hold counters used for
   39131 ** testing purposes only.  These variables do not exist in
   39132 ** a non-testing build.  These variables are not thread-safe.
   39133 */
   39134 #ifdef SQLITE_TEST
   39135 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   39136 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   39137 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   39138 # define PAGER_INCR(v)  v++
   39139 #else
   39140 # define PAGER_INCR(v)
   39141 #endif
   39142 
   39143 
   39144 
   39145 /*
   39146 ** Journal files begin with the following magic string.  The data
   39147 ** was obtained from /dev/random.  It is used only as a sanity check.
   39148 **
   39149 ** Since version 2.8.0, the journal format contains additional sanity
   39150 ** checking information.  If the power fails while the journal is being
   39151 ** written, semi-random garbage data might appear in the journal
   39152 ** file after power is restored.  If an attempt is then made
   39153 ** to roll the journal back, the database could be corrupted.  The additional
   39154 ** sanity checking data is an attempt to discover the garbage in the
   39155 ** journal and ignore it.
   39156 **
   39157 ** The sanity checking information for the new journal format consists
   39158 ** of a 32-bit checksum on each page of data.  The checksum covers both
   39159 ** the page number and the pPager->pageSize bytes of data for the page.
   39160 ** This cksum is initialized to a 32-bit random value that appears in the
   39161 ** journal file right after the header.  The random initializer is important,
   39162 ** because garbage data that appears at the end of a journal is likely
   39163 ** data that was once in other files that have now been deleted.  If the
   39164 ** garbage data came from an obsolete journal file, the checksums might
   39165 ** be correct.  But by initializing the checksum to random value which
   39166 ** is different for every journal, we minimize that risk.
   39167 */
   39168 static const unsigned char aJournalMagic[] = {
   39169   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   39170 };
   39171 
   39172 /*
   39173 ** The size of the of each page record in the journal is given by
   39174 ** the following macro.
   39175 */
   39176 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   39177 
   39178 /*
   39179 ** The journal header size for this pager. This is usually the same
   39180 ** size as a single disk sector. See also setSectorSize().
   39181 */
   39182 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   39183 
   39184 /*
   39185 ** The macro MEMDB is true if we are dealing with an in-memory database.
   39186 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   39187 ** the value of MEMDB will be a constant and the compiler will optimize
   39188 ** out code that would never execute.
   39189 */
   39190 #ifdef SQLITE_OMIT_MEMORYDB
   39191 # define MEMDB 0
   39192 #else
   39193 # define MEMDB pPager->memDb
   39194 #endif
   39195 
   39196 /*
   39197 ** The maximum legal page number is (2^31 - 1).
   39198 */
   39199 #define PAGER_MAX_PGNO 2147483647
   39200 
   39201 /*
   39202 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   39203 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   39204 **
   39205 ** This is so that expressions can be written as:
   39206 **
   39207 **   if( isOpen(pPager->jfd) ){ ...
   39208 **
   39209 ** instead of
   39210 **
   39211 **   if( pPager->jfd->pMethods ){ ...
   39212 */
   39213 #define isOpen(pFd) ((pFd)->pMethods)
   39214 
   39215 /*
   39216 ** Return true if this pager uses a write-ahead log instead of the usual
   39217 ** rollback journal. Otherwise false.
   39218 */
   39219 #ifndef SQLITE_OMIT_WAL
   39220 static int pagerUseWal(Pager *pPager){
   39221   return (pPager->pWal!=0);
   39222 }
   39223 #else
   39224 # define pagerUseWal(x) 0
   39225 # define pagerRollbackWal(x) 0
   39226 # define pagerWalFrames(v,w,x,y) 0
   39227 # define pagerOpenWalIfPresent(z) SQLITE_OK
   39228 # define pagerBeginReadTransaction(z) SQLITE_OK
   39229 #endif
   39230 
   39231 #ifndef NDEBUG
   39232 /*
   39233 ** Usage:
   39234 **
   39235 **   assert( assert_pager_state(pPager) );
   39236 **
   39237 ** This function runs many asserts to try to find inconsistencies in
   39238 ** the internal state of the Pager object.
   39239 */
   39240 static int assert_pager_state(Pager *p){
   39241   Pager *pPager = p;
   39242 
   39243   /* State must be valid. */
   39244   assert( p->eState==PAGER_OPEN
   39245        || p->eState==PAGER_READER
   39246        || p->eState==PAGER_WRITER_LOCKED
   39247        || p->eState==PAGER_WRITER_CACHEMOD
   39248        || p->eState==PAGER_WRITER_DBMOD
   39249        || p->eState==PAGER_WRITER_FINISHED
   39250        || p->eState==PAGER_ERROR
   39251   );
   39252 
   39253   /* Regardless of the current state, a temp-file connection always behaves
   39254   ** as if it has an exclusive lock on the database file. It never updates
   39255   ** the change-counter field, so the changeCountDone flag is always set.
   39256   */
   39257   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   39258   assert( p->tempFile==0 || pPager->changeCountDone );
   39259 
   39260   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   39261   ** And if the journal-mode is "OFF", the journal file must not be open.
   39262   */
   39263   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   39264   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   39265 
   39266   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   39267   ** this means an in-memory pager performs no IO at all, it cannot encounter
   39268   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   39269   ** a journal file. (although the in-memory journal implementation may
   39270   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   39271   ** is therefore not possible for an in-memory pager to enter the ERROR
   39272   ** state.
   39273   */
   39274   if( MEMDB ){
   39275     assert( p->noSync );
   39276     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   39277          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   39278     );
   39279     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   39280     assert( pagerUseWal(p)==0 );
   39281   }
   39282 
   39283   /* If changeCountDone is set, a RESERVED lock or greater must be held
   39284   ** on the file.
   39285   */
   39286   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   39287   assert( p->eLock!=PENDING_LOCK );
   39288 
   39289   switch( p->eState ){
   39290     case PAGER_OPEN:
   39291       assert( !MEMDB );
   39292       assert( pPager->errCode==SQLITE_OK );
   39293       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   39294       break;
   39295 
   39296     case PAGER_READER:
   39297       assert( pPager->errCode==SQLITE_OK );
   39298       assert( p->eLock!=UNKNOWN_LOCK );
   39299       assert( p->eLock>=SHARED_LOCK );
   39300       break;
   39301 
   39302     case PAGER_WRITER_LOCKED:
   39303       assert( p->eLock!=UNKNOWN_LOCK );
   39304       assert( pPager->errCode==SQLITE_OK );
   39305       if( !pagerUseWal(pPager) ){
   39306         assert( p->eLock>=RESERVED_LOCK );
   39307       }
   39308       assert( pPager->dbSize==pPager->dbOrigSize );
   39309       assert( pPager->dbOrigSize==pPager->dbFileSize );
   39310       assert( pPager->dbOrigSize==pPager->dbHintSize );
   39311       assert( pPager->setMaster==0 );
   39312       break;
   39313 
   39314     case PAGER_WRITER_CACHEMOD:
   39315       assert( p->eLock!=UNKNOWN_LOCK );
   39316       assert( pPager->errCode==SQLITE_OK );
   39317       if( !pagerUseWal(pPager) ){
   39318         /* It is possible that if journal_mode=wal here that neither the
   39319         ** journal file nor the WAL file are open. This happens during
   39320         ** a rollback transaction that switches from journal_mode=off
   39321         ** to journal_mode=wal.
   39322         */
   39323         assert( p->eLock>=RESERVED_LOCK );
   39324         assert( isOpen(p->jfd)
   39325              || p->journalMode==PAGER_JOURNALMODE_OFF
   39326              || p->journalMode==PAGER_JOURNALMODE_WAL
   39327         );
   39328       }
   39329       assert( pPager->dbOrigSize==pPager->dbFileSize );
   39330       assert( pPager->dbOrigSize==pPager->dbHintSize );
   39331       break;
   39332 
   39333     case PAGER_WRITER_DBMOD:
   39334       assert( p->eLock==EXCLUSIVE_LOCK );
   39335       assert( pPager->errCode==SQLITE_OK );
   39336       assert( !pagerUseWal(pPager) );
   39337       assert( p->eLock>=EXCLUSIVE_LOCK );
   39338       assert( isOpen(p->jfd)
   39339            || p->journalMode==PAGER_JOURNALMODE_OFF
   39340            || p->journalMode==PAGER_JOURNALMODE_WAL
   39341       );
   39342       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   39343       break;
   39344 
   39345     case PAGER_WRITER_FINISHED:
   39346       assert( p->eLock==EXCLUSIVE_LOCK );
   39347       assert( pPager->errCode==SQLITE_OK );
   39348       assert( !pagerUseWal(pPager) );
   39349       assert( isOpen(p->jfd)
   39350            || p->journalMode==PAGER_JOURNALMODE_OFF
   39351            || p->journalMode==PAGER_JOURNALMODE_WAL
   39352       );
   39353       break;
   39354 
   39355     case PAGER_ERROR:
   39356       /* There must be at least one outstanding reference to the pager if
   39357       ** in ERROR state. Otherwise the pager should have already dropped
   39358       ** back to OPEN state.
   39359       */
   39360       assert( pPager->errCode!=SQLITE_OK );
   39361       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   39362       break;
   39363   }
   39364 
   39365   return 1;
   39366 }
   39367 #endif /* ifndef NDEBUG */
   39368 
   39369 #ifdef SQLITE_DEBUG
   39370 /*
   39371 ** Return a pointer to a human readable string in a static buffer
   39372 ** containing the state of the Pager object passed as an argument. This
   39373 ** is intended to be used within debuggers. For example, as an alternative
   39374 ** to "print *pPager" in gdb:
   39375 **
   39376 ** (gdb) printf "%s", print_pager_state(pPager)
   39377 */
   39378 static char *print_pager_state(Pager *p){
   39379   static char zRet[1024];
   39380 
   39381   sqlite3_snprintf(1024, zRet,
   39382       "Filename:      %s\n"
   39383       "State:         %s errCode=%d\n"
   39384       "Lock:          %s\n"
   39385       "Locking mode:  locking_mode=%s\n"
   39386       "Journal mode:  journal_mode=%s\n"
   39387       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   39388       "Journal:       journalOff=%lld journalHdr=%lld\n"
   39389       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   39390       , p->zFilename
   39391       , p->eState==PAGER_OPEN            ? "OPEN" :
   39392         p->eState==PAGER_READER          ? "READER" :
   39393         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   39394         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   39395         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   39396         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   39397         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   39398       , (int)p->errCode
   39399       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   39400         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   39401         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   39402         p->eLock==SHARED_LOCK     ? "SHARED" :
   39403         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   39404       , p->exclusiveMode ? "exclusive" : "normal"
   39405       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   39406         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   39407         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   39408         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   39409         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   39410         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   39411       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   39412       , p->journalOff, p->journalHdr
   39413       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   39414   );
   39415 
   39416   return zRet;
   39417 }
   39418 #endif
   39419 
   39420 /*
   39421 ** Return true if it is necessary to write page *pPg into the sub-journal.
   39422 ** A page needs to be written into the sub-journal if there exists one
   39423 ** or more open savepoints for which:
   39424 **
   39425 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   39426 **   * The bit corresponding to the page-number is not set in
   39427 **     PagerSavepoint.pInSavepoint.
   39428 */
   39429 static int subjRequiresPage(PgHdr *pPg){
   39430   Pgno pgno = pPg->pgno;
   39431   Pager *pPager = pPg->pPager;
   39432   int i;
   39433   for(i=0; i<pPager->nSavepoint; i++){
   39434     PagerSavepoint *p = &pPager->aSavepoint[i];
   39435     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   39436       return 1;
   39437     }
   39438   }
   39439   return 0;
   39440 }
   39441 
   39442 /*
   39443 ** Return true if the page is already in the journal file.
   39444 */
   39445 static int pageInJournal(PgHdr *pPg){
   39446   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
   39447 }
   39448 
   39449 /*
   39450 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   39451 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   39452 ** error code is something goes wrong.
   39453 **
   39454 ** All values are stored on disk as big-endian.
   39455 */
   39456 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   39457   unsigned char ac[4];
   39458   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   39459   if( rc==SQLITE_OK ){
   39460     *pRes = sqlite3Get4byte(ac);
   39461   }
   39462   return rc;
   39463 }
   39464 
   39465 /*
   39466 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   39467 */
   39468 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   39469 
   39470 
   39471 /*
   39472 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   39473 ** on success or an error code is something goes wrong.
   39474 */
   39475 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   39476   char ac[4];
   39477   put32bits(ac, val);
   39478   return sqlite3OsWrite(fd, ac, 4, offset);
   39479 }
   39480 
   39481 /*
   39482 ** Unlock the database file to level eLock, which must be either NO_LOCK
   39483 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   39484 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   39485 **
   39486 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   39487 ** called, do not modify it. See the comment above the #define of
   39488 ** UNKNOWN_LOCK for an explanation of this.
   39489 */
   39490 static int pagerUnlockDb(Pager *pPager, int eLock){
   39491   int rc = SQLITE_OK;
   39492 
   39493   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   39494   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   39495   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   39496   if( isOpen(pPager->fd) ){
   39497     assert( pPager->eLock>=eLock );
   39498     rc = sqlite3OsUnlock(pPager->fd, eLock);
   39499     if( pPager->eLock!=UNKNOWN_LOCK ){
   39500       pPager->eLock = (u8)eLock;
   39501     }
   39502     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   39503   }
   39504   return rc;
   39505 }
   39506 
   39507 /*
   39508 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   39509 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   39510 ** Pager.eLock variable to the new locking state.
   39511 **
   39512 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   39513 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   39514 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   39515 ** of this.
   39516 */
   39517 static int pagerLockDb(Pager *pPager, int eLock){
   39518   int rc = SQLITE_OK;
   39519 
   39520   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   39521   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   39522     rc = sqlite3OsLock(pPager->fd, eLock);
   39523     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   39524       pPager->eLock = (u8)eLock;
   39525       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   39526     }
   39527   }
   39528   return rc;
   39529 }
   39530 
   39531 /*
   39532 ** This function determines whether or not the atomic-write optimization
   39533 ** can be used with this pager. The optimization can be used if:
   39534 **
   39535 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   39536 **      a database page may be written atomically, and
   39537 **  (b) the value returned by OsSectorSize() is less than or equal
   39538 **      to the page size.
   39539 **
   39540 ** The optimization is also always enabled for temporary files. It is
   39541 ** an error to call this function if pPager is opened on an in-memory
   39542 ** database.
   39543 **
   39544 ** If the optimization cannot be used, 0 is returned. If it can be used,
   39545 ** then the value returned is the size of the journal file when it
   39546 ** contains rollback data for exactly one page.
   39547 */
   39548 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   39549 static int jrnlBufferSize(Pager *pPager){
   39550   assert( !MEMDB );
   39551   if( !pPager->tempFile ){
   39552     int dc;                           /* Device characteristics */
   39553     int nSector;                      /* Sector size */
   39554     int szPage;                       /* Page size */
   39555 
   39556     assert( isOpen(pPager->fd) );
   39557     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   39558     nSector = pPager->sectorSize;
   39559     szPage = pPager->pageSize;
   39560 
   39561     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   39562     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   39563     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   39564       return 0;
   39565     }
   39566   }
   39567 
   39568   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   39569 }
   39570 #endif
   39571 
   39572 /*
   39573 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   39574 ** on the cache using a hash function.  This is used for testing
   39575 ** and debugging only.
   39576 */
   39577 #ifdef SQLITE_CHECK_PAGES
   39578 /*
   39579 ** Return a 32-bit hash of the page data for pPage.
   39580 */
   39581 static u32 pager_datahash(int nByte, unsigned char *pData){
   39582   u32 hash = 0;
   39583   int i;
   39584   for(i=0; i<nByte; i++){
   39585     hash = (hash*1039) + pData[i];
   39586   }
   39587   return hash;
   39588 }
   39589 static u32 pager_pagehash(PgHdr *pPage){
   39590   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   39591 }
   39592 static void pager_set_pagehash(PgHdr *pPage){
   39593   pPage->pageHash = pager_pagehash(pPage);
   39594 }
   39595 
   39596 /*
   39597 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   39598 ** is defined, and NDEBUG is not defined, an assert() statement checks
   39599 ** that the page is either dirty or still matches the calculated page-hash.
   39600 */
   39601 #define CHECK_PAGE(x) checkPage(x)
   39602 static void checkPage(PgHdr *pPg){
   39603   Pager *pPager = pPg->pPager;
   39604   assert( pPager->eState!=PAGER_ERROR );
   39605   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   39606 }
   39607 
   39608 #else
   39609 #define pager_datahash(X,Y)  0
   39610 #define pager_pagehash(X)  0
   39611 #define pager_set_pagehash(X)
   39612 #define CHECK_PAGE(x)
   39613 #endif  /* SQLITE_CHECK_PAGES */
   39614 
   39615 /*
   39616 ** When this is called the journal file for pager pPager must be open.
   39617 ** This function attempts to read a master journal file name from the
   39618 ** end of the file and, if successful, copies it into memory supplied
   39619 ** by the caller. See comments above writeMasterJournal() for the format
   39620 ** used to store a master journal file name at the end of a journal file.
   39621 **
   39622 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   39623 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   39624 ** enough space to write the master journal name). If the master journal
   39625 ** name in the journal is longer than nMaster bytes (including a
   39626 ** nul-terminator), then this is handled as if no master journal name
   39627 ** were present in the journal.
   39628 **
   39629 ** If a master journal file name is present at the end of the journal
   39630 ** file, then it is copied into the buffer pointed to by zMaster. A
   39631 ** nul-terminator byte is appended to the buffer following the master
   39632 ** journal file name.
   39633 **
   39634 ** If it is determined that no master journal file name is present
   39635 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   39636 **
   39637 ** If an error occurs while reading from the journal file, an SQLite
   39638 ** error code is returned.
   39639 */
   39640 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   39641   int rc;                    /* Return code */
   39642   u32 len;                   /* Length in bytes of master journal name */
   39643   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   39644   u32 cksum;                 /* MJ checksum value read from journal */
   39645   u32 u;                     /* Unsigned loop counter */
   39646   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   39647   zMaster[0] = '\0';
   39648 
   39649   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   39650    || szJ<16
   39651    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   39652    || len>=nMaster
   39653    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   39654    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   39655    || memcmp(aMagic, aJournalMagic, 8)
   39656    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   39657   ){
   39658     return rc;
   39659   }
   39660 
   39661   /* See if the checksum matches the master journal name */
   39662   for(u=0; u<len; u++){
   39663     cksum -= zMaster[u];
   39664   }
   39665   if( cksum ){
   39666     /* If the checksum doesn't add up, then one or more of the disk sectors
   39667     ** containing the master journal filename is corrupted. This means
   39668     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   39669     ** master-journal filename.
   39670     */
   39671     len = 0;
   39672   }
   39673   zMaster[len] = '\0';
   39674 
   39675   return SQLITE_OK;
   39676 }
   39677 
   39678 /*
   39679 ** Return the offset of the sector boundary at or immediately
   39680 ** following the value in pPager->journalOff, assuming a sector
   39681 ** size of pPager->sectorSize bytes.
   39682 **
   39683 ** i.e for a sector size of 512:
   39684 **
   39685 **   Pager.journalOff          Return value
   39686 **   ---------------------------------------
   39687 **   0                         0
   39688 **   512                       512
   39689 **   100                       512
   39690 **   2000                      2048
   39691 **
   39692 */
   39693 static i64 journalHdrOffset(Pager *pPager){
   39694   i64 offset = 0;
   39695   i64 c = pPager->journalOff;
   39696   if( c ){
   39697     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   39698   }
   39699   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   39700   assert( offset>=c );
   39701   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   39702   return offset;
   39703 }
   39704 
   39705 /*
   39706 ** The journal file must be open when this function is called.
   39707 **
   39708 ** This function is a no-op if the journal file has not been written to
   39709 ** within the current transaction (i.e. if Pager.journalOff==0).
   39710 **
   39711 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   39712 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   39713 ** zero the 28-byte header at the start of the journal file. In either case,
   39714 ** if the pager is not in no-sync mode, sync the journal file immediately
   39715 ** after writing or truncating it.
   39716 **
   39717 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   39718 ** following the truncation or zeroing described above the size of the
   39719 ** journal file in bytes is larger than this value, then truncate the
   39720 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   39721 ** not need to be synced following this operation.
   39722 **
   39723 ** If an IO error occurs, abandon processing and return the IO error code.
   39724 ** Otherwise, return SQLITE_OK.
   39725 */
   39726 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   39727   int rc = SQLITE_OK;                               /* Return code */
   39728   assert( isOpen(pPager->jfd) );
   39729   if( pPager->journalOff ){
   39730     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   39731 
   39732     IOTRACE(("JZEROHDR %p\n", pPager))
   39733     if( doTruncate || iLimit==0 ){
   39734       rc = sqlite3OsTruncate(pPager->jfd, 0);
   39735     }else{
   39736       static const char zeroHdr[28] = {0};
   39737       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   39738     }
   39739     if( rc==SQLITE_OK && !pPager->noSync ){
   39740       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   39741     }
   39742 
   39743     /* At this point the transaction is committed but the write lock
   39744     ** is still held on the file. If there is a size limit configured for
   39745     ** the persistent journal and the journal file currently consumes more
   39746     ** space than that limit allows for, truncate it now. There is no need
   39747     ** to sync the file following this operation.
   39748     */
   39749     if( rc==SQLITE_OK && iLimit>0 ){
   39750       i64 sz;
   39751       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   39752       if( rc==SQLITE_OK && sz>iLimit ){
   39753         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   39754       }
   39755     }
   39756   }
   39757   return rc;
   39758 }
   39759 
   39760 /*
   39761 ** The journal file must be open when this routine is called. A journal
   39762 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   39763 ** current location.
   39764 **
   39765 ** The format for the journal header is as follows:
   39766 ** - 8 bytes: Magic identifying journal format.
   39767 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   39768 ** - 4 bytes: Random number used for page hash.
   39769 ** - 4 bytes: Initial database page count.
   39770 ** - 4 bytes: Sector size used by the process that wrote this journal.
   39771 ** - 4 bytes: Database page size.
   39772 **
   39773 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   39774 */
   39775 static int writeJournalHdr(Pager *pPager){
   39776   int rc = SQLITE_OK;                 /* Return code */
   39777   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   39778   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   39779   u32 nWrite;                         /* Bytes of header sector written */
   39780   int ii;                             /* Loop counter */
   39781 
   39782   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   39783 
   39784   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   39785     nHeader = JOURNAL_HDR_SZ(pPager);
   39786   }
   39787 
   39788   /* If there are active savepoints and any of them were created
   39789   ** since the most recent journal header was written, update the
   39790   ** PagerSavepoint.iHdrOffset fields now.
   39791   */
   39792   for(ii=0; ii<pPager->nSavepoint; ii++){
   39793     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   39794       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   39795     }
   39796   }
   39797 
   39798   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   39799 
   39800   /*
   39801   ** Write the nRec Field - the number of page records that follow this
   39802   ** journal header. Normally, zero is written to this value at this time.
   39803   ** After the records are added to the journal (and the journal synced,
   39804   ** if in full-sync mode), the zero is overwritten with the true number
   39805   ** of records (see syncJournal()).
   39806   **
   39807   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   39808   ** reading the journal this value tells SQLite to assume that the
   39809   ** rest of the journal file contains valid page records. This assumption
   39810   ** is dangerous, as if a failure occurred whilst writing to the journal
   39811   ** file it may contain some garbage data. There are two scenarios
   39812   ** where this risk can be ignored:
   39813   **
   39814   **   * When the pager is in no-sync mode. Corruption can follow a
   39815   **     power failure in this case anyway.
   39816   **
   39817   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   39818   **     that garbage data is never appended to the journal file.
   39819   */
   39820   assert( isOpen(pPager->fd) || pPager->noSync );
   39821   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   39822    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   39823   ){
   39824     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   39825     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   39826   }else{
   39827     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   39828   }
   39829 
   39830   /* The random check-hash initialiser */
   39831   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   39832   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   39833   /* The initial database size */
   39834   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   39835   /* The assumed sector size for this process */
   39836   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   39837 
   39838   /* The page size */
   39839   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   39840 
   39841   /* Initializing the tail of the buffer is not necessary.  Everything
   39842   ** works find if the following memset() is omitted.  But initializing
   39843   ** the memory prevents valgrind from complaining, so we are willing to
   39844   ** take the performance hit.
   39845   */
   39846   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   39847          nHeader-(sizeof(aJournalMagic)+20));
   39848 
   39849   /* In theory, it is only necessary to write the 28 bytes that the
   39850   ** journal header consumes to the journal file here. Then increment the
   39851   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   39852   ** record is written to the following sector (leaving a gap in the file
   39853   ** that will be implicitly filled in by the OS).
   39854   **
   39855   ** However it has been discovered that on some systems this pattern can
   39856   ** be significantly slower than contiguously writing data to the file,
   39857   ** even if that means explicitly writing data to the block of
   39858   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   39859   ** is done.
   39860   **
   39861   ** The loop is required here in case the sector-size is larger than the
   39862   ** database page size. Since the zHeader buffer is only Pager.pageSize
   39863   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   39864   ** to populate the entire journal header sector.
   39865   */
   39866   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   39867     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   39868     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   39869     assert( pPager->journalHdr <= pPager->journalOff );
   39870     pPager->journalOff += nHeader;
   39871   }
   39872 
   39873   return rc;
   39874 }
   39875 
   39876 /*
   39877 ** The journal file must be open when this is called. A journal header file
   39878 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   39879 ** file. The current location in the journal file is given by
   39880 ** pPager->journalOff. See comments above function writeJournalHdr() for
   39881 ** a description of the journal header format.
   39882 **
   39883 ** If the header is read successfully, *pNRec is set to the number of
   39884 ** page records following this header and *pDbSize is set to the size of the
   39885 ** database before the transaction began, in pages. Also, pPager->cksumInit
   39886 ** is set to the value read from the journal header. SQLITE_OK is returned
   39887 ** in this case.
   39888 **
   39889 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   39890 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   39891 ** cannot be read from the journal file an error code is returned.
   39892 */
   39893 static int readJournalHdr(
   39894   Pager *pPager,               /* Pager object */
   39895   int isHot,
   39896   i64 journalSize,             /* Size of the open journal file in bytes */
   39897   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   39898   u32 *pDbSize                 /* OUT: Value of original database size field */
   39899 ){
   39900   int rc;                      /* Return code */
   39901   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   39902   i64 iHdrOff;                 /* Offset of journal header being read */
   39903 
   39904   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   39905 
   39906   /* Advance Pager.journalOff to the start of the next sector. If the
   39907   ** journal file is too small for there to be a header stored at this
   39908   ** point, return SQLITE_DONE.
   39909   */
   39910   pPager->journalOff = journalHdrOffset(pPager);
   39911   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   39912     return SQLITE_DONE;
   39913   }
   39914   iHdrOff = pPager->journalOff;
   39915 
   39916   /* Read in the first 8 bytes of the journal header. If they do not match
   39917   ** the  magic string found at the start of each journal header, return
   39918   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   39919   ** proceed.
   39920   */
   39921   if( isHot || iHdrOff!=pPager->journalHdr ){
   39922     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   39923     if( rc ){
   39924       return rc;
   39925     }
   39926     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   39927       return SQLITE_DONE;
   39928     }
   39929   }
   39930 
   39931   /* Read the first three 32-bit fields of the journal header: The nRec
   39932   ** field, the checksum-initializer and the database size at the start
   39933   ** of the transaction. Return an error code if anything goes wrong.
   39934   */
   39935   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   39936    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   39937    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   39938   ){
   39939     return rc;
   39940   }
   39941 
   39942   if( pPager->journalOff==0 ){
   39943     u32 iPageSize;               /* Page-size field of journal header */
   39944     u32 iSectorSize;             /* Sector-size field of journal header */
   39945 
   39946     /* Read the page-size and sector-size journal header fields. */
   39947     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   39948      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   39949     ){
   39950       return rc;
   39951     }
   39952 
   39953     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   39954     ** journal header to zero. In this case, assume that the Pager.pageSize
   39955     ** variable is already set to the correct page size.
   39956     */
   39957     if( iPageSize==0 ){
   39958       iPageSize = pPager->pageSize;
   39959     }
   39960 
   39961     /* Check that the values read from the page-size and sector-size fields
   39962     ** are within range. To be 'in range', both values need to be a power
   39963     ** of two greater than or equal to 512 or 32, and not greater than their
   39964     ** respective compile time maximum limits.
   39965     */
   39966     if( iPageSize<512                  || iSectorSize<32
   39967      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   39968      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   39969     ){
   39970       /* If the either the page-size or sector-size in the journal-header is
   39971       ** invalid, then the process that wrote the journal-header must have
   39972       ** crashed before the header was synced. In this case stop reading
   39973       ** the journal file here.
   39974       */
   39975       return SQLITE_DONE;
   39976     }
   39977 
   39978     /* Update the page-size to match the value read from the journal.
   39979     ** Use a testcase() macro to make sure that malloc failure within
   39980     ** PagerSetPagesize() is tested.
   39981     */
   39982     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   39983     testcase( rc!=SQLITE_OK );
   39984 
   39985     /* Update the assumed sector-size to match the value used by
   39986     ** the process that created this journal. If this journal was
   39987     ** created by a process other than this one, then this routine
   39988     ** is being called from within pager_playback(). The local value
   39989     ** of Pager.sectorSize is restored at the end of that routine.
   39990     */
   39991     pPager->sectorSize = iSectorSize;
   39992   }
   39993 
   39994   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   39995   return rc;
   39996 }
   39997 
   39998 
   39999 /*
   40000 ** Write the supplied master journal name into the journal file for pager
   40001 ** pPager at the current location. The master journal name must be the last
   40002 ** thing written to a journal file. If the pager is in full-sync mode, the
   40003 ** journal file descriptor is advanced to the next sector boundary before
   40004 ** anything is written. The format is:
   40005 **
   40006 **   + 4 bytes: PAGER_MJ_PGNO.
   40007 **   + N bytes: Master journal filename in utf-8.
   40008 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   40009 **   + 4 bytes: Master journal name checksum.
   40010 **   + 8 bytes: aJournalMagic[].
   40011 **
   40012 ** The master journal page checksum is the sum of the bytes in the master
   40013 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   40014 **
   40015 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   40016 ** this call is a no-op.
   40017 */
   40018 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   40019   int rc;                          /* Return code */
   40020   int nMaster;                     /* Length of string zMaster */
   40021   i64 iHdrOff;                     /* Offset of header in journal file */
   40022   i64 jrnlSize;                    /* Size of journal file on disk */
   40023   u32 cksum = 0;                   /* Checksum of string zMaster */
   40024 
   40025   assert( pPager->setMaster==0 );
   40026   assert( !pagerUseWal(pPager) );
   40027 
   40028   if( !zMaster
   40029    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   40030    || pPager->journalMode==PAGER_JOURNALMODE_OFF
   40031   ){
   40032     return SQLITE_OK;
   40033   }
   40034   pPager->setMaster = 1;
   40035   assert( isOpen(pPager->jfd) );
   40036   assert( pPager->journalHdr <= pPager->journalOff );
   40037 
   40038   /* Calculate the length in bytes and the checksum of zMaster */
   40039   for(nMaster=0; zMaster[nMaster]; nMaster++){
   40040     cksum += zMaster[nMaster];
   40041   }
   40042 
   40043   /* If in full-sync mode, advance to the next disk sector before writing
   40044   ** the master journal name. This is in case the previous page written to
   40045   ** the journal has already been synced.
   40046   */
   40047   if( pPager->fullSync ){
   40048     pPager->journalOff = journalHdrOffset(pPager);
   40049   }
   40050   iHdrOff = pPager->journalOff;
   40051 
   40052   /* Write the master journal data to the end of the journal file. If
   40053   ** an error occurs, return the error code to the caller.
   40054   */
   40055   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   40056    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   40057    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   40058    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   40059    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   40060   ){
   40061     return rc;
   40062   }
   40063   pPager->journalOff += (nMaster+20);
   40064 
   40065   /* If the pager is in peristent-journal mode, then the physical
   40066   ** journal-file may extend past the end of the master-journal name
   40067   ** and 8 bytes of magic data just written to the file. This is
   40068   ** dangerous because the code to rollback a hot-journal file
   40069   ** will not be able to find the master-journal name to determine
   40070   ** whether or not the journal is hot.
   40071   **
   40072   ** Easiest thing to do in this scenario is to truncate the journal
   40073   ** file to the required size.
   40074   */
   40075   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   40076    && jrnlSize>pPager->journalOff
   40077   ){
   40078     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   40079   }
   40080   return rc;
   40081 }
   40082 
   40083 /*
   40084 ** Find a page in the hash table given its page number. Return
   40085 ** a pointer to the page or NULL if the requested page is not
   40086 ** already in memory.
   40087 */
   40088 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   40089   PgHdr *p;                         /* Return value */
   40090 
   40091   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   40092   ** fail, since no attempt to allocate dynamic memory will be made.
   40093   */
   40094   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   40095   return p;
   40096 }
   40097 
   40098 /*
   40099 ** Discard the entire contents of the in-memory page-cache.
   40100 */
   40101 static void pager_reset(Pager *pPager){
   40102   sqlite3BackupRestart(pPager->pBackup);
   40103   sqlite3PcacheClear(pPager->pPCache);
   40104 }
   40105 
   40106 /*
   40107 ** Free all structures in the Pager.aSavepoint[] array and set both
   40108 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   40109 ** if it is open and the pager is not in exclusive mode.
   40110 */
   40111 static void releaseAllSavepoints(Pager *pPager){
   40112   int ii;               /* Iterator for looping through Pager.aSavepoint */
   40113   for(ii=0; ii<pPager->nSavepoint; ii++){
   40114     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   40115   }
   40116   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   40117     sqlite3OsClose(pPager->sjfd);
   40118   }
   40119   sqlite3_free(pPager->aSavepoint);
   40120   pPager->aSavepoint = 0;
   40121   pPager->nSavepoint = 0;
   40122   pPager->nSubRec = 0;
   40123 }
   40124 
   40125 /*
   40126 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   40127 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   40128 ** or SQLITE_NOMEM if a malloc failure occurs.
   40129 */
   40130 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   40131   int ii;                   /* Loop counter */
   40132   int rc = SQLITE_OK;       /* Result code */
   40133 
   40134   for(ii=0; ii<pPager->nSavepoint; ii++){
   40135     PagerSavepoint *p = &pPager->aSavepoint[ii];
   40136     if( pgno<=p->nOrig ){
   40137       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   40138       testcase( rc==SQLITE_NOMEM );
   40139       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   40140     }
   40141   }
   40142   return rc;
   40143 }
   40144 
   40145 /*
   40146 ** This function is a no-op if the pager is in exclusive mode and not
   40147 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   40148 ** state.
   40149 **
   40150 ** If the pager is not in exclusive-access mode, the database file is
   40151 ** completely unlocked. If the file is unlocked and the file-system does
   40152 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   40153 ** closed (if it is open).
   40154 **
   40155 ** If the pager is in ERROR state when this function is called, the
   40156 ** contents of the pager cache are discarded before switching back to
   40157 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   40158 ** or not, any journal file left in the file-system will be treated
   40159 ** as a hot-journal and rolled back the next time a read-transaction
   40160 ** is opened (by this or by any other connection).
   40161 */
   40162 static void pager_unlock(Pager *pPager){
   40163 
   40164   assert( pPager->eState==PAGER_READER
   40165        || pPager->eState==PAGER_OPEN
   40166        || pPager->eState==PAGER_ERROR
   40167   );
   40168 
   40169   sqlite3BitvecDestroy(pPager->pInJournal);
   40170   pPager->pInJournal = 0;
   40171   releaseAllSavepoints(pPager);
   40172 
   40173   if( pagerUseWal(pPager) ){
   40174     assert( !isOpen(pPager->jfd) );
   40175     sqlite3WalEndReadTransaction(pPager->pWal);
   40176     pPager->eState = PAGER_OPEN;
   40177   }else if( !pPager->exclusiveMode ){
   40178     int rc;                       /* Error code returned by pagerUnlockDb() */
   40179     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   40180 
   40181     /* If the operating system support deletion of open files, then
   40182     ** close the journal file when dropping the database lock.  Otherwise
   40183     ** another connection with journal_mode=delete might delete the file
   40184     ** out from under us.
   40185     */
   40186     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   40187     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   40188     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   40189     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   40190     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   40191     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   40192     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   40193      || 1!=(pPager->journalMode & 5)
   40194     ){
   40195       sqlite3OsClose(pPager->jfd);
   40196     }
   40197 
   40198     /* If the pager is in the ERROR state and the call to unlock the database
   40199     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   40200     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   40201     ** is necessary.
   40202     */
   40203     rc = pagerUnlockDb(pPager, NO_LOCK);
   40204     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   40205       pPager->eLock = UNKNOWN_LOCK;
   40206     }
   40207 
   40208     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   40209     ** without clearing the error code. This is intentional - the error
   40210     ** code is cleared and the cache reset in the block below.
   40211     */
   40212     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   40213     pPager->changeCountDone = 0;
   40214     pPager->eState = PAGER_OPEN;
   40215   }
   40216 
   40217   /* If Pager.errCode is set, the contents of the pager cache cannot be
   40218   ** trusted. Now that there are no outstanding references to the pager,
   40219   ** it can safely move back to PAGER_OPEN state. This happens in both
   40220   ** normal and exclusive-locking mode.
   40221   */
   40222   if( pPager->errCode ){
   40223     assert( !MEMDB );
   40224     pager_reset(pPager);
   40225     pPager->changeCountDone = pPager->tempFile;
   40226     pPager->eState = PAGER_OPEN;
   40227     pPager->errCode = SQLITE_OK;
   40228   }
   40229 
   40230   pPager->journalOff = 0;
   40231   pPager->journalHdr = 0;
   40232   pPager->setMaster = 0;
   40233 }
   40234 
   40235 /*
   40236 ** This function is called whenever an IOERR or FULL error that requires
   40237 ** the pager to transition into the ERROR state may ahve occurred.
   40238 ** The first argument is a pointer to the pager structure, the second
   40239 ** the error-code about to be returned by a pager API function. The
   40240 ** value returned is a copy of the second argument to this function.
   40241 **
   40242 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   40243 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   40244 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   40245 ** all major API calls on the Pager will immediately return Pager.errCode.
   40246 **
   40247 ** The ERROR state indicates that the contents of the pager-cache
   40248 ** cannot be trusted. This state can be cleared by completely discarding
   40249 ** the contents of the pager-cache. If a transaction was active when
   40250 ** the persistent error occurred, then the rollback journal may need
   40251 ** to be replayed to restore the contents of the database file (as if
   40252 ** it were a hot-journal).
   40253 */
   40254 static int pager_error(Pager *pPager, int rc){
   40255   int rc2 = rc & 0xff;
   40256   assert( rc==SQLITE_OK || !MEMDB );
   40257   assert(
   40258        pPager->errCode==SQLITE_FULL ||
   40259        pPager->errCode==SQLITE_OK ||
   40260        (pPager->errCode & 0xff)==SQLITE_IOERR
   40261   );
   40262   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   40263     pPager->errCode = rc;
   40264     pPager->eState = PAGER_ERROR;
   40265   }
   40266   return rc;
   40267 }
   40268 
   40269 /*
   40270 ** This routine ends a transaction. A transaction is usually ended by
   40271 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   40272 ** after rollback of a hot-journal, or if an error occurs while opening
   40273 ** the journal file or writing the very first journal-header of a
   40274 ** database transaction.
   40275 **
   40276 ** This routine is never called in PAGER_ERROR state. If it is called
   40277 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   40278 ** exclusive than a RESERVED lock, it is a no-op.
   40279 **
   40280 ** Otherwise, any active savepoints are released.
   40281 **
   40282 ** If the journal file is open, then it is "finalized". Once a journal
   40283 ** file has been finalized it is not possible to use it to roll back a
   40284 ** transaction. Nor will it be considered to be a hot-journal by this
   40285 ** or any other database connection. Exactly how a journal is finalized
   40286 ** depends on whether or not the pager is running in exclusive mode and
   40287 ** the current journal-mode (Pager.journalMode value), as follows:
   40288 **
   40289 **   journalMode==MEMORY
   40290 **     Journal file descriptor is simply closed. This destroys an
   40291 **     in-memory journal.
   40292 **
   40293 **   journalMode==TRUNCATE
   40294 **     Journal file is truncated to zero bytes in size.
   40295 **
   40296 **   journalMode==PERSIST
   40297 **     The first 28 bytes of the journal file are zeroed. This invalidates
   40298 **     the first journal header in the file, and hence the entire journal
   40299 **     file. An invalid journal file cannot be rolled back.
   40300 **
   40301 **   journalMode==DELETE
   40302 **     The journal file is closed and deleted using sqlite3OsDelete().
   40303 **
   40304 **     If the pager is running in exclusive mode, this method of finalizing
   40305 **     the journal file is never used. Instead, if the journalMode is
   40306 **     DELETE and the pager is in exclusive mode, the method described under
   40307 **     journalMode==PERSIST is used instead.
   40308 **
   40309 ** After the journal is finalized, the pager moves to PAGER_READER state.
   40310 ** If running in non-exclusive rollback mode, the lock on the file is
   40311 ** downgraded to a SHARED_LOCK.
   40312 **
   40313 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   40314 ** any of the IO operations to finalize the journal file or unlock the
   40315 ** database then the IO error code is returned to the user. If the
   40316 ** operation to finalize the journal file fails, then the code still
   40317 ** tries to unlock the database file if not in exclusive mode. If the
   40318 ** unlock operation fails as well, then the first error code related
   40319 ** to the first error encountered (the journal finalization one) is
   40320 ** returned.
   40321 */
   40322 static int pager_end_transaction(Pager *pPager, int hasMaster){
   40323   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   40324   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   40325 
   40326   /* Do nothing if the pager does not have an open write transaction
   40327   ** or at least a RESERVED lock. This function may be called when there
   40328   ** is no write-transaction active but a RESERVED or greater lock is
   40329   ** held under two circumstances:
   40330   **
   40331   **   1. After a successful hot-journal rollback, it is called with
   40332   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   40333   **
   40334   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   40335   **      lock switches back to locking_mode=normal and then executes a
   40336   **      read-transaction, this function is called with eState==PAGER_READER
   40337   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   40338   */
   40339   assert( assert_pager_state(pPager) );
   40340   assert( pPager->eState!=PAGER_ERROR );
   40341   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   40342     return SQLITE_OK;
   40343   }
   40344 
   40345   releaseAllSavepoints(pPager);
   40346   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   40347   if( isOpen(pPager->jfd) ){
   40348     assert( !pagerUseWal(pPager) );
   40349 
   40350     /* Finalize the journal file. */
   40351     if( sqlite3IsMemJournal(pPager->jfd) ){
   40352       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   40353       sqlite3OsClose(pPager->jfd);
   40354     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   40355       if( pPager->journalOff==0 ){
   40356         rc = SQLITE_OK;
   40357       }else{
   40358         rc = sqlite3OsTruncate(pPager->jfd, 0);
   40359       }
   40360       pPager->journalOff = 0;
   40361     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   40362       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   40363     ){
   40364       rc = zeroJournalHdr(pPager, hasMaster);
   40365       pPager->journalOff = 0;
   40366     }else{
   40367       /* This branch may be executed with Pager.journalMode==MEMORY if
   40368       ** a hot-journal was just rolled back. In this case the journal
   40369       ** file should be closed and deleted. If this connection writes to
   40370       ** the database file, it will do so using an in-memory journal.
   40371       */
   40372       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   40373            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   40374            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   40375       );
   40376       sqlite3OsClose(pPager->jfd);
   40377       if( !pPager->tempFile ){
   40378         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   40379       }
   40380     }
   40381   }
   40382 
   40383 #ifdef SQLITE_CHECK_PAGES
   40384   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   40385   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   40386     PgHdr *p = pager_lookup(pPager, 1);
   40387     if( p ){
   40388       p->pageHash = 0;
   40389       sqlite3PagerUnref(p);
   40390     }
   40391   }
   40392 #endif
   40393 
   40394   sqlite3BitvecDestroy(pPager->pInJournal);
   40395   pPager->pInJournal = 0;
   40396   pPager->nRec = 0;
   40397   sqlite3PcacheCleanAll(pPager->pPCache);
   40398   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   40399 
   40400   if( pagerUseWal(pPager) ){
   40401     /* Drop the WAL write-lock, if any. Also, if the connection was in
   40402     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   40403     ** lock held on the database file.
   40404     */
   40405     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   40406     assert( rc2==SQLITE_OK );
   40407   }
   40408   if( !pPager->exclusiveMode
   40409    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   40410   ){
   40411     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   40412     pPager->changeCountDone = 0;
   40413   }
   40414   pPager->eState = PAGER_READER;
   40415   pPager->setMaster = 0;
   40416 
   40417   return (rc==SQLITE_OK?rc2:rc);
   40418 }
   40419 
   40420 /*
   40421 ** Execute a rollback if a transaction is active and unlock the
   40422 ** database file.
   40423 **
   40424 ** If the pager has already entered the ERROR state, do not attempt
   40425 ** the rollback at this time. Instead, pager_unlock() is called. The
   40426 ** call to pager_unlock() will discard all in-memory pages, unlock
   40427 ** the database file and move the pager back to OPEN state. If this
   40428 ** means that there is a hot-journal left in the file-system, the next
   40429 ** connection to obtain a shared lock on the pager (which may be this one)
   40430 ** will roll it back.
   40431 **
   40432 ** If the pager has not already entered the ERROR state, but an IO or
   40433 ** malloc error occurs during a rollback, then this will itself cause
   40434 ** the pager to enter the ERROR state. Which will be cleared by the
   40435 ** call to pager_unlock(), as described above.
   40436 */
   40437 static void pagerUnlockAndRollback(Pager *pPager){
   40438   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   40439     assert( assert_pager_state(pPager) );
   40440     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   40441       sqlite3BeginBenignMalloc();
   40442       sqlite3PagerRollback(pPager);
   40443       sqlite3EndBenignMalloc();
   40444     }else if( !pPager->exclusiveMode ){
   40445       assert( pPager->eState==PAGER_READER );
   40446       pager_end_transaction(pPager, 0);
   40447     }
   40448   }
   40449   pager_unlock(pPager);
   40450 }
   40451 
   40452 /*
   40453 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   40454 ** of data. Compute and return a checksum based ont the contents of the
   40455 ** page of data and the current value of pPager->cksumInit.
   40456 **
   40457 ** This is not a real checksum. It is really just the sum of the
   40458 ** random initial value (pPager->cksumInit) and every 200th byte
   40459 ** of the page data, starting with byte offset (pPager->pageSize%200).
   40460 ** Each byte is interpreted as an 8-bit unsigned integer.
   40461 **
   40462 ** Changing the formula used to compute this checksum results in an
   40463 ** incompatible journal file format.
   40464 **
   40465 ** If journal corruption occurs due to a power failure, the most likely
   40466 ** scenario is that one end or the other of the record will be changed.
   40467 ** It is much less likely that the two ends of the journal record will be
   40468 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   40469 ** though fast and simple, catches the mostly likely kind of corruption.
   40470 */
   40471 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   40472   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   40473   int i = pPager->pageSize-200;          /* Loop counter */
   40474   while( i>0 ){
   40475     cksum += aData[i];
   40476     i -= 200;
   40477   }
   40478   return cksum;
   40479 }
   40480 
   40481 /*
   40482 ** Report the current page size and number of reserved bytes back
   40483 ** to the codec.
   40484 */
   40485 #ifdef SQLITE_HAS_CODEC
   40486 static void pagerReportSize(Pager *pPager){
   40487   if( pPager->xCodecSizeChng ){
   40488     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   40489                            (int)pPager->nReserve);
   40490   }
   40491 }
   40492 #else
   40493 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   40494 #endif
   40495 
   40496 /*
   40497 ** Read a single page from either the journal file (if isMainJrnl==1) or
   40498 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   40499 ** The page begins at offset *pOffset into the file. The *pOffset
   40500 ** value is increased to the start of the next page in the journal.
   40501 **
   40502 ** The main rollback journal uses checksums - the statement journal does
   40503 ** not.
   40504 **
   40505 ** If the page number of the page record read from the (sub-)journal file
   40506 ** is greater than the current value of Pager.dbSize, then playback is
   40507 ** skipped and SQLITE_OK is returned.
   40508 **
   40509 ** If pDone is not NULL, then it is a record of pages that have already
   40510 ** been played back.  If the page at *pOffset has already been played back
   40511 ** (if the corresponding pDone bit is set) then skip the playback.
   40512 ** Make sure the pDone bit corresponding to the *pOffset page is set
   40513 ** prior to returning.
   40514 **
   40515 ** If the page record is successfully read from the (sub-)journal file
   40516 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   40517 ** while reading the record from the (sub-)journal file or while writing
   40518 ** to the database file, then the IO error code is returned. If data
   40519 ** is successfully read from the (sub-)journal file but appears to be
   40520 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   40521 ** two circumstances:
   40522 **
   40523 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   40524 **   * If the record is being rolled back from the main journal file
   40525 **     and the checksum field does not match the record content.
   40526 **
   40527 ** Neither of these two scenarios are possible during a savepoint rollback.
   40528 **
   40529 ** If this is a savepoint rollback, then memory may have to be dynamically
   40530 ** allocated by this function. If this is the case and an allocation fails,
   40531 ** SQLITE_NOMEM is returned.
   40532 */
   40533 static int pager_playback_one_page(
   40534   Pager *pPager,                /* The pager being played back */
   40535   i64 *pOffset,                 /* Offset of record to playback */
   40536   Bitvec *pDone,                /* Bitvec of pages already played back */
   40537   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   40538   int isSavepnt                 /* True for a savepoint rollback */
   40539 ){
   40540   int rc;
   40541   PgHdr *pPg;                   /* An existing page in the cache */
   40542   Pgno pgno;                    /* The page number of a page in journal */
   40543   u32 cksum;                    /* Checksum used for sanity checking */
   40544   char *aData;                  /* Temporary storage for the page */
   40545   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   40546   int isSynced;                 /* True if journal page is synced */
   40547 
   40548   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   40549   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   40550   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   40551   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   40552 
   40553   aData = pPager->pTmpSpace;
   40554   assert( aData );         /* Temp storage must have already been allocated */
   40555   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   40556 
   40557   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   40558   ** or savepoint rollback done at the request of the caller) or this is
   40559   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   40560   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   40561   ** only reads from the main journal, not the sub-journal.
   40562   */
   40563   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   40564        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   40565   );
   40566   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   40567 
   40568   /* Read the page number and page data from the journal or sub-journal
   40569   ** file. Return an error code to the caller if an IO error occurs.
   40570   */
   40571   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   40572   rc = read32bits(jfd, *pOffset, &pgno);
   40573   if( rc!=SQLITE_OK ) return rc;
   40574   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   40575   if( rc!=SQLITE_OK ) return rc;
   40576   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   40577 
   40578   /* Sanity checking on the page.  This is more important that I originally
   40579   ** thought.  If a power failure occurs while the journal is being written,
   40580   ** it could cause invalid data to be written into the journal.  We need to
   40581   ** detect this invalid data (with high probability) and ignore it.
   40582   */
   40583   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   40584     assert( !isSavepnt );
   40585     return SQLITE_DONE;
   40586   }
   40587   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   40588     return SQLITE_OK;
   40589   }
   40590   if( isMainJrnl ){
   40591     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   40592     if( rc ) return rc;
   40593     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   40594       return SQLITE_DONE;
   40595     }
   40596   }
   40597 
   40598   /* If this page has already been played by before during the current
   40599   ** rollback, then don't bother to play it back again.
   40600   */
   40601   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   40602     return rc;
   40603   }
   40604 
   40605   /* When playing back page 1, restore the nReserve setting
   40606   */
   40607   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   40608     pPager->nReserve = ((u8*)aData)[20];
   40609     pagerReportSize(pPager);
   40610   }
   40611 
   40612   /* If the pager is in CACHEMOD state, then there must be a copy of this
   40613   ** page in the pager cache. In this case just update the pager cache,
   40614   ** not the database file. The page is left marked dirty in this case.
   40615   **
   40616   ** An exception to the above rule: If the database is in no-sync mode
   40617   ** and a page is moved during an incremental vacuum then the page may
   40618   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   40619   ** during a Movepage() call, then the page may not be in the cache
   40620   ** either. So the condition described in the above paragraph is not
   40621   ** assert()able.
   40622   **
   40623   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   40624   ** pager cache if it exists and the main file. The page is then marked
   40625   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   40626   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   40627   ** if the pager is in OPEN state.
   40628   **
   40629   ** Ticket #1171:  The statement journal might contain page content that is
   40630   ** different from the page content at the start of the transaction.
   40631   ** This occurs when a page is changed prior to the start of a statement
   40632   ** then changed again within the statement.  When rolling back such a
   40633   ** statement we must not write to the original database unless we know
   40634   ** for certain that original page contents are synced into the main rollback
   40635   ** journal.  Otherwise, a power loss might leave modified data in the
   40636   ** database file without an entry in the rollback journal that can
   40637   ** restore the database to its original form.  Two conditions must be
   40638   ** met before writing to the database files. (1) the database must be
   40639   ** locked.  (2) we know that the original page content is fully synced
   40640   ** in the main journal either because the page is not in cache or else
   40641   ** the page is marked as needSync==0.
   40642   **
   40643   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   40644   ** is possible to fail a statement on a database that does not yet exist.
   40645   ** Do not attempt to write if database file has never been opened.
   40646   */
   40647   if( pagerUseWal(pPager) ){
   40648     pPg = 0;
   40649   }else{
   40650     pPg = pager_lookup(pPager, pgno);
   40651   }
   40652   assert( pPg || !MEMDB );
   40653   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
   40654   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   40655            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   40656            (isMainJrnl?"main-journal":"sub-journal")
   40657   ));
   40658   if( isMainJrnl ){
   40659     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   40660   }else{
   40661     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   40662   }
   40663   if( isOpen(pPager->fd)
   40664    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   40665    && isSynced
   40666   ){
   40667     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   40668     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   40669     assert( !pagerUseWal(pPager) );
   40670     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
   40671     if( pgno>pPager->dbFileSize ){
   40672       pPager->dbFileSize = pgno;
   40673     }
   40674     if( pPager->pBackup ){
   40675       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   40676       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   40677       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   40678     }
   40679   }else if( !isMainJrnl && pPg==0 ){
   40680     /* If this is a rollback of a savepoint and data was not written to
   40681     ** the database and the page is not in-memory, there is a potential
   40682     ** problem. When the page is next fetched by the b-tree layer, it
   40683     ** will be read from the database file, which may or may not be
   40684     ** current.
   40685     **
   40686     ** There are a couple of different ways this can happen. All are quite
   40687     ** obscure. When running in synchronous mode, this can only happen
   40688     ** if the page is on the free-list at the start of the transaction, then
   40689     ** populated, then moved using sqlite3PagerMovepage().
   40690     **
   40691     ** The solution is to add an in-memory page to the cache containing
   40692     ** the data just read from the sub-journal. Mark the page as dirty
   40693     ** and if the pager requires a journal-sync, then mark the page as
   40694     ** requiring a journal-sync before it is written.
   40695     */
   40696     assert( isSavepnt );
   40697     assert( pPager->doNotSpill==0 );
   40698     pPager->doNotSpill++;
   40699     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
   40700     assert( pPager->doNotSpill==1 );
   40701     pPager->doNotSpill--;
   40702     if( rc!=SQLITE_OK ) return rc;
   40703     pPg->flags &= ~PGHDR_NEED_READ;
   40704     sqlite3PcacheMakeDirty(pPg);
   40705   }
   40706   if( pPg ){
   40707     /* No page should ever be explicitly rolled back that is in use, except
   40708     ** for page 1 which is held in use in order to keep the lock on the
   40709     ** database active. However such a page may be rolled back as a result
   40710     ** of an internal error resulting in an automatic call to
   40711     ** sqlite3PagerRollback().
   40712     */
   40713     void *pData;
   40714     pData = pPg->pData;
   40715     memcpy(pData, (u8*)aData, pPager->pageSize);
   40716     pPager->xReiniter(pPg);
   40717     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   40718       /* If the contents of this page were just restored from the main
   40719       ** journal file, then its content must be as they were when the
   40720       ** transaction was first opened. In this case we can mark the page
   40721       ** as clean, since there will be no need to write it out to the
   40722       ** database.
   40723       **
   40724       ** There is one exception to this rule. If the page is being rolled
   40725       ** back as part of a savepoint (or statement) rollback from an
   40726       ** unsynced portion of the main journal file, then it is not safe
   40727       ** to mark the page as clean. This is because marking the page as
   40728       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   40729       ** already in the journal file (recorded in Pager.pInJournal) and
   40730       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   40731       ** again within this transaction, it will be marked as dirty but
   40732       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   40733       ** be written out into the database file before its journal file
   40734       ** segment is synced. If a crash occurs during or following this,
   40735       ** database corruption may ensue.
   40736       */
   40737       assert( !pagerUseWal(pPager) );
   40738       sqlite3PcacheMakeClean(pPg);
   40739     }
   40740     pager_set_pagehash(pPg);
   40741 
   40742     /* If this was page 1, then restore the value of Pager.dbFileVers.
   40743     ** Do this before any decoding. */
   40744     if( pgno==1 ){
   40745       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   40746     }
   40747 
   40748     /* Decode the page just read from disk */
   40749     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   40750     sqlite3PcacheRelease(pPg);
   40751   }
   40752   return rc;
   40753 }
   40754 
   40755 /*
   40756 ** Parameter zMaster is the name of a master journal file. A single journal
   40757 ** file that referred to the master journal file has just been rolled back.
   40758 ** This routine checks if it is possible to delete the master journal file,
   40759 ** and does so if it is.
   40760 **
   40761 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   40762 ** available for use within this function.
   40763 **
   40764 ** When a master journal file is created, it is populated with the names
   40765 ** of all of its child journals, one after another, formatted as utf-8
   40766 ** encoded text. The end of each child journal file is marked with a
   40767 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   40768 ** file for a transaction involving two databases might be:
   40769 **
   40770 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   40771 **
   40772 ** A master journal file may only be deleted once all of its child
   40773 ** journals have been rolled back.
   40774 **
   40775 ** This function reads the contents of the master-journal file into
   40776 ** memory and loops through each of the child journal names. For
   40777 ** each child journal, it checks if:
   40778 **
   40779 **   * if the child journal exists, and if so
   40780 **   * if the child journal contains a reference to master journal
   40781 **     file zMaster
   40782 **
   40783 ** If a child journal can be found that matches both of the criteria
   40784 ** above, this function returns without doing anything. Otherwise, if
   40785 ** no such child journal can be found, file zMaster is deleted from
   40786 ** the file-system using sqlite3OsDelete().
   40787 **
   40788 ** If an IO error within this function, an error code is returned. This
   40789 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   40790 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   40791 ** occur, SQLITE_OK is returned.
   40792 **
   40793 ** TODO: This function allocates a single block of memory to load
   40794 ** the entire contents of the master journal file. This could be
   40795 ** a couple of kilobytes or so - potentially larger than the page
   40796 ** size.
   40797 */
   40798 static int pager_delmaster(Pager *pPager, const char *zMaster){
   40799   sqlite3_vfs *pVfs = pPager->pVfs;
   40800   int rc;                   /* Return code */
   40801   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   40802   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   40803   char *zMasterJournal = 0; /* Contents of master journal file */
   40804   i64 nMasterJournal;       /* Size of master journal file */
   40805   char *zJournal;           /* Pointer to one journal within MJ file */
   40806   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   40807   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   40808 
   40809   /* Allocate space for both the pJournal and pMaster file descriptors.
   40810   ** If successful, open the master journal file for reading.
   40811   */
   40812   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   40813   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   40814   if( !pMaster ){
   40815     rc = SQLITE_NOMEM;
   40816   }else{
   40817     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   40818     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   40819   }
   40820   if( rc!=SQLITE_OK ) goto delmaster_out;
   40821 
   40822   /* Load the entire master journal file into space obtained from
   40823   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   40824   ** sufficient space (in zMasterPtr) to hold the names of master
   40825   ** journal files extracted from regular rollback-journals.
   40826   */
   40827   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   40828   if( rc!=SQLITE_OK ) goto delmaster_out;
   40829   nMasterPtr = pVfs->mxPathname+1;
   40830   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   40831   if( !zMasterJournal ){
   40832     rc = SQLITE_NOMEM;
   40833     goto delmaster_out;
   40834   }
   40835   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   40836   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   40837   if( rc!=SQLITE_OK ) goto delmaster_out;
   40838   zMasterJournal[nMasterJournal] = 0;
   40839 
   40840   zJournal = zMasterJournal;
   40841   while( (zJournal-zMasterJournal)<nMasterJournal ){
   40842     int exists;
   40843     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   40844     if( rc!=SQLITE_OK ){
   40845       goto delmaster_out;
   40846     }
   40847     if( exists ){
   40848       /* One of the journals pointed to by the master journal exists.
   40849       ** Open it and check if it points at the master journal. If
   40850       ** so, return without deleting the master journal file.
   40851       */
   40852       int c;
   40853       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   40854       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   40855       if( rc!=SQLITE_OK ){
   40856         goto delmaster_out;
   40857       }
   40858 
   40859       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   40860       sqlite3OsClose(pJournal);
   40861       if( rc!=SQLITE_OK ){
   40862         goto delmaster_out;
   40863       }
   40864 
   40865       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   40866       if( c ){
   40867         /* We have a match. Do not delete the master journal file. */
   40868         goto delmaster_out;
   40869       }
   40870     }
   40871     zJournal += (sqlite3Strlen30(zJournal)+1);
   40872   }
   40873 
   40874   sqlite3OsClose(pMaster);
   40875   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   40876 
   40877 delmaster_out:
   40878   sqlite3_free(zMasterJournal);
   40879   if( pMaster ){
   40880     sqlite3OsClose(pMaster);
   40881     assert( !isOpen(pJournal) );
   40882     sqlite3_free(pMaster);
   40883   }
   40884   return rc;
   40885 }
   40886 
   40887 
   40888 /*
   40889 ** This function is used to change the actual size of the database
   40890 ** file in the file-system. This only happens when committing a transaction,
   40891 ** or rolling back a transaction (including rolling back a hot-journal).
   40892 **
   40893 ** If the main database file is not open, or the pager is not in either
   40894 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   40895 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   40896 ** If the file on disk is currently larger than nPage pages, then use the VFS
   40897 ** xTruncate() method to truncate it.
   40898 **
   40899 ** Or, it might might be the case that the file on disk is smaller than
   40900 ** nPage pages. Some operating system implementations can get confused if
   40901 ** you try to truncate a file to some size that is larger than it
   40902 ** currently is, so detect this case and write a single zero byte to
   40903 ** the end of the new file instead.
   40904 **
   40905 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   40906 ** the database file, return the error code to the caller.
   40907 */
   40908 static int pager_truncate(Pager *pPager, Pgno nPage){
   40909   int rc = SQLITE_OK;
   40910   assert( pPager->eState!=PAGER_ERROR );
   40911   assert( pPager->eState!=PAGER_READER );
   40912 
   40913   if( isOpen(pPager->fd)
   40914    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   40915   ){
   40916     i64 currentSize, newSize;
   40917     int szPage = pPager->pageSize;
   40918     assert( pPager->eLock==EXCLUSIVE_LOCK );
   40919     /* TODO: Is it safe to use Pager.dbFileSize here? */
   40920     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   40921     newSize = szPage*(i64)nPage;
   40922     if( rc==SQLITE_OK && currentSize!=newSize ){
   40923       if( currentSize>newSize ){
   40924         rc = sqlite3OsTruncate(pPager->fd, newSize);
   40925       }else if( (currentSize+szPage)<=newSize ){
   40926         char *pTmp = pPager->pTmpSpace;
   40927         memset(pTmp, 0, szPage);
   40928         testcase( (newSize-szPage) == currentSize );
   40929         testcase( (newSize-szPage) >  currentSize );
   40930         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
   40931       }
   40932       if( rc==SQLITE_OK ){
   40933         pPager->dbFileSize = nPage;
   40934       }
   40935     }
   40936   }
   40937   return rc;
   40938 }
   40939 
   40940 /*
   40941 ** Set the value of the Pager.sectorSize variable for the given
   40942 ** pager based on the value returned by the xSectorSize method
   40943 ** of the open database file. The sector size will be used used
   40944 ** to determine the size and alignment of journal header and
   40945 ** master journal pointers within created journal files.
   40946 **
   40947 ** For temporary files the effective sector size is always 512 bytes.
   40948 **
   40949 ** Otherwise, for non-temporary files, the effective sector size is
   40950 ** the value returned by the xSectorSize() method rounded up to 32 if
   40951 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   40952 ** is greater than MAX_SECTOR_SIZE.
   40953 **
   40954 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
   40955 ** the effective sector size to its minimum value (512).  The purpose of
   40956 ** pPager->sectorSize is to define the "blast radius" of bytes that
   40957 ** might change if a crash occurs while writing to a single byte in
   40958 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
   40959 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
   40960 ** size.  For backwards compatibility of the rollback journal file format,
   40961 ** we cannot reduce the effective sector size below 512.
   40962 */
   40963 static void setSectorSize(Pager *pPager){
   40964   assert( isOpen(pPager->fd) || pPager->tempFile );
   40965 
   40966   if( pPager->tempFile
   40967    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
   40968               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   40969   ){
   40970     /* Sector size doesn't matter for temporary files. Also, the file
   40971     ** may not have been opened yet, in which case the OsSectorSize()
   40972     ** call will segfault. */
   40973     pPager->sectorSize = 512;
   40974   }else{
   40975     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
   40976     if( pPager->sectorSize<32 ){
   40977       pPager->sectorSize = 512;
   40978     }
   40979     if( pPager->sectorSize>MAX_SECTOR_SIZE ){
   40980       assert( MAX_SECTOR_SIZE>=512 );
   40981       pPager->sectorSize = MAX_SECTOR_SIZE;
   40982     }
   40983   }
   40984 }
   40985 
   40986 /*
   40987 ** Playback the journal and thus restore the database file to
   40988 ** the state it was in before we started making changes.
   40989 **
   40990 ** The journal file format is as follows:
   40991 **
   40992 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   40993 **  (2)  4 byte big-endian integer which is the number of valid page records
   40994 **       in the journal.  If this value is 0xffffffff, then compute the
   40995 **       number of page records from the journal size.
   40996 **  (3)  4 byte big-endian integer which is the initial value for the
   40997 **       sanity checksum.
   40998 **  (4)  4 byte integer which is the number of pages to truncate the
   40999 **       database to during a rollback.
   41000 **  (5)  4 byte big-endian integer which is the sector size.  The header
   41001 **       is this many bytes in size.
   41002 **  (6)  4 byte big-endian integer which is the page size.
   41003 **  (7)  zero padding out to the next sector size.
   41004 **  (8)  Zero or more pages instances, each as follows:
   41005 **        +  4 byte page number.
   41006 **        +  pPager->pageSize bytes of data.
   41007 **        +  4 byte checksum
   41008 **
   41009 ** When we speak of the journal header, we mean the first 7 items above.
   41010 ** Each entry in the journal is an instance of the 8th item.
   41011 **
   41012 ** Call the value from the second bullet "nRec".  nRec is the number of
   41013 ** valid page entries in the journal.  In most cases, you can compute the
   41014 ** value of nRec from the size of the journal file.  But if a power
   41015 ** failure occurred while the journal was being written, it could be the
   41016 ** case that the size of the journal file had already been increased but
   41017 ** the extra entries had not yet made it safely to disk.  In such a case,
   41018 ** the value of nRec computed from the file size would be too large.  For
   41019 ** that reason, we always use the nRec value in the header.
   41020 **
   41021 ** If the nRec value is 0xffffffff it means that nRec should be computed
   41022 ** from the file size.  This value is used when the user selects the
   41023 ** no-sync option for the journal.  A power failure could lead to corruption
   41024 ** in this case.  But for things like temporary table (which will be
   41025 ** deleted when the power is restored) we don't care.
   41026 **
   41027 ** If the file opened as the journal file is not a well-formed
   41028 ** journal file then all pages up to the first corrupted page are rolled
   41029 ** back (or no pages if the journal header is corrupted). The journal file
   41030 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   41031 ** been encountered.
   41032 **
   41033 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   41034 ** and an error code is returned.
   41035 **
   41036 ** The isHot parameter indicates that we are trying to rollback a journal
   41037 ** that might be a hot journal.  Or, it could be that the journal is
   41038 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   41039 ** If the journal really is hot, reset the pager cache prior rolling
   41040 ** back any content.  If the journal is merely persistent, no reset is
   41041 ** needed.
   41042 */
   41043 static int pager_playback(Pager *pPager, int isHot){
   41044   sqlite3_vfs *pVfs = pPager->pVfs;
   41045   i64 szJ;                 /* Size of the journal file in bytes */
   41046   u32 nRec;                /* Number of Records in the journal */
   41047   u32 u;                   /* Unsigned loop counter */
   41048   Pgno mxPg = 0;           /* Size of the original file in pages */
   41049   int rc;                  /* Result code of a subroutine */
   41050   int res = 1;             /* Value returned by sqlite3OsAccess() */
   41051   char *zMaster = 0;       /* Name of master journal file if any */
   41052   int needPagerReset;      /* True to reset page prior to first page rollback */
   41053 
   41054   /* Figure out how many records are in the journal.  Abort early if
   41055   ** the journal is empty.
   41056   */
   41057   assert( isOpen(pPager->jfd) );
   41058   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   41059   if( rc!=SQLITE_OK ){
   41060     goto end_playback;
   41061   }
   41062 
   41063   /* Read the master journal name from the journal, if it is present.
   41064   ** If a master journal file name is specified, but the file is not
   41065   ** present on disk, then the journal is not hot and does not need to be
   41066   ** played back.
   41067   **
   41068   ** TODO: Technically the following is an error because it assumes that
   41069   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   41070   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   41071   **  mxPathname is 512, which is the same as the minimum allowable value
   41072   ** for pageSize.
   41073   */
   41074   zMaster = pPager->pTmpSpace;
   41075   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   41076   if( rc==SQLITE_OK && zMaster[0] ){
   41077     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   41078   }
   41079   zMaster = 0;
   41080   if( rc!=SQLITE_OK || !res ){
   41081     goto end_playback;
   41082   }
   41083   pPager->journalOff = 0;
   41084   needPagerReset = isHot;
   41085 
   41086   /* This loop terminates either when a readJournalHdr() or
   41087   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   41088   ** occurs.
   41089   */
   41090   while( 1 ){
   41091     /* Read the next journal header from the journal file.  If there are
   41092     ** not enough bytes left in the journal file for a complete header, or
   41093     ** it is corrupted, then a process must have failed while writing it.
   41094     ** This indicates nothing more needs to be rolled back.
   41095     */
   41096     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   41097     if( rc!=SQLITE_OK ){
   41098       if( rc==SQLITE_DONE ){
   41099         rc = SQLITE_OK;
   41100       }
   41101       goto end_playback;
   41102     }
   41103 
   41104     /* If nRec is 0xffffffff, then this journal was created by a process
   41105     ** working in no-sync mode. This means that the rest of the journal
   41106     ** file consists of pages, there are no more journal headers. Compute
   41107     ** the value of nRec based on this assumption.
   41108     */
   41109     if( nRec==0xffffffff ){
   41110       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   41111       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   41112     }
   41113 
   41114     /* If nRec is 0 and this rollback is of a transaction created by this
   41115     ** process and if this is the final header in the journal, then it means
   41116     ** that this part of the journal was being filled but has not yet been
   41117     ** synced to disk.  Compute the number of pages based on the remaining
   41118     ** size of the file.
   41119     **
   41120     ** The third term of the test was added to fix ticket #2565.
   41121     ** When rolling back a hot journal, nRec==0 always means that the next
   41122     ** chunk of the journal contains zero pages to be rolled back.  But
   41123     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   41124     ** the journal, it means that the journal might contain additional
   41125     ** pages that need to be rolled back and that the number of pages
   41126     ** should be computed based on the journal file size.
   41127     */
   41128     if( nRec==0 && !isHot &&
   41129         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   41130       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   41131     }
   41132 
   41133     /* If this is the first header read from the journal, truncate the
   41134     ** database file back to its original size.
   41135     */
   41136     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   41137       rc = pager_truncate(pPager, mxPg);
   41138       if( rc!=SQLITE_OK ){
   41139         goto end_playback;
   41140       }
   41141       pPager->dbSize = mxPg;
   41142     }
   41143 
   41144     /* Copy original pages out of the journal and back into the
   41145     ** database file and/or page cache.
   41146     */
   41147     for(u=0; u<nRec; u++){
   41148       if( needPagerReset ){
   41149         pager_reset(pPager);
   41150         needPagerReset = 0;
   41151       }
   41152       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   41153       if( rc!=SQLITE_OK ){
   41154         if( rc==SQLITE_DONE ){
   41155           pPager->journalOff = szJ;
   41156           break;
   41157         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   41158           /* If the journal has been truncated, simply stop reading and
   41159           ** processing the journal. This might happen if the journal was
   41160           ** not completely written and synced prior to a crash.  In that
   41161           ** case, the database should have never been written in the
   41162           ** first place so it is OK to simply abandon the rollback. */
   41163           rc = SQLITE_OK;
   41164           goto end_playback;
   41165         }else{
   41166           /* If we are unable to rollback, quit and return the error
   41167           ** code.  This will cause the pager to enter the error state
   41168           ** so that no further harm will be done.  Perhaps the next
   41169           ** process to come along will be able to rollback the database.
   41170           */
   41171           goto end_playback;
   41172         }
   41173       }
   41174     }
   41175   }
   41176   /*NOTREACHED*/
   41177   assert( 0 );
   41178 
   41179 end_playback:
   41180   /* Following a rollback, the database file should be back in its original
   41181   ** state prior to the start of the transaction, so invoke the
   41182   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   41183   ** assertion that the transaction counter was modified.
   41184   */
   41185 #ifdef SQLITE_DEBUG
   41186   if( pPager->fd->pMethods ){
   41187     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
   41188   }
   41189 #endif
   41190 
   41191   /* If this playback is happening automatically as a result of an IO or
   41192   ** malloc error that occurred after the change-counter was updated but
   41193   ** before the transaction was committed, then the change-counter
   41194   ** modification may just have been reverted. If this happens in exclusive
   41195   ** mode, then subsequent transactions performed by the connection will not
   41196   ** update the change-counter at all. This may lead to cache inconsistency
   41197   ** problems for other processes at some point in the future. So, just
   41198   ** in case this has happened, clear the changeCountDone flag now.
   41199   */
   41200   pPager->changeCountDone = pPager->tempFile;
   41201 
   41202   if( rc==SQLITE_OK ){
   41203     zMaster = pPager->pTmpSpace;
   41204     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   41205     testcase( rc!=SQLITE_OK );
   41206   }
   41207   if( rc==SQLITE_OK
   41208    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   41209   ){
   41210     rc = sqlite3PagerSync(pPager);
   41211   }
   41212   if( rc==SQLITE_OK ){
   41213     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
   41214     testcase( rc!=SQLITE_OK );
   41215   }
   41216   if( rc==SQLITE_OK && zMaster[0] && res ){
   41217     /* If there was a master journal and this routine will return success,
   41218     ** see if it is possible to delete the master journal.
   41219     */
   41220     rc = pager_delmaster(pPager, zMaster);
   41221     testcase( rc!=SQLITE_OK );
   41222   }
   41223 
   41224   /* The Pager.sectorSize variable may have been updated while rolling
   41225   ** back a journal created by a process with a different sector size
   41226   ** value. Reset it to the correct value for this process.
   41227   */
   41228   setSectorSize(pPager);
   41229   return rc;
   41230 }
   41231 
   41232 
   41233 /*
   41234 ** Read the content for page pPg out of the database file and into
   41235 ** pPg->pData. A shared lock or greater must be held on the database
   41236 ** file before this function is called.
   41237 **
   41238 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   41239 ** the value read from the database file.
   41240 **
   41241 ** If an IO error occurs, then the IO error is returned to the caller.
   41242 ** Otherwise, SQLITE_OK is returned.
   41243 */
   41244 static int readDbPage(PgHdr *pPg){
   41245   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   41246   Pgno pgno = pPg->pgno;       /* Page number to read */
   41247   int rc = SQLITE_OK;          /* Return code */
   41248   int isInWal = 0;             /* True if page is in log file */
   41249   int pgsz = pPager->pageSize; /* Number of bytes to read */
   41250 
   41251   assert( pPager->eState>=PAGER_READER && !MEMDB );
   41252   assert( isOpen(pPager->fd) );
   41253 
   41254   if( NEVER(!isOpen(pPager->fd)) ){
   41255     assert( pPager->tempFile );
   41256     memset(pPg->pData, 0, pPager->pageSize);
   41257     return SQLITE_OK;
   41258   }
   41259 
   41260   if( pagerUseWal(pPager) ){
   41261     /* Try to pull the page from the write-ahead log. */
   41262     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
   41263   }
   41264   if( rc==SQLITE_OK && !isInWal ){
   41265     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
   41266     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
   41267     if( rc==SQLITE_IOERR_SHORT_READ ){
   41268       rc = SQLITE_OK;
   41269     }
   41270   }
   41271 
   41272   if( pgno==1 ){
   41273     if( rc ){
   41274       /* If the read is unsuccessful, set the dbFileVers[] to something
   41275       ** that will never be a valid file version.  dbFileVers[] is a copy
   41276       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   41277       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   41278       ** should be page numbers which are never 0xffffffff.  So filling
   41279       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   41280       **
   41281       ** For an encrypted database, the situation is more complex:  bytes
   41282       ** 24..39 of the database are white noise.  But the probability of
   41283       ** white noising equaling 16 bytes of 0xff is vanishingly small so
   41284       ** we should still be ok.
   41285       */
   41286       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   41287     }else{
   41288       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   41289       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   41290     }
   41291   }
   41292   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   41293 
   41294   PAGER_INCR(sqlite3_pager_readdb_count);
   41295   PAGER_INCR(pPager->nRead);
   41296   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   41297   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   41298                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   41299 
   41300   return rc;
   41301 }
   41302 
   41303 /*
   41304 ** Update the value of the change-counter at offsets 24 and 92 in
   41305 ** the header and the sqlite version number at offset 96.
   41306 **
   41307 ** This is an unconditional update.  See also the pager_incr_changecounter()
   41308 ** routine which only updates the change-counter if the update is actually
   41309 ** needed, as determined by the pPager->changeCountDone state variable.
   41310 */
   41311 static void pager_write_changecounter(PgHdr *pPg){
   41312   u32 change_counter;
   41313 
   41314   /* Increment the value just read and write it back to byte 24. */
   41315   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   41316   put32bits(((char*)pPg->pData)+24, change_counter);
   41317 
   41318   /* Also store the SQLite version number in bytes 96..99 and in
   41319   ** bytes 92..95 store the change counter for which the version number
   41320   ** is valid. */
   41321   put32bits(((char*)pPg->pData)+92, change_counter);
   41322   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   41323 }
   41324 
   41325 #ifndef SQLITE_OMIT_WAL
   41326 /*
   41327 ** This function is invoked once for each page that has already been
   41328 ** written into the log file when a WAL transaction is rolled back.
   41329 ** Parameter iPg is the page number of said page. The pCtx argument
   41330 ** is actually a pointer to the Pager structure.
   41331 **
   41332 ** If page iPg is present in the cache, and has no outstanding references,
   41333 ** it is discarded. Otherwise, if there are one or more outstanding
   41334 ** references, the page content is reloaded from the database. If the
   41335 ** attempt to reload content from the database is required and fails,
   41336 ** return an SQLite error code. Otherwise, SQLITE_OK.
   41337 */
   41338 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   41339   int rc = SQLITE_OK;
   41340   Pager *pPager = (Pager *)pCtx;
   41341   PgHdr *pPg;
   41342 
   41343   pPg = sqlite3PagerLookup(pPager, iPg);
   41344   if( pPg ){
   41345     if( sqlite3PcachePageRefcount(pPg)==1 ){
   41346       sqlite3PcacheDrop(pPg);
   41347     }else{
   41348       rc = readDbPage(pPg);
   41349       if( rc==SQLITE_OK ){
   41350         pPager->xReiniter(pPg);
   41351       }
   41352       sqlite3PagerUnref(pPg);
   41353     }
   41354   }
   41355 
   41356   /* Normally, if a transaction is rolled back, any backup processes are
   41357   ** updated as data is copied out of the rollback journal and into the
   41358   ** database. This is not generally possible with a WAL database, as
   41359   ** rollback involves simply truncating the log file. Therefore, if one
   41360   ** or more frames have already been written to the log (and therefore
   41361   ** also copied into the backup databases) as part of this transaction,
   41362   ** the backups must be restarted.
   41363   */
   41364   sqlite3BackupRestart(pPager->pBackup);
   41365 
   41366   return rc;
   41367 }
   41368 
   41369 /*
   41370 ** This function is called to rollback a transaction on a WAL database.
   41371 */
   41372 static int pagerRollbackWal(Pager *pPager){
   41373   int rc;                         /* Return Code */
   41374   PgHdr *pList;                   /* List of dirty pages to revert */
   41375 
   41376   /* For all pages in the cache that are currently dirty or have already
   41377   ** been written (but not committed) to the log file, do one of the
   41378   ** following:
   41379   **
   41380   **   + Discard the cached page (if refcount==0), or
   41381   **   + Reload page content from the database (if refcount>0).
   41382   */
   41383   pPager->dbSize = pPager->dbOrigSize;
   41384   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   41385   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   41386   while( pList && rc==SQLITE_OK ){
   41387     PgHdr *pNext = pList->pDirty;
   41388     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   41389     pList = pNext;
   41390   }
   41391 
   41392   return rc;
   41393 }
   41394 
   41395 /*
   41396 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   41397 ** the contents of the list of pages headed by pList (connected by pDirty),
   41398 ** this function notifies any active backup processes that the pages have
   41399 ** changed.
   41400 **
   41401 ** The list of pages passed into this routine is always sorted by page number.
   41402 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   41403 */
   41404 static int pagerWalFrames(
   41405   Pager *pPager,                  /* Pager object */
   41406   PgHdr *pList,                   /* List of frames to log */
   41407   Pgno nTruncate,                 /* Database size after this commit */
   41408   int isCommit                    /* True if this is a commit */
   41409 ){
   41410   int rc;                         /* Return code */
   41411 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
   41412   PgHdr *p;                       /* For looping over pages */
   41413 #endif
   41414 
   41415   assert( pPager->pWal );
   41416   assert( pList );
   41417 #ifdef SQLITE_DEBUG
   41418   /* Verify that the page list is in accending order */
   41419   for(p=pList; p && p->pDirty; p=p->pDirty){
   41420     assert( p->pgno < p->pDirty->pgno );
   41421   }
   41422 #endif
   41423 
   41424   if( isCommit ){
   41425     /* If a WAL transaction is being committed, there is no point in writing
   41426     ** any pages with page numbers greater than nTruncate into the WAL file.
   41427     ** They will never be read by any client. So remove them from the pDirty
   41428     ** list here. */
   41429     PgHdr *p;
   41430     PgHdr **ppNext = &pList;
   41431     for(p=pList; (*ppNext = p); p=p->pDirty){
   41432       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
   41433     }
   41434     assert( pList );
   41435   }
   41436 
   41437   if( pList->pgno==1 ) pager_write_changecounter(pList);
   41438   rc = sqlite3WalFrames(pPager->pWal,
   41439       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   41440   );
   41441   if( rc==SQLITE_OK && pPager->pBackup ){
   41442     PgHdr *p;
   41443     for(p=pList; p; p=p->pDirty){
   41444       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   41445     }
   41446   }
   41447 
   41448 #ifdef SQLITE_CHECK_PAGES
   41449   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   41450   for(p=pList; p; p=p->pDirty){
   41451     pager_set_pagehash(p);
   41452   }
   41453 #endif
   41454 
   41455   return rc;
   41456 }
   41457 
   41458 /*
   41459 ** Begin a read transaction on the WAL.
   41460 **
   41461 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   41462 ** makes a snapshot of the database at the current point in time and preserves
   41463 ** that snapshot for use by the reader in spite of concurrently changes by
   41464 ** other writers or checkpointers.
   41465 */
   41466 static int pagerBeginReadTransaction(Pager *pPager){
   41467   int rc;                         /* Return code */
   41468   int changed = 0;                /* True if cache must be reset */
   41469 
   41470   assert( pagerUseWal(pPager) );
   41471   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   41472 
   41473   /* sqlite3WalEndReadTransaction() was not called for the previous
   41474   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   41475   ** are in locking_mode=NORMAL and EndRead() was previously called,
   41476   ** the duplicate call is harmless.
   41477   */
   41478   sqlite3WalEndReadTransaction(pPager->pWal);
   41479 
   41480   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   41481   if( rc!=SQLITE_OK || changed ){
   41482     pager_reset(pPager);
   41483   }
   41484 
   41485   return rc;
   41486 }
   41487 #endif
   41488 
   41489 /*
   41490 ** This function is called as part of the transition from PAGER_OPEN
   41491 ** to PAGER_READER state to determine the size of the database file
   41492 ** in pages (assuming the page size currently stored in Pager.pageSize).
   41493 **
   41494 ** If no error occurs, SQLITE_OK is returned and the size of the database
   41495 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   41496 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   41497 */
   41498 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   41499   Pgno nPage;                     /* Value to return via *pnPage */
   41500 
   41501   /* Query the WAL sub-system for the database size. The WalDbsize()
   41502   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   41503   ** if the database size is not available. The database size is not
   41504   ** available from the WAL sub-system if the log file is empty or
   41505   ** contains no valid committed transactions.
   41506   */
   41507   assert( pPager->eState==PAGER_OPEN );
   41508   assert( pPager->eLock>=SHARED_LOCK );
   41509   nPage = sqlite3WalDbsize(pPager->pWal);
   41510 
   41511   /* If the database size was not available from the WAL sub-system,
   41512   ** determine it based on the size of the database file. If the size
   41513   ** of the database file is not an integer multiple of the page-size,
   41514   ** round down to the nearest page. Except, any file larger than 0
   41515   ** bytes in size is considered to contain at least one page.
   41516   */
   41517   if( nPage==0 ){
   41518     i64 n = 0;                    /* Size of db file in bytes */
   41519     assert( isOpen(pPager->fd) || pPager->tempFile );
   41520     if( isOpen(pPager->fd) ){
   41521       int rc = sqlite3OsFileSize(pPager->fd, &n);
   41522       if( rc!=SQLITE_OK ){
   41523         return rc;
   41524       }
   41525     }
   41526     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
   41527   }
   41528 
   41529   /* If the current number of pages in the file is greater than the
   41530   ** configured maximum pager number, increase the allowed limit so
   41531   ** that the file can be read.
   41532   */
   41533   if( nPage>pPager->mxPgno ){
   41534     pPager->mxPgno = (Pgno)nPage;
   41535   }
   41536 
   41537   *pnPage = nPage;
   41538   return SQLITE_OK;
   41539 }
   41540 
   41541 #ifndef SQLITE_OMIT_WAL
   41542 /*
   41543 ** Check if the *-wal file that corresponds to the database opened by pPager
   41544 ** exists if the database is not empy, or verify that the *-wal file does
   41545 ** not exist (by deleting it) if the database file is empty.
   41546 **
   41547 ** If the database is not empty and the *-wal file exists, open the pager
   41548 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   41549 ** if no error occurs, make sure Pager.journalMode is not set to
   41550 ** PAGER_JOURNALMODE_WAL.
   41551 **
   41552 ** Return SQLITE_OK or an error code.
   41553 **
   41554 ** The caller must hold a SHARED lock on the database file to call this
   41555 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   41556 ** a WAL on a none-empty database, this ensures there is no race condition
   41557 ** between the xAccess() below and an xDelete() being executed by some
   41558 ** other connection.
   41559 */
   41560 static int pagerOpenWalIfPresent(Pager *pPager){
   41561   int rc = SQLITE_OK;
   41562   assert( pPager->eState==PAGER_OPEN );
   41563   assert( pPager->eLock>=SHARED_LOCK );
   41564 
   41565   if( !pPager->tempFile ){
   41566     int isWal;                    /* True if WAL file exists */
   41567     Pgno nPage;                   /* Size of the database file */
   41568 
   41569     rc = pagerPagecount(pPager, &nPage);
   41570     if( rc ) return rc;
   41571     if( nPage==0 ){
   41572       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   41573       isWal = 0;
   41574     }else{
   41575       rc = sqlite3OsAccess(
   41576           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   41577       );
   41578     }
   41579     if( rc==SQLITE_OK ){
   41580       if( isWal ){
   41581         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   41582         rc = sqlite3PagerOpenWal(pPager, 0);
   41583       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   41584         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   41585       }
   41586     }
   41587   }
   41588   return rc;
   41589 }
   41590 #endif
   41591 
   41592 /*
   41593 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   41594 ** the entire master journal file. The case pSavepoint==NULL occurs when
   41595 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   41596 ** savepoint.
   41597 **
   41598 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   41599 ** being rolled back), then the rollback consists of up to three stages,
   41600 ** performed in the order specified:
   41601 **
   41602 **   * Pages are played back from the main journal starting at byte
   41603 **     offset PagerSavepoint.iOffset and continuing to
   41604 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   41605 **     file if PagerSavepoint.iHdrOffset is zero.
   41606 **
   41607 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   41608 **     back starting from the journal header immediately following
   41609 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   41610 **
   41611 **   * Pages are then played back from the sub-journal file, starting
   41612 **     with the PagerSavepoint.iSubRec and continuing to the end of
   41613 **     the journal file.
   41614 **
   41615 ** Throughout the rollback process, each time a page is rolled back, the
   41616 ** corresponding bit is set in a bitvec structure (variable pDone in the
   41617 ** implementation below). This is used to ensure that a page is only
   41618 ** rolled back the first time it is encountered in either journal.
   41619 **
   41620 ** If pSavepoint is NULL, then pages are only played back from the main
   41621 ** journal file. There is no need for a bitvec in this case.
   41622 **
   41623 ** In either case, before playback commences the Pager.dbSize variable
   41624 ** is reset to the value that it held at the start of the savepoint
   41625 ** (or transaction). No page with a page-number greater than this value
   41626 ** is played back. If one is encountered it is simply skipped.
   41627 */
   41628 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   41629   i64 szJ;                 /* Effective size of the main journal */
   41630   i64 iHdrOff;             /* End of first segment of main-journal records */
   41631   int rc = SQLITE_OK;      /* Return code */
   41632   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   41633 
   41634   assert( pPager->eState!=PAGER_ERROR );
   41635   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   41636 
   41637   /* Allocate a bitvec to use to store the set of pages rolled back */
   41638   if( pSavepoint ){
   41639     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   41640     if( !pDone ){
   41641       return SQLITE_NOMEM;
   41642     }
   41643   }
   41644 
   41645   /* Set the database size back to the value it was before the savepoint
   41646   ** being reverted was opened.
   41647   */
   41648   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   41649   pPager->changeCountDone = pPager->tempFile;
   41650 
   41651   if( !pSavepoint && pagerUseWal(pPager) ){
   41652     return pagerRollbackWal(pPager);
   41653   }
   41654 
   41655   /* Use pPager->journalOff as the effective size of the main rollback
   41656   ** journal.  The actual file might be larger than this in
   41657   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   41658   ** past pPager->journalOff is off-limits to us.
   41659   */
   41660   szJ = pPager->journalOff;
   41661   assert( pagerUseWal(pPager)==0 || szJ==0 );
   41662 
   41663   /* Begin by rolling back records from the main journal starting at
   41664   ** PagerSavepoint.iOffset and continuing to the next journal header.
   41665   ** There might be records in the main journal that have a page number
   41666   ** greater than the current database size (pPager->dbSize) but those
   41667   ** will be skipped automatically.  Pages are added to pDone as they
   41668   ** are played back.
   41669   */
   41670   if( pSavepoint && !pagerUseWal(pPager) ){
   41671     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   41672     pPager->journalOff = pSavepoint->iOffset;
   41673     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   41674       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   41675     }
   41676     assert( rc!=SQLITE_DONE );
   41677   }else{
   41678     pPager->journalOff = 0;
   41679   }
   41680 
   41681   /* Continue rolling back records out of the main journal starting at
   41682   ** the first journal header seen and continuing until the effective end
   41683   ** of the main journal file.  Continue to skip out-of-range pages and
   41684   ** continue adding pages rolled back to pDone.
   41685   */
   41686   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   41687     u32 ii;            /* Loop counter */
   41688     u32 nJRec = 0;     /* Number of Journal Records */
   41689     u32 dummy;
   41690     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   41691     assert( rc!=SQLITE_DONE );
   41692 
   41693     /*
   41694     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   41695     ** test is related to ticket #2565.  See the discussion in the
   41696     ** pager_playback() function for additional information.
   41697     */
   41698     if( nJRec==0
   41699      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   41700     ){
   41701       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   41702     }
   41703     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   41704       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   41705     }
   41706     assert( rc!=SQLITE_DONE );
   41707   }
   41708   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   41709 
   41710   /* Finally,  rollback pages from the sub-journal.  Page that were
   41711   ** previously rolled back out of the main journal (and are hence in pDone)
   41712   ** will be skipped.  Out-of-range pages are also skipped.
   41713   */
   41714   if( pSavepoint ){
   41715     u32 ii;            /* Loop counter */
   41716     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
   41717 
   41718     if( pagerUseWal(pPager) ){
   41719       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   41720     }
   41721     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   41722       assert( offset==(i64)ii*(4+pPager->pageSize) );
   41723       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   41724     }
   41725     assert( rc!=SQLITE_DONE );
   41726   }
   41727 
   41728   sqlite3BitvecDestroy(pDone);
   41729   if( rc==SQLITE_OK ){
   41730     pPager->journalOff = szJ;
   41731   }
   41732 
   41733   return rc;
   41734 }
   41735 
   41736 /*
   41737 ** Change the maximum number of in-memory pages that are allowed.
   41738 */
   41739 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   41740   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   41741 }
   41742 
   41743 /*
   41744 ** Free as much memory as possible from the pager.
   41745 */
   41746 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
   41747   sqlite3PcacheShrink(pPager->pPCache);
   41748 }
   41749 
   41750 /*
   41751 ** Adjust the robustness of the database to damage due to OS crashes
   41752 ** or power failures by changing the number of syncs()s when writing
   41753 ** the rollback journal.  There are three levels:
   41754 **
   41755 **    OFF       sqlite3OsSync() is never called.  This is the default
   41756 **              for temporary and transient files.
   41757 **
   41758 **    NORMAL    The journal is synced once before writes begin on the
   41759 **              database.  This is normally adequate protection, but
   41760 **              it is theoretically possible, though very unlikely,
   41761 **              that an inopertune power failure could leave the journal
   41762 **              in a state which would cause damage to the database
   41763 **              when it is rolled back.
   41764 **
   41765 **    FULL      The journal is synced twice before writes begin on the
   41766 **              database (with some additional information - the nRec field
   41767 **              of the journal header - being written in between the two
   41768 **              syncs).  If we assume that writing a
   41769 **              single disk sector is atomic, then this mode provides
   41770 **              assurance that the journal will not be corrupted to the
   41771 **              point of causing damage to the database during rollback.
   41772 **
   41773 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   41774 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   41775 ** prior to the start of checkpoint and that the database file is synced
   41776 ** at the conclusion of the checkpoint if the entire content of the WAL
   41777 ** was written back into the database.  But no sync operations occur for
   41778 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   41779 ** file is synced following each commit operation, in addition to the
   41780 ** syncs associated with NORMAL.
   41781 **
   41782 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   41783 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   41784 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   41785 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   41786 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   41787 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   41788 ** the xSync primitive is called and is relevant to all platforms.
   41789 **
   41790 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   41791 ** and FULL=3.
   41792 */
   41793 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   41794 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
   41795   Pager *pPager,        /* The pager to set safety level for */
   41796   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   41797   int bFullFsync,       /* PRAGMA fullfsync */
   41798   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
   41799 ){
   41800   assert( level>=1 && level<=3 );
   41801   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   41802   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   41803   if( pPager->noSync ){
   41804     pPager->syncFlags = 0;
   41805     pPager->ckptSyncFlags = 0;
   41806   }else if( bFullFsync ){
   41807     pPager->syncFlags = SQLITE_SYNC_FULL;
   41808     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   41809   }else if( bCkptFullFsync ){
   41810     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   41811     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   41812   }else{
   41813     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   41814     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   41815   }
   41816   pPager->walSyncFlags = pPager->syncFlags;
   41817   if( pPager->fullSync ){
   41818     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
   41819   }
   41820 }
   41821 #endif
   41822 
   41823 /*
   41824 ** The following global variable is incremented whenever the library
   41825 ** attempts to open a temporary file.  This information is used for
   41826 ** testing and analysis only.
   41827 */
   41828 #ifdef SQLITE_TEST
   41829 SQLITE_API int sqlite3_opentemp_count = 0;
   41830 #endif
   41831 
   41832 /*
   41833 ** Open a temporary file.
   41834 **
   41835 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   41836 ** or some other error code if we fail. The OS will automatically
   41837 ** delete the temporary file when it is closed.
   41838 **
   41839 ** The flags passed to the VFS layer xOpen() call are those specified
   41840 ** by parameter vfsFlags ORed with the following:
   41841 **
   41842 **     SQLITE_OPEN_READWRITE
   41843 **     SQLITE_OPEN_CREATE
   41844 **     SQLITE_OPEN_EXCLUSIVE
   41845 **     SQLITE_OPEN_DELETEONCLOSE
   41846 */
   41847 static int pagerOpentemp(
   41848   Pager *pPager,        /* The pager object */
   41849   sqlite3_file *pFile,  /* Write the file descriptor here */
   41850   int vfsFlags          /* Flags passed through to the VFS */
   41851 ){
   41852   int rc;               /* Return code */
   41853 
   41854 #ifdef SQLITE_TEST
   41855   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   41856 #endif
   41857 
   41858   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   41859             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   41860   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   41861   assert( rc!=SQLITE_OK || isOpen(pFile) );
   41862   return rc;
   41863 }
   41864 
   41865 /*
   41866 ** Set the busy handler function.
   41867 **
   41868 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   41869 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   41870 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   41871 ** lock. It does *not* invoke the busy handler when upgrading from
   41872 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   41873 ** (which occurs during hot-journal rollback). Summary:
   41874 **
   41875 **   Transition                        | Invokes xBusyHandler
   41876 **   --------------------------------------------------------
   41877 **   NO_LOCK       -> SHARED_LOCK      | Yes
   41878 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   41879 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   41880 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   41881 **
   41882 ** If the busy-handler callback returns non-zero, the lock is
   41883 ** retried. If it returns zero, then the SQLITE_BUSY error is
   41884 ** returned to the caller of the pager API function.
   41885 */
   41886 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   41887   Pager *pPager,                       /* Pager object */
   41888   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   41889   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   41890 ){
   41891   pPager->xBusyHandler = xBusyHandler;
   41892   pPager->pBusyHandlerArg = pBusyHandlerArg;
   41893 }
   41894 
   41895 /*
   41896 ** Change the page size used by the Pager object. The new page size
   41897 ** is passed in *pPageSize.
   41898 **
   41899 ** If the pager is in the error state when this function is called, it
   41900 ** is a no-op. The value returned is the error state error code (i.e.
   41901 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   41902 **
   41903 ** Otherwise, if all of the following are true:
   41904 **
   41905 **   * the new page size (value of *pPageSize) is valid (a power
   41906 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   41907 **
   41908 **   * there are no outstanding page references, and
   41909 **
   41910 **   * the database is either not an in-memory database or it is
   41911 **     an in-memory database that currently consists of zero pages.
   41912 **
   41913 ** then the pager object page size is set to *pPageSize.
   41914 **
   41915 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   41916 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   41917 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   41918 ** In all other cases, SQLITE_OK is returned.
   41919 **
   41920 ** If the page size is not changed, either because one of the enumerated
   41921 ** conditions above is not true, the pager was in error state when this
   41922 ** function was called, or because the memory allocation attempt failed,
   41923 ** then *pPageSize is set to the old, retained page size before returning.
   41924 */
   41925 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   41926   int rc = SQLITE_OK;
   41927 
   41928   /* It is not possible to do a full assert_pager_state() here, as this
   41929   ** function may be called from within PagerOpen(), before the state
   41930   ** of the Pager object is internally consistent.
   41931   **
   41932   ** At one point this function returned an error if the pager was in
   41933   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   41934   ** there is at least one outstanding page reference, this function
   41935   ** is a no-op for that case anyhow.
   41936   */
   41937 
   41938   u32 pageSize = *pPageSize;
   41939   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   41940   if( (pPager->memDb==0 || pPager->dbSize==0)
   41941    && sqlite3PcacheRefCount(pPager->pPCache)==0
   41942    && pageSize && pageSize!=(u32)pPager->pageSize
   41943   ){
   41944     char *pNew = NULL;             /* New temp space */
   41945     i64 nByte = 0;
   41946 
   41947     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   41948       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   41949     }
   41950     if( rc==SQLITE_OK ){
   41951       pNew = (char *)sqlite3PageMalloc(pageSize);
   41952       if( !pNew ) rc = SQLITE_NOMEM;
   41953     }
   41954 
   41955     if( rc==SQLITE_OK ){
   41956       pager_reset(pPager);
   41957       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
   41958       pPager->pageSize = pageSize;
   41959       sqlite3PageFree(pPager->pTmpSpace);
   41960       pPager->pTmpSpace = pNew;
   41961       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   41962     }
   41963   }
   41964 
   41965   *pPageSize = pPager->pageSize;
   41966   if( rc==SQLITE_OK ){
   41967     if( nReserve<0 ) nReserve = pPager->nReserve;
   41968     assert( nReserve>=0 && nReserve<1000 );
   41969     pPager->nReserve = (i16)nReserve;
   41970     pagerReportSize(pPager);
   41971   }
   41972   return rc;
   41973 }
   41974 
   41975 /*
   41976 ** Return a pointer to the "temporary page" buffer held internally
   41977 ** by the pager.  This is a buffer that is big enough to hold the
   41978 ** entire content of a database page.  This buffer is used internally
   41979 ** during rollback and will be overwritten whenever a rollback
   41980 ** occurs.  But other modules are free to use it too, as long as
   41981 ** no rollbacks are happening.
   41982 */
   41983 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   41984   return pPager->pTmpSpace;
   41985 }
   41986 
   41987 /*
   41988 ** Attempt to set the maximum database page count if mxPage is positive.
   41989 ** Make no changes if mxPage is zero or negative.  And never reduce the
   41990 ** maximum page count below the current size of the database.
   41991 **
   41992 ** Regardless of mxPage, return the current maximum page count.
   41993 */
   41994 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   41995   if( mxPage>0 ){
   41996     pPager->mxPgno = mxPage;
   41997   }
   41998   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   41999   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   42000   return pPager->mxPgno;
   42001 }
   42002 
   42003 /*
   42004 ** The following set of routines are used to disable the simulated
   42005 ** I/O error mechanism.  These routines are used to avoid simulated
   42006 ** errors in places where we do not care about errors.
   42007 **
   42008 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   42009 ** and generate no code.
   42010 */
   42011 #ifdef SQLITE_TEST
   42012 SQLITE_API extern int sqlite3_io_error_pending;
   42013 SQLITE_API extern int sqlite3_io_error_hit;
   42014 static int saved_cnt;
   42015 void disable_simulated_io_errors(void){
   42016   saved_cnt = sqlite3_io_error_pending;
   42017   sqlite3_io_error_pending = -1;
   42018 }
   42019 void enable_simulated_io_errors(void){
   42020   sqlite3_io_error_pending = saved_cnt;
   42021 }
   42022 #else
   42023 # define disable_simulated_io_errors()
   42024 # define enable_simulated_io_errors()
   42025 #endif
   42026 
   42027 /*
   42028 ** Read the first N bytes from the beginning of the file into memory
   42029 ** that pDest points to.
   42030 **
   42031 ** If the pager was opened on a transient file (zFilename==""), or
   42032 ** opened on a file less than N bytes in size, the output buffer is
   42033 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   42034 ** function is used to read database headers, and a new transient or
   42035 ** zero sized database has a header than consists entirely of zeroes.
   42036 **
   42037 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   42038 ** the error code is returned to the caller and the contents of the
   42039 ** output buffer undefined.
   42040 */
   42041 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   42042   int rc = SQLITE_OK;
   42043   memset(pDest, 0, N);
   42044   assert( isOpen(pPager->fd) || pPager->tempFile );
   42045 
   42046   /* This routine is only called by btree immediately after creating
   42047   ** the Pager object.  There has not been an opportunity to transition
   42048   ** to WAL mode yet.
   42049   */
   42050   assert( !pagerUseWal(pPager) );
   42051 
   42052   if( isOpen(pPager->fd) ){
   42053     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   42054     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   42055     if( rc==SQLITE_IOERR_SHORT_READ ){
   42056       rc = SQLITE_OK;
   42057     }
   42058   }
   42059   return rc;
   42060 }
   42061 
   42062 /*
   42063 ** This function may only be called when a read-transaction is open on
   42064 ** the pager. It returns the total number of pages in the database.
   42065 **
   42066 ** However, if the file is between 1 and <page-size> bytes in size, then
   42067 ** this is considered a 1 page file.
   42068 */
   42069 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   42070   assert( pPager->eState>=PAGER_READER );
   42071   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   42072   *pnPage = (int)pPager->dbSize;
   42073 }
   42074 
   42075 
   42076 /*
   42077 ** Try to obtain a lock of type locktype on the database file. If
   42078 ** a similar or greater lock is already held, this function is a no-op
   42079 ** (returning SQLITE_OK immediately).
   42080 **
   42081 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   42082 ** the busy callback if the lock is currently not available. Repeat
   42083 ** until the busy callback returns false or until the attempt to
   42084 ** obtain the lock succeeds.
   42085 **
   42086 ** Return SQLITE_OK on success and an error code if we cannot obtain
   42087 ** the lock. If the lock is obtained successfully, set the Pager.state
   42088 ** variable to locktype before returning.
   42089 */
   42090 static int pager_wait_on_lock(Pager *pPager, int locktype){
   42091   int rc;                              /* Return code */
   42092 
   42093   /* Check that this is either a no-op (because the requested lock is
   42094   ** already held, or one of the transistions that the busy-handler
   42095   ** may be invoked during, according to the comment above
   42096   ** sqlite3PagerSetBusyhandler().
   42097   */
   42098   assert( (pPager->eLock>=locktype)
   42099        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   42100        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   42101   );
   42102 
   42103   do {
   42104     rc = pagerLockDb(pPager, locktype);
   42105   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   42106   return rc;
   42107 }
   42108 
   42109 /*
   42110 ** Function assertTruncateConstraint(pPager) checks that one of the
   42111 ** following is true for all dirty pages currently in the page-cache:
   42112 **
   42113 **   a) The page number is less than or equal to the size of the
   42114 **      current database image, in pages, OR
   42115 **
   42116 **   b) if the page content were written at this time, it would not
   42117 **      be necessary to write the current content out to the sub-journal
   42118 **      (as determined by function subjRequiresPage()).
   42119 **
   42120 ** If the condition asserted by this function were not true, and the
   42121 ** dirty page were to be discarded from the cache via the pagerStress()
   42122 ** routine, pagerStress() would not write the current page content to
   42123 ** the database file. If a savepoint transaction were rolled back after
   42124 ** this happened, the correct behaviour would be to restore the current
   42125 ** content of the page. However, since this content is not present in either
   42126 ** the database file or the portion of the rollback journal and
   42127 ** sub-journal rolled back the content could not be restored and the
   42128 ** database image would become corrupt. It is therefore fortunate that
   42129 ** this circumstance cannot arise.
   42130 */
   42131 #if defined(SQLITE_DEBUG)
   42132 static void assertTruncateConstraintCb(PgHdr *pPg){
   42133   assert( pPg->flags&PGHDR_DIRTY );
   42134   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   42135 }
   42136 static void assertTruncateConstraint(Pager *pPager){
   42137   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   42138 }
   42139 #else
   42140 # define assertTruncateConstraint(pPager)
   42141 #endif
   42142 
   42143 /*
   42144 ** Truncate the in-memory database file image to nPage pages. This
   42145 ** function does not actually modify the database file on disk. It
   42146 ** just sets the internal state of the pager object so that the
   42147 ** truncation will be done when the current transaction is committed.
   42148 */
   42149 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   42150   assert( pPager->dbSize>=nPage );
   42151   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   42152   pPager->dbSize = nPage;
   42153   assertTruncateConstraint(pPager);
   42154 }
   42155 
   42156 
   42157 /*
   42158 ** This function is called before attempting a hot-journal rollback. It
   42159 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   42160 ** size of the journal file so that the pager_playback() routine knows
   42161 ** that the entire journal file has been synced.
   42162 **
   42163 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   42164 ** that if a power-failure occurs during the rollback, the process that
   42165 ** attempts rollback following system recovery sees the same journal
   42166 ** content as this process.
   42167 **
   42168 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   42169 ** an SQLite error code.
   42170 */
   42171 static int pagerSyncHotJournal(Pager *pPager){
   42172   int rc = SQLITE_OK;
   42173   if( !pPager->noSync ){
   42174     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   42175   }
   42176   if( rc==SQLITE_OK ){
   42177     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   42178   }
   42179   return rc;
   42180 }
   42181 
   42182 /*
   42183 ** Shutdown the page cache.  Free all memory and close all files.
   42184 **
   42185 ** If a transaction was in progress when this routine is called, that
   42186 ** transaction is rolled back.  All outstanding pages are invalidated
   42187 ** and their memory is freed.  Any attempt to use a page associated
   42188 ** with this page cache after this function returns will likely
   42189 ** result in a coredump.
   42190 **
   42191 ** This function always succeeds. If a transaction is active an attempt
   42192 ** is made to roll it back. If an error occurs during the rollback
   42193 ** a hot journal may be left in the filesystem but no error is returned
   42194 ** to the caller.
   42195 */
   42196 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   42197   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   42198 
   42199   assert( assert_pager_state(pPager) );
   42200   disable_simulated_io_errors();
   42201   sqlite3BeginBenignMalloc();
   42202   /* pPager->errCode = 0; */
   42203   pPager->exclusiveMode = 0;
   42204 #ifndef SQLITE_OMIT_WAL
   42205   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
   42206   pPager->pWal = 0;
   42207 #endif
   42208   pager_reset(pPager);
   42209   if( MEMDB ){
   42210     pager_unlock(pPager);
   42211   }else{
   42212     /* If it is open, sync the journal file before calling UnlockAndRollback.
   42213     ** If this is not done, then an unsynced portion of the open journal
   42214     ** file may be played back into the database. If a power failure occurs
   42215     ** while this is happening, the database could become corrupt.
   42216     **
   42217     ** If an error occurs while trying to sync the journal, shift the pager
   42218     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   42219     ** database and close the journal file without attempting to roll it
   42220     ** back or finalize it. The next database user will have to do hot-journal
   42221     ** rollback before accessing the database file.
   42222     */
   42223     if( isOpen(pPager->jfd) ){
   42224       pager_error(pPager, pagerSyncHotJournal(pPager));
   42225     }
   42226     pagerUnlockAndRollback(pPager);
   42227   }
   42228   sqlite3EndBenignMalloc();
   42229   enable_simulated_io_errors();
   42230   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   42231   IOTRACE(("CLOSE %p\n", pPager))
   42232   sqlite3OsClose(pPager->jfd);
   42233   sqlite3OsClose(pPager->fd);
   42234   sqlite3PageFree(pTmp);
   42235   sqlite3PcacheClose(pPager->pPCache);
   42236 
   42237 #ifdef SQLITE_HAS_CODEC
   42238   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   42239 #endif
   42240 
   42241   assert( !pPager->aSavepoint && !pPager->pInJournal );
   42242   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   42243 
   42244   sqlite3_free(pPager);
   42245   return SQLITE_OK;
   42246 }
   42247 
   42248 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   42249 /*
   42250 ** Return the page number for page pPg.
   42251 */
   42252 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   42253   return pPg->pgno;
   42254 }
   42255 #endif
   42256 
   42257 /*
   42258 ** Increment the reference count for page pPg.
   42259 */
   42260 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   42261   sqlite3PcacheRef(pPg);
   42262 }
   42263 
   42264 /*
   42265 ** Sync the journal. In other words, make sure all the pages that have
   42266 ** been written to the journal have actually reached the surface of the
   42267 ** disk and can be restored in the event of a hot-journal rollback.
   42268 **
   42269 ** If the Pager.noSync flag is set, then this function is a no-op.
   42270 ** Otherwise, the actions required depend on the journal-mode and the
   42271 ** device characteristics of the the file-system, as follows:
   42272 **
   42273 **   * If the journal file is an in-memory journal file, no action need
   42274 **     be taken.
   42275 **
   42276 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   42277 **     then the nRec field of the most recently written journal header
   42278 **     is updated to contain the number of journal records that have
   42279 **     been written following it. If the pager is operating in full-sync
   42280 **     mode, then the journal file is synced before this field is updated.
   42281 **
   42282 **   * If the device does not support the SEQUENTIAL property, then
   42283 **     journal file is synced.
   42284 **
   42285 ** Or, in pseudo-code:
   42286 **
   42287 **   if( NOT <in-memory journal> ){
   42288 **     if( NOT SAFE_APPEND ){
   42289 **       if( <full-sync mode> ) xSync(<journal file>);
   42290 **       <update nRec field>
   42291 **     }
   42292 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   42293 **   }
   42294 **
   42295 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   42296 ** page currently held in memory before returning SQLITE_OK. If an IO
   42297 ** error is encountered, then the IO error code is returned to the caller.
   42298 */
   42299 static int syncJournal(Pager *pPager, int newHdr){
   42300   int rc;                         /* Return code */
   42301 
   42302   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   42303        || pPager->eState==PAGER_WRITER_DBMOD
   42304   );
   42305   assert( assert_pager_state(pPager) );
   42306   assert( !pagerUseWal(pPager) );
   42307 
   42308   rc = sqlite3PagerExclusiveLock(pPager);
   42309   if( rc!=SQLITE_OK ) return rc;
   42310 
   42311   if( !pPager->noSync ){
   42312     assert( !pPager->tempFile );
   42313     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   42314       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   42315       assert( isOpen(pPager->jfd) );
   42316 
   42317       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   42318         /* This block deals with an obscure problem. If the last connection
   42319         ** that wrote to this database was operating in persistent-journal
   42320         ** mode, then the journal file may at this point actually be larger
   42321         ** than Pager.journalOff bytes. If the next thing in the journal
   42322         ** file happens to be a journal-header (written as part of the
   42323         ** previous connection's transaction), and a crash or power-failure
   42324         ** occurs after nRec is updated but before this connection writes
   42325         ** anything else to the journal file (or commits/rolls back its
   42326         ** transaction), then SQLite may become confused when doing the
   42327         ** hot-journal rollback following recovery. It may roll back all
   42328         ** of this connections data, then proceed to rolling back the old,
   42329         ** out-of-date data that follows it. Database corruption.
   42330         **
   42331         ** To work around this, if the journal file does appear to contain
   42332         ** a valid header following Pager.journalOff, then write a 0x00
   42333         ** byte to the start of it to prevent it from being recognized.
   42334         **
   42335         ** Variable iNextHdrOffset is set to the offset at which this
   42336         ** problematic header will occur, if it exists. aMagic is used
   42337         ** as a temporary buffer to inspect the first couple of bytes of
   42338         ** the potential journal header.
   42339         */
   42340         i64 iNextHdrOffset;
   42341         u8 aMagic[8];
   42342         u8 zHeader[sizeof(aJournalMagic)+4];
   42343 
   42344         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   42345         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   42346 
   42347         iNextHdrOffset = journalHdrOffset(pPager);
   42348         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   42349         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   42350           static const u8 zerobyte = 0;
   42351           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   42352         }
   42353         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   42354           return rc;
   42355         }
   42356 
   42357         /* Write the nRec value into the journal file header. If in
   42358         ** full-synchronous mode, sync the journal first. This ensures that
   42359         ** all data has really hit the disk before nRec is updated to mark
   42360         ** it as a candidate for rollback.
   42361         **
   42362         ** This is not required if the persistent media supports the
   42363         ** SAFE_APPEND property. Because in this case it is not possible
   42364         ** for garbage data to be appended to the file, the nRec field
   42365         ** is populated with 0xFFFFFFFF when the journal header is written
   42366         ** and never needs to be updated.
   42367         */
   42368         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   42369           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   42370           IOTRACE(("JSYNC %p\n", pPager))
   42371           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   42372           if( rc!=SQLITE_OK ) return rc;
   42373         }
   42374         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   42375         rc = sqlite3OsWrite(
   42376             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   42377         );
   42378         if( rc!=SQLITE_OK ) return rc;
   42379       }
   42380       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   42381         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   42382         IOTRACE(("JSYNC %p\n", pPager))
   42383         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   42384           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   42385         );
   42386         if( rc!=SQLITE_OK ) return rc;
   42387       }
   42388 
   42389       pPager->journalHdr = pPager->journalOff;
   42390       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   42391         pPager->nRec = 0;
   42392         rc = writeJournalHdr(pPager);
   42393         if( rc!=SQLITE_OK ) return rc;
   42394       }
   42395     }else{
   42396       pPager->journalHdr = pPager->journalOff;
   42397     }
   42398   }
   42399 
   42400   /* Unless the pager is in noSync mode, the journal file was just
   42401   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   42402   ** all pages.
   42403   */
   42404   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   42405   pPager->eState = PAGER_WRITER_DBMOD;
   42406   assert( assert_pager_state(pPager) );
   42407   return SQLITE_OK;
   42408 }
   42409 
   42410 /*
   42411 ** The argument is the first in a linked list of dirty pages connected
   42412 ** by the PgHdr.pDirty pointer. This function writes each one of the
   42413 ** in-memory pages in the list to the database file. The argument may
   42414 ** be NULL, representing an empty list. In this case this function is
   42415 ** a no-op.
   42416 **
   42417 ** The pager must hold at least a RESERVED lock when this function
   42418 ** is called. Before writing anything to the database file, this lock
   42419 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   42420 ** SQLITE_BUSY is returned and no data is written to the database file.
   42421 **
   42422 ** If the pager is a temp-file pager and the actual file-system file
   42423 ** is not yet open, it is created and opened before any data is
   42424 ** written out.
   42425 **
   42426 ** Once the lock has been upgraded and, if necessary, the file opened,
   42427 ** the pages are written out to the database file in list order. Writing
   42428 ** a page is skipped if it meets either of the following criteria:
   42429 **
   42430 **   * The page number is greater than Pager.dbSize, or
   42431 **   * The PGHDR_DONT_WRITE flag is set on the page.
   42432 **
   42433 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   42434 ** is updated accordingly. If page 1 is written out, then the value cached
   42435 ** in Pager.dbFileVers[] is updated to match the new value stored in
   42436 ** the database file.
   42437 **
   42438 ** If everything is successful, SQLITE_OK is returned. If an IO error
   42439 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   42440 ** be obtained, SQLITE_BUSY is returned.
   42441 */
   42442 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   42443   int rc = SQLITE_OK;                  /* Return code */
   42444 
   42445   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   42446   assert( !pagerUseWal(pPager) );
   42447   assert( pPager->eState==PAGER_WRITER_DBMOD );
   42448   assert( pPager->eLock==EXCLUSIVE_LOCK );
   42449 
   42450   /* If the file is a temp-file has not yet been opened, open it now. It
   42451   ** is not possible for rc to be other than SQLITE_OK if this branch
   42452   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   42453   */
   42454   if( !isOpen(pPager->fd) ){
   42455     assert( pPager->tempFile && rc==SQLITE_OK );
   42456     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   42457   }
   42458 
   42459   /* Before the first write, give the VFS a hint of what the final
   42460   ** file size will be.
   42461   */
   42462   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   42463   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
   42464     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   42465     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   42466     pPager->dbHintSize = pPager->dbSize;
   42467   }
   42468 
   42469   while( rc==SQLITE_OK && pList ){
   42470     Pgno pgno = pList->pgno;
   42471 
   42472     /* If there are dirty pages in the page cache with page numbers greater
   42473     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   42474     ** make the file smaller (presumably by auto-vacuum code). Do not write
   42475     ** any such pages to the file.
   42476     **
   42477     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   42478     ** set (set by sqlite3PagerDontWrite()).
   42479     */
   42480     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   42481       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   42482       char *pData;                                   /* Data to write */
   42483 
   42484       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   42485       if( pList->pgno==1 ) pager_write_changecounter(pList);
   42486 
   42487       /* Encode the database */
   42488       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   42489 
   42490       /* Write out the page data. */
   42491       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   42492 
   42493       /* If page 1 was just written, update Pager.dbFileVers to match
   42494       ** the value now stored in the database file. If writing this
   42495       ** page caused the database file to grow, update dbFileSize.
   42496       */
   42497       if( pgno==1 ){
   42498         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   42499       }
   42500       if( pgno>pPager->dbFileSize ){
   42501         pPager->dbFileSize = pgno;
   42502       }
   42503 
   42504       /* Update any backup objects copying the contents of this pager. */
   42505       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   42506 
   42507       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   42508                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   42509       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   42510       PAGER_INCR(sqlite3_pager_writedb_count);
   42511       PAGER_INCR(pPager->nWrite);
   42512     }else{
   42513       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   42514     }
   42515     pager_set_pagehash(pList);
   42516     pList = pList->pDirty;
   42517   }
   42518 
   42519   return rc;
   42520 }
   42521 
   42522 /*
   42523 ** Ensure that the sub-journal file is open. If it is already open, this
   42524 ** function is a no-op.
   42525 **
   42526 ** SQLITE_OK is returned if everything goes according to plan. An
   42527 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   42528 ** fails.
   42529 */
   42530 static int openSubJournal(Pager *pPager){
   42531   int rc = SQLITE_OK;
   42532   if( !isOpen(pPager->sjfd) ){
   42533     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   42534       sqlite3MemJournalOpen(pPager->sjfd);
   42535     }else{
   42536       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   42537     }
   42538   }
   42539   return rc;
   42540 }
   42541 
   42542 /*
   42543 ** Append a record of the current state of page pPg to the sub-journal.
   42544 ** It is the callers responsibility to use subjRequiresPage() to check
   42545 ** that it is really required before calling this function.
   42546 **
   42547 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   42548 ** for all open savepoints before returning.
   42549 **
   42550 ** This function returns SQLITE_OK if everything is successful, an IO
   42551 ** error code if the attempt to write to the sub-journal fails, or
   42552 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   42553 ** bitvec.
   42554 */
   42555 static int subjournalPage(PgHdr *pPg){
   42556   int rc = SQLITE_OK;
   42557   Pager *pPager = pPg->pPager;
   42558   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   42559 
   42560     /* Open the sub-journal, if it has not already been opened */
   42561     assert( pPager->useJournal );
   42562     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   42563     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   42564     assert( pagerUseWal(pPager)
   42565          || pageInJournal(pPg)
   42566          || pPg->pgno>pPager->dbOrigSize
   42567     );
   42568     rc = openSubJournal(pPager);
   42569 
   42570     /* If the sub-journal was opened successfully (or was already open),
   42571     ** write the journal record into the file.  */
   42572     if( rc==SQLITE_OK ){
   42573       void *pData = pPg->pData;
   42574       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
   42575       char *pData2;
   42576 
   42577       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   42578       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   42579       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   42580       if( rc==SQLITE_OK ){
   42581         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   42582       }
   42583     }
   42584   }
   42585   if( rc==SQLITE_OK ){
   42586     pPager->nSubRec++;
   42587     assert( pPager->nSavepoint>0 );
   42588     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   42589   }
   42590   return rc;
   42591 }
   42592 
   42593 /*
   42594 ** This function is called by the pcache layer when it has reached some
   42595 ** soft memory limit. The first argument is a pointer to a Pager object
   42596 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   42597 ** database). The second argument is a reference to a page that is
   42598 ** currently dirty but has no outstanding references. The page
   42599 ** is always associated with the Pager object passed as the first
   42600 ** argument.
   42601 **
   42602 ** The job of this function is to make pPg clean by writing its contents
   42603 ** out to the database file, if possible. This may involve syncing the
   42604 ** journal file.
   42605 **
   42606 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   42607 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   42608 ** page clean, the IO error code is returned. If the page cannot be
   42609 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   42610 ** is returned by sqlite3PcacheMakeClean() is not called.
   42611 */
   42612 static int pagerStress(void *p, PgHdr *pPg){
   42613   Pager *pPager = (Pager *)p;
   42614   int rc = SQLITE_OK;
   42615 
   42616   assert( pPg->pPager==pPager );
   42617   assert( pPg->flags&PGHDR_DIRTY );
   42618 
   42619   /* The doNotSyncSpill flag is set during times when doing a sync of
   42620   ** journal (and adding a new header) is not allowed.  This occurs
   42621   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   42622   ** pages belonging to the same sector.
   42623   **
   42624   ** The doNotSpill flag inhibits all cache spilling regardless of whether
   42625   ** or not a sync is required.  This is set during a rollback.
   42626   **
   42627   ** Spilling is also prohibited when in an error state since that could
   42628   ** lead to database corruption.   In the current implementaton it
   42629   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
   42630   ** while in the error state, hence it is impossible for this routine to
   42631   ** be called in the error state.  Nevertheless, we include a NEVER()
   42632   ** test for the error state as a safeguard against future changes.
   42633   */
   42634   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   42635   if( pPager->doNotSpill ) return SQLITE_OK;
   42636   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
   42637     return SQLITE_OK;
   42638   }
   42639 
   42640   pPg->pDirty = 0;
   42641   if( pagerUseWal(pPager) ){
   42642     /* Write a single frame for this page to the log. */
   42643     if( subjRequiresPage(pPg) ){
   42644       rc = subjournalPage(pPg);
   42645     }
   42646     if( rc==SQLITE_OK ){
   42647       rc = pagerWalFrames(pPager, pPg, 0, 0);
   42648     }
   42649   }else{
   42650 
   42651     /* Sync the journal file if required. */
   42652     if( pPg->flags&PGHDR_NEED_SYNC
   42653      || pPager->eState==PAGER_WRITER_CACHEMOD
   42654     ){
   42655       rc = syncJournal(pPager, 1);
   42656     }
   42657 
   42658     /* If the page number of this page is larger than the current size of
   42659     ** the database image, it may need to be written to the sub-journal.
   42660     ** This is because the call to pager_write_pagelist() below will not
   42661     ** actually write data to the file in this case.
   42662     **
   42663     ** Consider the following sequence of events:
   42664     **
   42665     **   BEGIN;
   42666     **     <journal page X>
   42667     **     <modify page X>
   42668     **     SAVEPOINT sp;
   42669     **       <shrink database file to Y pages>
   42670     **       pagerStress(page X)
   42671     **     ROLLBACK TO sp;
   42672     **
   42673     ** If (X>Y), then when pagerStress is called page X will not be written
   42674     ** out to the database file, but will be dropped from the cache. Then,
   42675     ** following the "ROLLBACK TO sp" statement, reading page X will read
   42676     ** data from the database file. This will be the copy of page X as it
   42677     ** was when the transaction started, not as it was when "SAVEPOINT sp"
   42678     ** was executed.
   42679     **
   42680     ** The solution is to write the current data for page X into the
   42681     ** sub-journal file now (if it is not already there), so that it will
   42682     ** be restored to its current value when the "ROLLBACK TO sp" is
   42683     ** executed.
   42684     */
   42685     if( NEVER(
   42686         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   42687     ) ){
   42688       rc = subjournalPage(pPg);
   42689     }
   42690 
   42691     /* Write the contents of the page out to the database file. */
   42692     if( rc==SQLITE_OK ){
   42693       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   42694       rc = pager_write_pagelist(pPager, pPg);
   42695     }
   42696   }
   42697 
   42698   /* Mark the page as clean. */
   42699   if( rc==SQLITE_OK ){
   42700     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   42701     sqlite3PcacheMakeClean(pPg);
   42702   }
   42703 
   42704   return pager_error(pPager, rc);
   42705 }
   42706 
   42707 
   42708 /*
   42709 ** Allocate and initialize a new Pager object and put a pointer to it
   42710 ** in *ppPager. The pager should eventually be freed by passing it
   42711 ** to sqlite3PagerClose().
   42712 **
   42713 ** The zFilename argument is the path to the database file to open.
   42714 ** If zFilename is NULL then a randomly-named temporary file is created
   42715 ** and used as the file to be cached. Temporary files are be deleted
   42716 ** automatically when they are closed. If zFilename is ":memory:" then
   42717 ** all information is held in cache. It is never written to disk.
   42718 ** This can be used to implement an in-memory database.
   42719 **
   42720 ** The nExtra parameter specifies the number of bytes of space allocated
   42721 ** along with each page reference. This space is available to the user
   42722 ** via the sqlite3PagerGetExtra() API.
   42723 **
   42724 ** The flags argument is used to specify properties that affect the
   42725 ** operation of the pager. It should be passed some bitwise combination
   42726 ** of the PAGER_* flags.
   42727 **
   42728 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   42729 ** of the xOpen() method of the supplied VFS when opening files.
   42730 **
   42731 ** If the pager object is allocated and the specified file opened
   42732 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   42733 ** the new pager object. If an error occurs, *ppPager is set to NULL
   42734 ** and error code returned. This function may return SQLITE_NOMEM
   42735 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   42736 ** various SQLITE_IO_XXX errors.
   42737 */
   42738 SQLITE_PRIVATE int sqlite3PagerOpen(
   42739   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   42740   Pager **ppPager,         /* OUT: Return the Pager structure here */
   42741   const char *zFilename,   /* Name of the database file to open */
   42742   int nExtra,              /* Extra bytes append to each in-memory page */
   42743   int flags,               /* flags controlling this file */
   42744   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   42745   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   42746 ){
   42747   u8 *pPtr;
   42748   Pager *pPager = 0;       /* Pager object to allocate and return */
   42749   int rc = SQLITE_OK;      /* Return code */
   42750   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   42751   int memDb = 0;           /* True if this is an in-memory file */
   42752   int readOnly = 0;        /* True if this is a read-only file */
   42753   int journalFileSize;     /* Bytes to allocate for each journal fd */
   42754   char *zPathname = 0;     /* Full path to database file */
   42755   int nPathname = 0;       /* Number of bytes in zPathname */
   42756   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   42757   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   42758   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   42759   const char *zUri = 0;    /* URI args to copy */
   42760   int nUri = 0;            /* Number of bytes of URI args at *zUri */
   42761 
   42762   /* Figure out how much space is required for each journal file-handle
   42763   ** (there are two of them, the main journal and the sub-journal). This
   42764   ** is the maximum space required for an in-memory journal file handle
   42765   ** and a regular journal file-handle. Note that a "regular journal-handle"
   42766   ** may be a wrapper capable of caching the first portion of the journal
   42767   ** file in memory to implement the atomic-write optimization (see
   42768   ** source file journal.c).
   42769   */
   42770   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   42771     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   42772   }else{
   42773     journalFileSize = ROUND8(sqlite3MemJournalSize());
   42774   }
   42775 
   42776   /* Set the output variable to NULL in case an error occurs. */
   42777   *ppPager = 0;
   42778 
   42779 #ifndef SQLITE_OMIT_MEMORYDB
   42780   if( flags & PAGER_MEMORY ){
   42781     memDb = 1;
   42782     zFilename = 0;
   42783   }
   42784 #endif
   42785 
   42786   /* Compute and store the full pathname in an allocated buffer pointed
   42787   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   42788   ** leave both nPathname and zPathname set to 0.
   42789   */
   42790   if( zFilename && zFilename[0] ){
   42791     const char *z;
   42792     nPathname = pVfs->mxPathname+1;
   42793     zPathname = sqlite3Malloc(nPathname*2);
   42794     if( zPathname==0 ){
   42795       return SQLITE_NOMEM;
   42796     }
   42797     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   42798     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   42799     nPathname = sqlite3Strlen30(zPathname);
   42800     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
   42801     while( *z ){
   42802       z += sqlite3Strlen30(z)+1;
   42803       z += sqlite3Strlen30(z)+1;
   42804     }
   42805     nUri = (int)(&z[1] - zUri);
   42806     assert( nUri>=0 );
   42807     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   42808       /* This branch is taken when the journal path required by
   42809       ** the database being opened will be more than pVfs->mxPathname
   42810       ** bytes in length. This means the database cannot be opened,
   42811       ** as it will not be possible to open the journal file or even
   42812       ** check for a hot-journal before reading.
   42813       */
   42814       rc = SQLITE_CANTOPEN_BKPT;
   42815     }
   42816     if( rc!=SQLITE_OK ){
   42817       sqlite3_free(zPathname);
   42818       return rc;
   42819     }
   42820   }
   42821 
   42822   /* Allocate memory for the Pager structure, PCache object, the
   42823   ** three file descriptors, the database file name and the journal
   42824   ** file name. The layout in memory is as follows:
   42825   **
   42826   **     Pager object                    (sizeof(Pager) bytes)
   42827   **     PCache object                   (sqlite3PcacheSize() bytes)
   42828   **     Database file handle            (pVfs->szOsFile bytes)
   42829   **     Sub-journal file handle         (journalFileSize bytes)
   42830   **     Main journal file handle        (journalFileSize bytes)
   42831   **     Database file name              (nPathname+1 bytes)
   42832   **     Journal file name               (nPathname+8+1 bytes)
   42833   */
   42834   pPtr = (u8 *)sqlite3MallocZero(
   42835     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   42836     ROUND8(pcacheSize) +           /* PCache object */
   42837     ROUND8(pVfs->szOsFile) +       /* The main db file */
   42838     journalFileSize * 2 +          /* The two journal files */
   42839     nPathname + 1 + nUri +         /* zFilename */
   42840     nPathname + 8 + 2              /* zJournal */
   42841 #ifndef SQLITE_OMIT_WAL
   42842     + nPathname + 4 + 2            /* zWal */
   42843 #endif
   42844   );
   42845   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   42846   if( !pPtr ){
   42847     sqlite3_free(zPathname);
   42848     return SQLITE_NOMEM;
   42849   }
   42850   pPager =              (Pager*)(pPtr);
   42851   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   42852   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   42853   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   42854   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   42855   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   42856   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   42857 
   42858   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   42859   if( zPathname ){
   42860     assert( nPathname>0 );
   42861     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
   42862     memcpy(pPager->zFilename, zPathname, nPathname);
   42863     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
   42864     memcpy(pPager->zJournal, zPathname, nPathname);
   42865     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
   42866     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
   42867 #ifndef SQLITE_OMIT_WAL
   42868     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   42869     memcpy(pPager->zWal, zPathname, nPathname);
   42870     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
   42871     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
   42872 #endif
   42873     sqlite3_free(zPathname);
   42874   }
   42875   pPager->pVfs = pVfs;
   42876   pPager->vfsFlags = vfsFlags;
   42877 
   42878   /* Open the pager file.
   42879   */
   42880   if( zFilename && zFilename[0] ){
   42881     int fout = 0;                    /* VFS flags returned by xOpen() */
   42882     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   42883     assert( !memDb );
   42884     readOnly = (fout&SQLITE_OPEN_READONLY);
   42885 
   42886     /* If the file was successfully opened for read/write access,
   42887     ** choose a default page size in case we have to create the
   42888     ** database file. The default page size is the maximum of:
   42889     **
   42890     **    + SQLITE_DEFAULT_PAGE_SIZE,
   42891     **    + The value returned by sqlite3OsSectorSize()
   42892     **    + The largest page size that can be written atomically.
   42893     */
   42894     if( rc==SQLITE_OK && !readOnly ){
   42895       setSectorSize(pPager);
   42896       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   42897       if( szPageDflt<pPager->sectorSize ){
   42898         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   42899           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   42900         }else{
   42901           szPageDflt = (u32)pPager->sectorSize;
   42902         }
   42903       }
   42904 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   42905       {
   42906         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   42907         int ii;
   42908         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   42909         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   42910         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   42911         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   42912           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   42913             szPageDflt = ii;
   42914           }
   42915         }
   42916       }
   42917 #endif
   42918     }
   42919   }else{
   42920     /* If a temporary file is requested, it is not opened immediately.
   42921     ** In this case we accept the default page size and delay actually
   42922     ** opening the file until the first call to OsWrite().
   42923     **
   42924     ** This branch is also run for an in-memory database. An in-memory
   42925     ** database is the same as a temp-file that is never written out to
   42926     ** disk and uses an in-memory rollback journal.
   42927     */
   42928     tempFile = 1;
   42929     pPager->eState = PAGER_READER;
   42930     pPager->eLock = EXCLUSIVE_LOCK;
   42931     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   42932   }
   42933 
   42934   /* The following call to PagerSetPagesize() serves to set the value of
   42935   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   42936   */
   42937   if( rc==SQLITE_OK ){
   42938     assert( pPager->memDb==0 );
   42939     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   42940     testcase( rc!=SQLITE_OK );
   42941   }
   42942 
   42943   /* If an error occurred in either of the blocks above, free the
   42944   ** Pager structure and close the file.
   42945   */
   42946   if( rc!=SQLITE_OK ){
   42947     assert( !pPager->pTmpSpace );
   42948     sqlite3OsClose(pPager->fd);
   42949     sqlite3_free(pPager);
   42950     return rc;
   42951   }
   42952 
   42953   /* Initialize the PCache object. */
   42954   assert( nExtra<1000 );
   42955   nExtra = ROUND8(nExtra);
   42956   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   42957                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   42958 
   42959   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   42960   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   42961 
   42962   pPager->useJournal = (u8)useJournal;
   42963   /* pPager->stmtOpen = 0; */
   42964   /* pPager->stmtInUse = 0; */
   42965   /* pPager->nRef = 0; */
   42966   /* pPager->stmtSize = 0; */
   42967   /* pPager->stmtJSize = 0; */
   42968   /* pPager->nPage = 0; */
   42969   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   42970   /* pPager->state = PAGER_UNLOCK; */
   42971 #if 0
   42972   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
   42973 #endif
   42974   /* pPager->errMask = 0; */
   42975   pPager->tempFile = (u8)tempFile;
   42976   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   42977           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   42978   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   42979   pPager->exclusiveMode = (u8)tempFile;
   42980   pPager->changeCountDone = pPager->tempFile;
   42981   pPager->memDb = (u8)memDb;
   42982   pPager->readOnly = (u8)readOnly;
   42983   assert( useJournal || pPager->tempFile );
   42984   pPager->noSync = pPager->tempFile;
   42985   if( pPager->noSync ){
   42986     assert( pPager->fullSync==0 );
   42987     assert( pPager->syncFlags==0 );
   42988     assert( pPager->walSyncFlags==0 );
   42989     assert( pPager->ckptSyncFlags==0 );
   42990   }else{
   42991     pPager->fullSync = 1;
   42992     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   42993     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
   42994     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   42995   }
   42996   /* pPager->pFirst = 0; */
   42997   /* pPager->pFirstSynced = 0; */
   42998   /* pPager->pLast = 0; */
   42999   pPager->nExtra = (u16)nExtra;
   43000   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   43001   assert( isOpen(pPager->fd) || tempFile );
   43002   setSectorSize(pPager);
   43003   if( !useJournal ){
   43004     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   43005   }else if( memDb ){
   43006     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   43007   }
   43008   /* pPager->xBusyHandler = 0; */
   43009   /* pPager->pBusyHandlerArg = 0; */
   43010   pPager->xReiniter = xReinit;
   43011   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   43012 
   43013   *ppPager = pPager;
   43014   return SQLITE_OK;
   43015 }
   43016 
   43017 
   43018 
   43019 /*
   43020 ** This function is called after transitioning from PAGER_UNLOCK to
   43021 ** PAGER_SHARED state. It tests if there is a hot journal present in
   43022 ** the file-system for the given pager. A hot journal is one that
   43023 ** needs to be played back. According to this function, a hot-journal
   43024 ** file exists if the following criteria are met:
   43025 **
   43026 **   * The journal file exists in the file system, and
   43027 **   * No process holds a RESERVED or greater lock on the database file, and
   43028 **   * The database file itself is greater than 0 bytes in size, and
   43029 **   * The first byte of the journal file exists and is not 0x00.
   43030 **
   43031 ** If the current size of the database file is 0 but a journal file
   43032 ** exists, that is probably an old journal left over from a prior
   43033 ** database with the same name. In this case the journal file is
   43034 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   43035 ** is returned.
   43036 **
   43037 ** This routine does not check if there is a master journal filename
   43038 ** at the end of the file. If there is, and that master journal file
   43039 ** does not exist, then the journal file is not really hot. In this
   43040 ** case this routine will return a false-positive. The pager_playback()
   43041 ** routine will discover that the journal file is not really hot and
   43042 ** will not roll it back.
   43043 **
   43044 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   43045 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   43046 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   43047 ** to determine whether or not a hot-journal file exists, the IO error
   43048 ** code is returned and the value of *pExists is undefined.
   43049 */
   43050 static int hasHotJournal(Pager *pPager, int *pExists){
   43051   sqlite3_vfs * const pVfs = pPager->pVfs;
   43052   int rc = SQLITE_OK;           /* Return code */
   43053   int exists = 1;               /* True if a journal file is present */
   43054   int jrnlOpen = !!isOpen(pPager->jfd);
   43055 
   43056   assert( pPager->useJournal );
   43057   assert( isOpen(pPager->fd) );
   43058   assert( pPager->eState==PAGER_OPEN );
   43059 
   43060   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   43061     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   43062   ));
   43063 
   43064   *pExists = 0;
   43065   if( !jrnlOpen ){
   43066     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   43067   }
   43068   if( rc==SQLITE_OK && exists ){
   43069     int locked = 0;             /* True if some process holds a RESERVED lock */
   43070 
   43071     /* Race condition here:  Another process might have been holding the
   43072     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   43073     ** call above, but then delete the journal and drop the lock before
   43074     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   43075     ** is the case, this routine might think there is a hot journal when
   43076     ** in fact there is none.  This results in a false-positive which will
   43077     ** be dealt with by the playback routine.  Ticket #3883.
   43078     */
   43079     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   43080     if( rc==SQLITE_OK && !locked ){
   43081       Pgno nPage;                 /* Number of pages in database file */
   43082 
   43083       /* Check the size of the database file. If it consists of 0 pages,
   43084       ** then delete the journal file. See the header comment above for
   43085       ** the reasoning here.  Delete the obsolete journal file under
   43086       ** a RESERVED lock to avoid race conditions and to avoid violating
   43087       ** [H33020].
   43088       */
   43089       rc = pagerPagecount(pPager, &nPage);
   43090       if( rc==SQLITE_OK ){
   43091         if( nPage==0 ){
   43092           sqlite3BeginBenignMalloc();
   43093           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   43094             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   43095             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   43096           }
   43097           sqlite3EndBenignMalloc();
   43098         }else{
   43099           /* The journal file exists and no other connection has a reserved
   43100           ** or greater lock on the database file. Now check that there is
   43101           ** at least one non-zero bytes at the start of the journal file.
   43102           ** If there is, then we consider this journal to be hot. If not,
   43103           ** it can be ignored.
   43104           */
   43105           if( !jrnlOpen ){
   43106             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   43107             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   43108           }
   43109           if( rc==SQLITE_OK ){
   43110             u8 first = 0;
   43111             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   43112             if( rc==SQLITE_IOERR_SHORT_READ ){
   43113               rc = SQLITE_OK;
   43114             }
   43115             if( !jrnlOpen ){
   43116               sqlite3OsClose(pPager->jfd);
   43117             }
   43118             *pExists = (first!=0);
   43119           }else if( rc==SQLITE_CANTOPEN ){
   43120             /* If we cannot open the rollback journal file in order to see if
   43121             ** its has a zero header, that might be due to an I/O error, or
   43122             ** it might be due to the race condition described above and in
   43123             ** ticket #3883.  Either way, assume that the journal is hot.
   43124             ** This might be a false positive.  But if it is, then the
   43125             ** automatic journal playback and recovery mechanism will deal
   43126             ** with it under an EXCLUSIVE lock where we do not need to
   43127             ** worry so much with race conditions.
   43128             */
   43129             *pExists = 1;
   43130             rc = SQLITE_OK;
   43131           }
   43132         }
   43133       }
   43134     }
   43135   }
   43136 
   43137   return rc;
   43138 }
   43139 
   43140 /*
   43141 ** This function is called to obtain a shared lock on the database file.
   43142 ** It is illegal to call sqlite3PagerAcquire() until after this function
   43143 ** has been successfully called. If a shared-lock is already held when
   43144 ** this function is called, it is a no-op.
   43145 **
   43146 ** The following operations are also performed by this function.
   43147 **
   43148 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   43149 **      on the database file), then an attempt is made to obtain a
   43150 **      SHARED lock on the database file. Immediately after obtaining
   43151 **      the SHARED lock, the file-system is checked for a hot-journal,
   43152 **      which is played back if present. Following any hot-journal
   43153 **      rollback, the contents of the cache are validated by checking
   43154 **      the 'change-counter' field of the database file header and
   43155 **      discarded if they are found to be invalid.
   43156 **
   43157 **   2) If the pager is running in exclusive-mode, and there are currently
   43158 **      no outstanding references to any pages, and is in the error state,
   43159 **      then an attempt is made to clear the error state by discarding
   43160 **      the contents of the page cache and rolling back any open journal
   43161 **      file.
   43162 **
   43163 ** If everything is successful, SQLITE_OK is returned. If an IO error
   43164 ** occurs while locking the database, checking for a hot-journal file or
   43165 ** rolling back a journal file, the IO error code is returned.
   43166 */
   43167 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   43168   int rc = SQLITE_OK;                /* Return code */
   43169 
   43170   /* This routine is only called from b-tree and only when there are no
   43171   ** outstanding pages. This implies that the pager state should either
   43172   ** be OPEN or READER. READER is only possible if the pager is or was in
   43173   ** exclusive access mode.
   43174   */
   43175   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   43176   assert( assert_pager_state(pPager) );
   43177   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   43178   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   43179 
   43180   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   43181     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   43182 
   43183     assert( !MEMDB );
   43184 
   43185     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   43186     if( rc!=SQLITE_OK ){
   43187       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   43188       goto failed;
   43189     }
   43190 
   43191     /* If a journal file exists, and there is no RESERVED lock on the
   43192     ** database file, then it either needs to be played back or deleted.
   43193     */
   43194     if( pPager->eLock<=SHARED_LOCK ){
   43195       rc = hasHotJournal(pPager, &bHotJournal);
   43196     }
   43197     if( rc!=SQLITE_OK ){
   43198       goto failed;
   43199     }
   43200     if( bHotJournal ){
   43201       /* Get an EXCLUSIVE lock on the database file. At this point it is
   43202       ** important that a RESERVED lock is not obtained on the way to the
   43203       ** EXCLUSIVE lock. If it were, another process might open the
   43204       ** database file, detect the RESERVED lock, and conclude that the
   43205       ** database is safe to read while this process is still rolling the
   43206       ** hot-journal back.
   43207       **
   43208       ** Because the intermediate RESERVED lock is not requested, any
   43209       ** other process attempting to access the database file will get to
   43210       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   43211       ** on the database file.
   43212       **
   43213       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   43214       ** downgraded to SHARED_LOCK before this function returns.
   43215       */
   43216       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   43217       if( rc!=SQLITE_OK ){
   43218         goto failed;
   43219       }
   43220 
   43221       /* If it is not already open and the file exists on disk, open the
   43222       ** journal for read/write access. Write access is required because
   43223       ** in exclusive-access mode the file descriptor will be kept open
   43224       ** and possibly used for a transaction later on. Also, write-access
   43225       ** is usually required to finalize the journal in journal_mode=persist
   43226       ** mode (and also for journal_mode=truncate on some systems).
   43227       **
   43228       ** If the journal does not exist, it usually means that some
   43229       ** other connection managed to get in and roll it back before
   43230       ** this connection obtained the exclusive lock above. Or, it
   43231       ** may mean that the pager was in the error-state when this
   43232       ** function was called and the journal file does not exist.
   43233       */
   43234       if( !isOpen(pPager->jfd) ){
   43235         sqlite3_vfs * const pVfs = pPager->pVfs;
   43236         int bExists;              /* True if journal file exists */
   43237         rc = sqlite3OsAccess(
   43238             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   43239         if( rc==SQLITE_OK && bExists ){
   43240           int fout = 0;
   43241           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   43242           assert( !pPager->tempFile );
   43243           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   43244           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   43245           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   43246             rc = SQLITE_CANTOPEN_BKPT;
   43247             sqlite3OsClose(pPager->jfd);
   43248           }
   43249         }
   43250       }
   43251 
   43252       /* Playback and delete the journal.  Drop the database write
   43253       ** lock and reacquire the read lock. Purge the cache before
   43254       ** playing back the hot-journal so that we don't end up with
   43255       ** an inconsistent cache.  Sync the hot journal before playing
   43256       ** it back since the process that crashed and left the hot journal
   43257       ** probably did not sync it and we are required to always sync
   43258       ** the journal before playing it back.
   43259       */
   43260       if( isOpen(pPager->jfd) ){
   43261         assert( rc==SQLITE_OK );
   43262         rc = pagerSyncHotJournal(pPager);
   43263         if( rc==SQLITE_OK ){
   43264           rc = pager_playback(pPager, 1);
   43265           pPager->eState = PAGER_OPEN;
   43266         }
   43267       }else if( !pPager->exclusiveMode ){
   43268         pagerUnlockDb(pPager, SHARED_LOCK);
   43269       }
   43270 
   43271       if( rc!=SQLITE_OK ){
   43272         /* This branch is taken if an error occurs while trying to open
   43273         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   43274         ** pager_unlock() routine will be called before returning to unlock
   43275         ** the file. If the unlock attempt fails, then Pager.eLock must be
   43276         ** set to UNKNOWN_LOCK (see the comment above the #define for
   43277         ** UNKNOWN_LOCK above for an explanation).
   43278         **
   43279         ** In order to get pager_unlock() to do this, set Pager.eState to
   43280         ** PAGER_ERROR now. This is not actually counted as a transition
   43281         ** to ERROR state in the state diagram at the top of this file,
   43282         ** since we know that the same call to pager_unlock() will very
   43283         ** shortly transition the pager object to the OPEN state. Calling
   43284         ** assert_pager_state() would fail now, as it should not be possible
   43285         ** to be in ERROR state when there are zero outstanding page
   43286         ** references.
   43287         */
   43288         pager_error(pPager, rc);
   43289         goto failed;
   43290       }
   43291 
   43292       assert( pPager->eState==PAGER_OPEN );
   43293       assert( (pPager->eLock==SHARED_LOCK)
   43294            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   43295       );
   43296     }
   43297 
   43298     if( !pPager->tempFile
   43299      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
   43300     ){
   43301       /* The shared-lock has just been acquired on the database file
   43302       ** and there are already pages in the cache (from a previous
   43303       ** read or write transaction).  Check to see if the database
   43304       ** has been modified.  If the database has changed, flush the
   43305       ** cache.
   43306       **
   43307       ** Database changes is detected by looking at 15 bytes beginning
   43308       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   43309       ** a 32-bit counter that is incremented with each change.  The
   43310       ** other bytes change randomly with each file change when
   43311       ** a codec is in use.
   43312       **
   43313       ** There is a vanishingly small chance that a change will not be
   43314       ** detected.  The chance of an undetected change is so small that
   43315       ** it can be neglected.
   43316       */
   43317       Pgno nPage = 0;
   43318       char dbFileVers[sizeof(pPager->dbFileVers)];
   43319 
   43320       rc = pagerPagecount(pPager, &nPage);
   43321       if( rc ) goto failed;
   43322 
   43323       if( nPage>0 ){
   43324         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   43325         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   43326         if( rc!=SQLITE_OK ){
   43327           goto failed;
   43328         }
   43329       }else{
   43330         memset(dbFileVers, 0, sizeof(dbFileVers));
   43331       }
   43332 
   43333       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   43334         pager_reset(pPager);
   43335       }
   43336     }
   43337 
   43338     /* If there is a WAL file in the file-system, open this database in WAL
   43339     ** mode. Otherwise, the following function call is a no-op.
   43340     */
   43341     rc = pagerOpenWalIfPresent(pPager);
   43342 #ifndef SQLITE_OMIT_WAL
   43343     assert( pPager->pWal==0 || rc==SQLITE_OK );
   43344 #endif
   43345   }
   43346 
   43347   if( pagerUseWal(pPager) ){
   43348     assert( rc==SQLITE_OK );
   43349     rc = pagerBeginReadTransaction(pPager);
   43350   }
   43351 
   43352   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   43353     rc = pagerPagecount(pPager, &pPager->dbSize);
   43354   }
   43355 
   43356  failed:
   43357   if( rc!=SQLITE_OK ){
   43358     assert( !MEMDB );
   43359     pager_unlock(pPager);
   43360     assert( pPager->eState==PAGER_OPEN );
   43361   }else{
   43362     pPager->eState = PAGER_READER;
   43363   }
   43364   return rc;
   43365 }
   43366 
   43367 /*
   43368 ** If the reference count has reached zero, rollback any active
   43369 ** transaction and unlock the pager.
   43370 **
   43371 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   43372 ** the rollback journal, the unlock is not performed and there is
   43373 ** nothing to rollback, so this routine is a no-op.
   43374 */
   43375 static void pagerUnlockIfUnused(Pager *pPager){
   43376   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
   43377     pagerUnlockAndRollback(pPager);
   43378   }
   43379 }
   43380 
   43381 /*
   43382 ** Acquire a reference to page number pgno in pager pPager (a page
   43383 ** reference has type DbPage*). If the requested reference is
   43384 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   43385 **
   43386 ** If the requested page is already in the cache, it is returned.
   43387 ** Otherwise, a new page object is allocated and populated with data
   43388 ** read from the database file. In some cases, the pcache module may
   43389 ** choose not to allocate a new page object and may reuse an existing
   43390 ** object with no outstanding references.
   43391 **
   43392 ** The extra data appended to a page is always initialized to zeros the
   43393 ** first time a page is loaded into memory. If the page requested is
   43394 ** already in the cache when this function is called, then the extra
   43395 ** data is left as it was when the page object was last used.
   43396 **
   43397 ** If the database image is smaller than the requested page or if a
   43398 ** non-zero value is passed as the noContent parameter and the
   43399 ** requested page is not already stored in the cache, then no
   43400 ** actual disk read occurs. In this case the memory image of the
   43401 ** page is initialized to all zeros.
   43402 **
   43403 ** If noContent is true, it means that we do not care about the contents
   43404 ** of the page. This occurs in two seperate scenarios:
   43405 **
   43406 **   a) When reading a free-list leaf page from the database, and
   43407 **
   43408 **   b) When a savepoint is being rolled back and we need to load
   43409 **      a new page into the cache to be filled with the data read
   43410 **      from the savepoint journal.
   43411 **
   43412 ** If noContent is true, then the data returned is zeroed instead of
   43413 ** being read from the database. Additionally, the bits corresponding
   43414 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   43415 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   43416 ** savepoints are set. This means if the page is made writable at any
   43417 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   43418 ** will not be journaled. This saves IO.
   43419 **
   43420 ** The acquisition might fail for several reasons.  In all cases,
   43421 ** an appropriate error code is returned and *ppPage is set to NULL.
   43422 **
   43423 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   43424 ** to find a page in the in-memory cache first.  If the page is not already
   43425 ** in memory, this routine goes to disk to read it in whereas Lookup()
   43426 ** just returns 0.  This routine acquires a read-lock the first time it
   43427 ** has to go to disk, and could also playback an old journal if necessary.
   43428 ** Since Lookup() never goes to disk, it never has to deal with locks
   43429 ** or journal files.
   43430 */
   43431 SQLITE_PRIVATE int sqlite3PagerAcquire(
   43432   Pager *pPager,      /* The pager open on the database file */
   43433   Pgno pgno,          /* Page number to fetch */
   43434   DbPage **ppPage,    /* Write a pointer to the page here */
   43435   int noContent       /* Do not bother reading content from disk if true */
   43436 ){
   43437   int rc;
   43438   PgHdr *pPg;
   43439 
   43440   assert( pPager->eState>=PAGER_READER );
   43441   assert( assert_pager_state(pPager) );
   43442 
   43443   if( pgno==0 ){
   43444     return SQLITE_CORRUPT_BKPT;
   43445   }
   43446 
   43447   /* If the pager is in the error state, return an error immediately.
   43448   ** Otherwise, request the page from the PCache layer. */
   43449   if( pPager->errCode!=SQLITE_OK ){
   43450     rc = pPager->errCode;
   43451   }else{
   43452     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   43453   }
   43454 
   43455   if( rc!=SQLITE_OK ){
   43456     /* Either the call to sqlite3PcacheFetch() returned an error or the
   43457     ** pager was already in the error-state when this function was called.
   43458     ** Set pPg to 0 and jump to the exception handler.  */
   43459     pPg = 0;
   43460     goto pager_acquire_err;
   43461   }
   43462   assert( (*ppPage)->pgno==pgno );
   43463   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   43464 
   43465   if( (*ppPage)->pPager && !noContent ){
   43466     /* In this case the pcache already contains an initialized copy of
   43467     ** the page. Return without further ado.  */
   43468     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   43469     pPager->nHit++;
   43470     return SQLITE_OK;
   43471 
   43472   }else{
   43473     /* The pager cache has created a new page. Its content needs to
   43474     ** be initialized.  */
   43475 
   43476     pPg = *ppPage;
   43477     pPg->pPager = pPager;
   43478 
   43479     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   43480     ** number greater than this, or the unused locking-page, is requested. */
   43481     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   43482       rc = SQLITE_CORRUPT_BKPT;
   43483       goto pager_acquire_err;
   43484     }
   43485 
   43486     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
   43487       if( pgno>pPager->mxPgno ){
   43488         rc = SQLITE_FULL;
   43489         goto pager_acquire_err;
   43490       }
   43491       if( noContent ){
   43492         /* Failure to set the bits in the InJournal bit-vectors is benign.
   43493         ** It merely means that we might do some extra work to journal a
   43494         ** page that does not need to be journaled.  Nevertheless, be sure
   43495         ** to test the case where a malloc error occurs while trying to set
   43496         ** a bit in a bit vector.
   43497         */
   43498         sqlite3BeginBenignMalloc();
   43499         if( pgno<=pPager->dbOrigSize ){
   43500           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   43501           testcase( rc==SQLITE_NOMEM );
   43502         }
   43503         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   43504         testcase( rc==SQLITE_NOMEM );
   43505         sqlite3EndBenignMalloc();
   43506       }
   43507       memset(pPg->pData, 0, pPager->pageSize);
   43508       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   43509     }else{
   43510       assert( pPg->pPager==pPager );
   43511       pPager->nMiss++;
   43512       rc = readDbPage(pPg);
   43513       if( rc!=SQLITE_OK ){
   43514         goto pager_acquire_err;
   43515       }
   43516     }
   43517     pager_set_pagehash(pPg);
   43518   }
   43519 
   43520   return SQLITE_OK;
   43521 
   43522 pager_acquire_err:
   43523   assert( rc!=SQLITE_OK );
   43524   if( pPg ){
   43525     sqlite3PcacheDrop(pPg);
   43526   }
   43527   pagerUnlockIfUnused(pPager);
   43528 
   43529   *ppPage = 0;
   43530   return rc;
   43531 }
   43532 
   43533 /*
   43534 ** Acquire a page if it is already in the in-memory cache.  Do
   43535 ** not read the page from disk.  Return a pointer to the page,
   43536 ** or 0 if the page is not in cache.
   43537 **
   43538 ** See also sqlite3PagerGet().  The difference between this routine
   43539 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   43540 ** in the page if the page is not already in cache.  This routine
   43541 ** returns NULL if the page is not in cache or if a disk I/O error
   43542 ** has ever happened.
   43543 */
   43544 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   43545   PgHdr *pPg = 0;
   43546   assert( pPager!=0 );
   43547   assert( pgno!=0 );
   43548   assert( pPager->pPCache!=0 );
   43549   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
   43550   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   43551   return pPg;
   43552 }
   43553 
   43554 /*
   43555 ** Release a page reference.
   43556 **
   43557 ** If the number of references to the page drop to zero, then the
   43558 ** page is added to the LRU list.  When all references to all pages
   43559 ** are released, a rollback occurs and the lock on the database is
   43560 ** removed.
   43561 */
   43562 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   43563   if( pPg ){
   43564     Pager *pPager = pPg->pPager;
   43565     sqlite3PcacheRelease(pPg);
   43566     pagerUnlockIfUnused(pPager);
   43567   }
   43568 }
   43569 
   43570 /*
   43571 ** This function is called at the start of every write transaction.
   43572 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   43573 ** file when this routine is called.
   43574 **
   43575 ** Open the journal file for pager pPager and write a journal header
   43576 ** to the start of it. If there are active savepoints, open the sub-journal
   43577 ** as well. This function is only used when the journal file is being
   43578 ** opened to write a rollback log for a transaction. It is not used
   43579 ** when opening a hot journal file to roll it back.
   43580 **
   43581 ** If the journal file is already open (as it may be in exclusive mode),
   43582 ** then this function just writes a journal header to the start of the
   43583 ** already open file.
   43584 **
   43585 ** Whether or not the journal file is opened by this function, the
   43586 ** Pager.pInJournal bitvec structure is allocated.
   43587 **
   43588 ** Return SQLITE_OK if everything is successful. Otherwise, return
   43589 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   43590 ** an IO error code if opening or writing the journal file fails.
   43591 */
   43592 static int pager_open_journal(Pager *pPager){
   43593   int rc = SQLITE_OK;                        /* Return code */
   43594   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   43595 
   43596   assert( pPager->eState==PAGER_WRITER_LOCKED );
   43597   assert( assert_pager_state(pPager) );
   43598   assert( pPager->pInJournal==0 );
   43599 
   43600   /* If already in the error state, this function is a no-op.  But on
   43601   ** the other hand, this routine is never called if we are already in
   43602   ** an error state. */
   43603   if( NEVER(pPager->errCode) ) return pPager->errCode;
   43604 
   43605   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   43606     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   43607     if( pPager->pInJournal==0 ){
   43608       return SQLITE_NOMEM;
   43609     }
   43610 
   43611     /* Open the journal file if it is not already open. */
   43612     if( !isOpen(pPager->jfd) ){
   43613       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   43614         sqlite3MemJournalOpen(pPager->jfd);
   43615       }else{
   43616         const int flags =                   /* VFS flags to open journal file */
   43617           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   43618           (pPager->tempFile ?
   43619             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   43620             (SQLITE_OPEN_MAIN_JOURNAL)
   43621           );
   43622   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   43623         rc = sqlite3JournalOpen(
   43624             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   43625         );
   43626   #else
   43627         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   43628   #endif
   43629       }
   43630       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   43631     }
   43632 
   43633 
   43634     /* Write the first journal header to the journal file and open
   43635     ** the sub-journal if necessary.
   43636     */
   43637     if( rc==SQLITE_OK ){
   43638       /* TODO: Check if all of these are really required. */
   43639       pPager->nRec = 0;
   43640       pPager->journalOff = 0;
   43641       pPager->setMaster = 0;
   43642       pPager->journalHdr = 0;
   43643       rc = writeJournalHdr(pPager);
   43644     }
   43645   }
   43646 
   43647   if( rc!=SQLITE_OK ){
   43648     sqlite3BitvecDestroy(pPager->pInJournal);
   43649     pPager->pInJournal = 0;
   43650   }else{
   43651     assert( pPager->eState==PAGER_WRITER_LOCKED );
   43652     pPager->eState = PAGER_WRITER_CACHEMOD;
   43653   }
   43654 
   43655   return rc;
   43656 }
   43657 
   43658 /*
   43659 ** Begin a write-transaction on the specified pager object. If a
   43660 ** write-transaction has already been opened, this function is a no-op.
   43661 **
   43662 ** If the exFlag argument is false, then acquire at least a RESERVED
   43663 ** lock on the database file. If exFlag is true, then acquire at least
   43664 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   43665 ** functions need be called.
   43666 **
   43667 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   43668 ** within this transaction will be opened as an in-memory file. This
   43669 ** has no effect if the sub-journal is already opened (as it may be when
   43670 ** running in exclusive mode) or if the transaction does not require a
   43671 ** sub-journal. If the subjInMemory argument is zero, then any required
   43672 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   43673 ** or using a temporary file otherwise.
   43674 */
   43675 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   43676   int rc = SQLITE_OK;
   43677 
   43678   if( pPager->errCode ) return pPager->errCode;
   43679   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   43680   pPager->subjInMemory = (u8)subjInMemory;
   43681 
   43682   if( ALWAYS(pPager->eState==PAGER_READER) ){
   43683     assert( pPager->pInJournal==0 );
   43684 
   43685     if( pagerUseWal(pPager) ){
   43686       /* If the pager is configured to use locking_mode=exclusive, and an
   43687       ** exclusive lock on the database is not already held, obtain it now.
   43688       */
   43689       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   43690         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   43691         if( rc!=SQLITE_OK ){
   43692           return rc;
   43693         }
   43694         sqlite3WalExclusiveMode(pPager->pWal, 1);
   43695       }
   43696 
   43697       /* Grab the write lock on the log file. If successful, upgrade to
   43698       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   43699       ** The busy-handler is not invoked if another connection already
   43700       ** holds the write-lock. If possible, the upper layer will call it.
   43701       */
   43702       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   43703     }else{
   43704       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   43705       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   43706       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   43707       ** lock, but not when obtaining the RESERVED lock.
   43708       */
   43709       rc = pagerLockDb(pPager, RESERVED_LOCK);
   43710       if( rc==SQLITE_OK && exFlag ){
   43711         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   43712       }
   43713     }
   43714 
   43715     if( rc==SQLITE_OK ){
   43716       /* Change to WRITER_LOCKED state.
   43717       **
   43718       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   43719       ** when it has an open transaction, but never to DBMOD or FINISHED.
   43720       ** This is because in those states the code to roll back savepoint
   43721       ** transactions may copy data from the sub-journal into the database
   43722       ** file as well as into the page cache. Which would be incorrect in
   43723       ** WAL mode.
   43724       */
   43725       pPager->eState = PAGER_WRITER_LOCKED;
   43726       pPager->dbHintSize = pPager->dbSize;
   43727       pPager->dbFileSize = pPager->dbSize;
   43728       pPager->dbOrigSize = pPager->dbSize;
   43729       pPager->journalOff = 0;
   43730     }
   43731 
   43732     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   43733     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   43734     assert( assert_pager_state(pPager) );
   43735   }
   43736 
   43737   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   43738   return rc;
   43739 }
   43740 
   43741 /*
   43742 ** Mark a single data page as writeable. The page is written into the
   43743 ** main journal or sub-journal as required. If the page is written into
   43744 ** one of the journals, the corresponding bit is set in the
   43745 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   43746 ** of any open savepoints as appropriate.
   43747 */
   43748 static int pager_write(PgHdr *pPg){
   43749   void *pData = pPg->pData;
   43750   Pager *pPager = pPg->pPager;
   43751   int rc = SQLITE_OK;
   43752 
   43753   /* This routine is not called unless a write-transaction has already
   43754   ** been started. The journal file may or may not be open at this point.
   43755   ** It is never called in the ERROR state.
   43756   */
   43757   assert( pPager->eState==PAGER_WRITER_LOCKED
   43758        || pPager->eState==PAGER_WRITER_CACHEMOD
   43759        || pPager->eState==PAGER_WRITER_DBMOD
   43760   );
   43761   assert( assert_pager_state(pPager) );
   43762 
   43763   /* If an error has been previously detected, report the same error
   43764   ** again. This should not happen, but the check provides robustness. */
   43765   if( NEVER(pPager->errCode) )  return pPager->errCode;
   43766 
   43767   /* Higher-level routines never call this function if database is not
   43768   ** writable.  But check anyway, just for robustness. */
   43769   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
   43770 
   43771   CHECK_PAGE(pPg);
   43772 
   43773   /* The journal file needs to be opened. Higher level routines have already
   43774   ** obtained the necessary locks to begin the write-transaction, but the
   43775   ** rollback journal might not yet be open. Open it now if this is the case.
   43776   **
   43777   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   43778   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   43779   ** an error might occur and the pager would end up in WRITER_LOCKED state
   43780   ** with pages marked as dirty in the cache.
   43781   */
   43782   if( pPager->eState==PAGER_WRITER_LOCKED ){
   43783     rc = pager_open_journal(pPager);
   43784     if( rc!=SQLITE_OK ) return rc;
   43785   }
   43786   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   43787   assert( assert_pager_state(pPager) );
   43788 
   43789   /* Mark the page as dirty.  If the page has already been written
   43790   ** to the journal then we can return right away.
   43791   */
   43792   sqlite3PcacheMakeDirty(pPg);
   43793   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
   43794     assert( !pagerUseWal(pPager) );
   43795   }else{
   43796 
   43797     /* The transaction journal now exists and we have a RESERVED or an
   43798     ** EXCLUSIVE lock on the main database file.  Write the current page to
   43799     ** the transaction journal if it is not there already.
   43800     */
   43801     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
   43802       assert( pagerUseWal(pPager)==0 );
   43803       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
   43804         u32 cksum;
   43805         char *pData2;
   43806         i64 iOff = pPager->journalOff;
   43807 
   43808         /* We should never write to the journal file the page that
   43809         ** contains the database locks.  The following assert verifies
   43810         ** that we do not. */
   43811         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   43812 
   43813         assert( pPager->journalHdr<=pPager->journalOff );
   43814         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   43815         cksum = pager_cksum(pPager, (u8*)pData2);
   43816 
   43817         /* Even if an IO or diskfull error occurs while journalling the
   43818         ** page in the block above, set the need-sync flag for the page.
   43819         ** Otherwise, when the transaction is rolled back, the logic in
   43820         ** playback_one_page() will think that the page needs to be restored
   43821         ** in the database file. And if an IO error occurs while doing so,
   43822         ** then corruption may follow.
   43823         */
   43824         pPg->flags |= PGHDR_NEED_SYNC;
   43825 
   43826         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   43827         if( rc!=SQLITE_OK ) return rc;
   43828         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   43829         if( rc!=SQLITE_OK ) return rc;
   43830         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   43831         if( rc!=SQLITE_OK ) return rc;
   43832 
   43833         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   43834                  pPager->journalOff, pPager->pageSize));
   43835         PAGER_INCR(sqlite3_pager_writej_count);
   43836         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   43837              PAGERID(pPager), pPg->pgno,
   43838              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   43839 
   43840         pPager->journalOff += 8 + pPager->pageSize;
   43841         pPager->nRec++;
   43842         assert( pPager->pInJournal!=0 );
   43843         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   43844         testcase( rc==SQLITE_NOMEM );
   43845         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   43846         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   43847         if( rc!=SQLITE_OK ){
   43848           assert( rc==SQLITE_NOMEM );
   43849           return rc;
   43850         }
   43851       }else{
   43852         if( pPager->eState!=PAGER_WRITER_DBMOD ){
   43853           pPg->flags |= PGHDR_NEED_SYNC;
   43854         }
   43855         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   43856                 PAGERID(pPager), pPg->pgno,
   43857                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   43858       }
   43859     }
   43860 
   43861     /* If the statement journal is open and the page is not in it,
   43862     ** then write the current page to the statement journal.  Note that
   43863     ** the statement journal format differs from the standard journal format
   43864     ** in that it omits the checksums and the header.
   43865     */
   43866     if( subjRequiresPage(pPg) ){
   43867       rc = subjournalPage(pPg);
   43868     }
   43869   }
   43870 
   43871   /* Update the database size and return.
   43872   */
   43873   if( pPager->dbSize<pPg->pgno ){
   43874     pPager->dbSize = pPg->pgno;
   43875   }
   43876   return rc;
   43877 }
   43878 
   43879 /*
   43880 ** Mark a data page as writeable. This routine must be called before
   43881 ** making changes to a page. The caller must check the return value
   43882 ** of this function and be careful not to change any page data unless
   43883 ** this routine returns SQLITE_OK.
   43884 **
   43885 ** The difference between this function and pager_write() is that this
   43886 ** function also deals with the special case where 2 or more pages
   43887 ** fit on a single disk sector. In this case all co-resident pages
   43888 ** must have been written to the journal file before returning.
   43889 **
   43890 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   43891 ** as appropriate. Otherwise, SQLITE_OK.
   43892 */
   43893 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   43894   int rc = SQLITE_OK;
   43895 
   43896   PgHdr *pPg = pDbPage;
   43897   Pager *pPager = pPg->pPager;
   43898   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   43899 
   43900   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   43901   assert( pPager->eState!=PAGER_ERROR );
   43902   assert( assert_pager_state(pPager) );
   43903 
   43904   if( nPagePerSector>1 ){
   43905     Pgno nPageCount;          /* Total number of pages in database file */
   43906     Pgno pg1;                 /* First page of the sector pPg is located on. */
   43907     int nPage = 0;            /* Number of pages starting at pg1 to journal */
   43908     int ii;                   /* Loop counter */
   43909     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   43910 
   43911     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
   43912     ** a journal header to be written between the pages journaled by
   43913     ** this function.
   43914     */
   43915     assert( !MEMDB );
   43916     assert( pPager->doNotSyncSpill==0 );
   43917     pPager->doNotSyncSpill++;
   43918 
   43919     /* This trick assumes that both the page-size and sector-size are
   43920     ** an integer power of 2. It sets variable pg1 to the identifier
   43921     ** of the first page of the sector pPg is located on.
   43922     */
   43923     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   43924 
   43925     nPageCount = pPager->dbSize;
   43926     if( pPg->pgno>nPageCount ){
   43927       nPage = (pPg->pgno - pg1)+1;
   43928     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   43929       nPage = nPageCount+1-pg1;
   43930     }else{
   43931       nPage = nPagePerSector;
   43932     }
   43933     assert(nPage>0);
   43934     assert(pg1<=pPg->pgno);
   43935     assert((pg1+nPage)>pPg->pgno);
   43936 
   43937     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   43938       Pgno pg = pg1+ii;
   43939       PgHdr *pPage;
   43940       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   43941         if( pg!=PAGER_MJ_PGNO(pPager) ){
   43942           rc = sqlite3PagerGet(pPager, pg, &pPage);
   43943           if( rc==SQLITE_OK ){
   43944             rc = pager_write(pPage);
   43945             if( pPage->flags&PGHDR_NEED_SYNC ){
   43946               needSync = 1;
   43947             }
   43948             sqlite3PagerUnref(pPage);
   43949           }
   43950         }
   43951       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   43952         if( pPage->flags&PGHDR_NEED_SYNC ){
   43953           needSync = 1;
   43954         }
   43955         sqlite3PagerUnref(pPage);
   43956       }
   43957     }
   43958 
   43959     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   43960     ** starting at pg1, then it needs to be set for all of them. Because
   43961     ** writing to any of these nPage pages may damage the others, the
   43962     ** journal file must contain sync()ed copies of all of them
   43963     ** before any of them can be written out to the database file.
   43964     */
   43965     if( rc==SQLITE_OK && needSync ){
   43966       assert( !MEMDB );
   43967       for(ii=0; ii<nPage; ii++){
   43968         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   43969         if( pPage ){
   43970           pPage->flags |= PGHDR_NEED_SYNC;
   43971           sqlite3PagerUnref(pPage);
   43972         }
   43973       }
   43974     }
   43975 
   43976     assert( pPager->doNotSyncSpill==1 );
   43977     pPager->doNotSyncSpill--;
   43978   }else{
   43979     rc = pager_write(pDbPage);
   43980   }
   43981   return rc;
   43982 }
   43983 
   43984 /*
   43985 ** Return TRUE if the page given in the argument was previously passed
   43986 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   43987 ** to change the content of the page.
   43988 */
   43989 #ifndef NDEBUG
   43990 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   43991   return pPg->flags&PGHDR_DIRTY;
   43992 }
   43993 #endif
   43994 
   43995 /*
   43996 ** A call to this routine tells the pager that it is not necessary to
   43997 ** write the information on page pPg back to the disk, even though
   43998 ** that page might be marked as dirty.  This happens, for example, when
   43999 ** the page has been added as a leaf of the freelist and so its
   44000 ** content no longer matters.
   44001 **
   44002 ** The overlying software layer calls this routine when all of the data
   44003 ** on the given page is unused. The pager marks the page as clean so
   44004 ** that it does not get written to disk.
   44005 **
   44006 ** Tests show that this optimization can quadruple the speed of large
   44007 ** DELETE operations.
   44008 */
   44009 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   44010   Pager *pPager = pPg->pPager;
   44011   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   44012     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   44013     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   44014     pPg->flags |= PGHDR_DONT_WRITE;
   44015     pager_set_pagehash(pPg);
   44016   }
   44017 }
   44018 
   44019 /*
   44020 ** This routine is called to increment the value of the database file
   44021 ** change-counter, stored as a 4-byte big-endian integer starting at
   44022 ** byte offset 24 of the pager file.  The secondary change counter at
   44023 ** 92 is also updated, as is the SQLite version number at offset 96.
   44024 **
   44025 ** But this only happens if the pPager->changeCountDone flag is false.
   44026 ** To avoid excess churning of page 1, the update only happens once.
   44027 ** See also the pager_write_changecounter() routine that does an
   44028 ** unconditional update of the change counters.
   44029 **
   44030 ** If the isDirectMode flag is zero, then this is done by calling
   44031 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   44032 ** page data. In this case the file will be updated when the current
   44033 ** transaction is committed.
   44034 **
   44035 ** The isDirectMode flag may only be non-zero if the library was compiled
   44036 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   44037 ** if isDirect is non-zero, then the database file is updated directly
   44038 ** by writing an updated version of page 1 using a call to the
   44039 ** sqlite3OsWrite() function.
   44040 */
   44041 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   44042   int rc = SQLITE_OK;
   44043 
   44044   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44045        || pPager->eState==PAGER_WRITER_DBMOD
   44046   );
   44047   assert( assert_pager_state(pPager) );
   44048 
   44049   /* Declare and initialize constant integer 'isDirect'. If the
   44050   ** atomic-write optimization is enabled in this build, then isDirect
   44051   ** is initialized to the value passed as the isDirectMode parameter
   44052   ** to this function. Otherwise, it is always set to zero.
   44053   **
   44054   ** The idea is that if the atomic-write optimization is not
   44055   ** enabled at compile time, the compiler can omit the tests of
   44056   ** 'isDirect' below, as well as the block enclosed in the
   44057   ** "if( isDirect )" condition.
   44058   */
   44059 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   44060 # define DIRECT_MODE 0
   44061   assert( isDirectMode==0 );
   44062   UNUSED_PARAMETER(isDirectMode);
   44063 #else
   44064 # define DIRECT_MODE isDirectMode
   44065 #endif
   44066 
   44067   if( !pPager->changeCountDone && pPager->dbSize>0 ){
   44068     PgHdr *pPgHdr;                /* Reference to page 1 */
   44069 
   44070     assert( !pPager->tempFile && isOpen(pPager->fd) );
   44071 
   44072     /* Open page 1 of the file for writing. */
   44073     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   44074     assert( pPgHdr==0 || rc==SQLITE_OK );
   44075 
   44076     /* If page one was fetched successfully, and this function is not
   44077     ** operating in direct-mode, make page 1 writable.  When not in
   44078     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   44079     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   44080     */
   44081     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
   44082       rc = sqlite3PagerWrite(pPgHdr);
   44083     }
   44084 
   44085     if( rc==SQLITE_OK ){
   44086       /* Actually do the update of the change counter */
   44087       pager_write_changecounter(pPgHdr);
   44088 
   44089       /* If running in direct mode, write the contents of page 1 to the file. */
   44090       if( DIRECT_MODE ){
   44091         const void *zBuf;
   44092         assert( pPager->dbFileSize>0 );
   44093         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
   44094         if( rc==SQLITE_OK ){
   44095           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   44096         }
   44097         if( rc==SQLITE_OK ){
   44098           pPager->changeCountDone = 1;
   44099         }
   44100       }else{
   44101         pPager->changeCountDone = 1;
   44102       }
   44103     }
   44104 
   44105     /* Release the page reference. */
   44106     sqlite3PagerUnref(pPgHdr);
   44107   }
   44108   return rc;
   44109 }
   44110 
   44111 /*
   44112 ** Sync the database file to disk. This is a no-op for in-memory databases
   44113 ** or pages with the Pager.noSync flag set.
   44114 **
   44115 ** If successful, or if called on a pager for which it is a no-op, this
   44116 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   44117 */
   44118 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
   44119   int rc = SQLITE_OK;
   44120   if( !pPager->noSync ){
   44121     assert( !MEMDB );
   44122     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   44123   }else if( isOpen(pPager->fd) ){
   44124     assert( !MEMDB );
   44125     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
   44126     if( rc==SQLITE_NOTFOUND ){
   44127       rc = SQLITE_OK;
   44128     }
   44129   }
   44130   return rc;
   44131 }
   44132 
   44133 /*
   44134 ** This function may only be called while a write-transaction is active in
   44135 ** rollback. If the connection is in WAL mode, this call is a no-op.
   44136 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   44137 ** the database file, an attempt is made to obtain one.
   44138 **
   44139 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   44140 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   44141 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   44142 ** returned.
   44143 */
   44144 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   44145   int rc = SQLITE_OK;
   44146   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44147        || pPager->eState==PAGER_WRITER_DBMOD
   44148        || pPager->eState==PAGER_WRITER_LOCKED
   44149   );
   44150   assert( assert_pager_state(pPager) );
   44151   if( 0==pagerUseWal(pPager) ){
   44152     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   44153   }
   44154   return rc;
   44155 }
   44156 
   44157 /*
   44158 ** Sync the database file for the pager pPager. zMaster points to the name
   44159 ** of a master journal file that should be written into the individual
   44160 ** journal file. zMaster may be NULL, which is interpreted as no master
   44161 ** journal (a single database transaction).
   44162 **
   44163 ** This routine ensures that:
   44164 **
   44165 **   * The database file change-counter is updated,
   44166 **   * the journal is synced (unless the atomic-write optimization is used),
   44167 **   * all dirty pages are written to the database file,
   44168 **   * the database file is truncated (if required), and
   44169 **   * the database file synced.
   44170 **
   44171 ** The only thing that remains to commit the transaction is to finalize
   44172 ** (delete, truncate or zero the first part of) the journal file (or
   44173 ** delete the master journal file if specified).
   44174 **
   44175 ** Note that if zMaster==NULL, this does not overwrite a previous value
   44176 ** passed to an sqlite3PagerCommitPhaseOne() call.
   44177 **
   44178 ** If the final parameter - noSync - is true, then the database file itself
   44179 ** is not synced. The caller must call sqlite3PagerSync() directly to
   44180 ** sync the database file before calling CommitPhaseTwo() to delete the
   44181 ** journal file in this case.
   44182 */
   44183 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   44184   Pager *pPager,                  /* Pager object */
   44185   const char *zMaster,            /* If not NULL, the master journal name */
   44186   int noSync                      /* True to omit the xSync on the db file */
   44187 ){
   44188   int rc = SQLITE_OK;             /* Return code */
   44189 
   44190   assert( pPager->eState==PAGER_WRITER_LOCKED
   44191        || pPager->eState==PAGER_WRITER_CACHEMOD
   44192        || pPager->eState==PAGER_WRITER_DBMOD
   44193        || pPager->eState==PAGER_ERROR
   44194   );
   44195   assert( assert_pager_state(pPager) );
   44196 
   44197   /* If a prior error occurred, report that error again. */
   44198   if( NEVER(pPager->errCode) ) return pPager->errCode;
   44199 
   44200   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   44201       pPager->zFilename, zMaster, pPager->dbSize));
   44202 
   44203   /* If no database changes have been made, return early. */
   44204   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   44205 
   44206   if( MEMDB ){
   44207     /* If this is an in-memory db, or no pages have been written to, or this
   44208     ** function has already been called, it is mostly a no-op.  However, any
   44209     ** backup in progress needs to be restarted.
   44210     */
   44211     sqlite3BackupRestart(pPager->pBackup);
   44212   }else{
   44213     if( pagerUseWal(pPager) ){
   44214       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   44215       PgHdr *pPageOne = 0;
   44216       if( pList==0 ){
   44217         /* Must have at least one page for the WAL commit flag.
   44218         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
   44219         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
   44220         pList = pPageOne;
   44221         pList->pDirty = 0;
   44222       }
   44223       assert( rc==SQLITE_OK );
   44224       if( ALWAYS(pList) ){
   44225         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
   44226       }
   44227       sqlite3PagerUnref(pPageOne);
   44228       if( rc==SQLITE_OK ){
   44229         sqlite3PcacheCleanAll(pPager->pPCache);
   44230       }
   44231     }else{
   44232       /* The following block updates the change-counter. Exactly how it
   44233       ** does this depends on whether or not the atomic-update optimization
   44234       ** was enabled at compile time, and if this transaction meets the
   44235       ** runtime criteria to use the operation:
   44236       **
   44237       **    * The file-system supports the atomic-write property for
   44238       **      blocks of size page-size, and
   44239       **    * This commit is not part of a multi-file transaction, and
   44240       **    * Exactly one page has been modified and store in the journal file.
   44241       **
   44242       ** If the optimization was not enabled at compile time, then the
   44243       ** pager_incr_changecounter() function is called to update the change
   44244       ** counter in 'indirect-mode'. If the optimization is compiled in but
   44245       ** is not applicable to this transaction, call sqlite3JournalCreate()
   44246       ** to make sure the journal file has actually been created, then call
   44247       ** pager_incr_changecounter() to update the change-counter in indirect
   44248       ** mode.
   44249       **
   44250       ** Otherwise, if the optimization is both enabled and applicable,
   44251       ** then call pager_incr_changecounter() to update the change-counter
   44252       ** in 'direct' mode. In this case the journal file will never be
   44253       ** created for this transaction.
   44254       */
   44255   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   44256       PgHdr *pPg;
   44257       assert( isOpen(pPager->jfd)
   44258            || pPager->journalMode==PAGER_JOURNALMODE_OFF
   44259            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   44260       );
   44261       if( !zMaster && isOpen(pPager->jfd)
   44262        && pPager->journalOff==jrnlBufferSize(pPager)
   44263        && pPager->dbSize>=pPager->dbOrigSize
   44264        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   44265       ){
   44266         /* Update the db file change counter via the direct-write method. The
   44267         ** following call will modify the in-memory representation of page 1
   44268         ** to include the updated change counter and then write page 1
   44269         ** directly to the database file. Because of the atomic-write
   44270         ** property of the host file-system, this is safe.
   44271         */
   44272         rc = pager_incr_changecounter(pPager, 1);
   44273       }else{
   44274         rc = sqlite3JournalCreate(pPager->jfd);
   44275         if( rc==SQLITE_OK ){
   44276           rc = pager_incr_changecounter(pPager, 0);
   44277         }
   44278       }
   44279   #else
   44280       rc = pager_incr_changecounter(pPager, 0);
   44281   #endif
   44282       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44283 
   44284       /* If this transaction has made the database smaller, then all pages
   44285       ** being discarded by the truncation must be written to the journal
   44286       ** file. This can only happen in auto-vacuum mode.
   44287       **
   44288       ** Before reading the pages with page numbers larger than the
   44289       ** current value of Pager.dbSize, set dbSize back to the value
   44290       ** that it took at the start of the transaction. Otherwise, the
   44291       ** calls to sqlite3PagerGet() return zeroed pages instead of
   44292       ** reading data from the database file.
   44293       */
   44294   #ifndef SQLITE_OMIT_AUTOVACUUM
   44295       if( pPager->dbSize<pPager->dbOrigSize
   44296        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
   44297       ){
   44298         Pgno i;                                   /* Iterator variable */
   44299         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
   44300         const Pgno dbSize = pPager->dbSize;       /* Database image size */
   44301         pPager->dbSize = pPager->dbOrigSize;
   44302         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
   44303           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
   44304             PgHdr *pPage;             /* Page to journal */
   44305             rc = sqlite3PagerGet(pPager, i, &pPage);
   44306             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44307             rc = sqlite3PagerWrite(pPage);
   44308             sqlite3PagerUnref(pPage);
   44309             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44310           }
   44311         }
   44312         pPager->dbSize = dbSize;
   44313       }
   44314   #endif
   44315 
   44316       /* Write the master journal name into the journal file. If a master
   44317       ** journal file name has already been written to the journal file,
   44318       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   44319       */
   44320       rc = writeMasterJournal(pPager, zMaster);
   44321       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44322 
   44323       /* Sync the journal file and write all dirty pages to the database.
   44324       ** If the atomic-update optimization is being used, this sync will not
   44325       ** create the journal file or perform any real IO.
   44326       **
   44327       ** Because the change-counter page was just modified, unless the
   44328       ** atomic-update optimization is used it is almost certain that the
   44329       ** journal requires a sync here. However, in locking_mode=exclusive
   44330       ** on a system under memory pressure it is just possible that this is
   44331       ** not the case. In this case it is likely enough that the redundant
   44332       ** xSync() call will be changed to a no-op by the OS anyhow.
   44333       */
   44334       rc = syncJournal(pPager, 0);
   44335       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44336 
   44337       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   44338       if( rc!=SQLITE_OK ){
   44339         assert( rc!=SQLITE_IOERR_BLOCKED );
   44340         goto commit_phase_one_exit;
   44341       }
   44342       sqlite3PcacheCleanAll(pPager->pPCache);
   44343 
   44344       /* If the file on disk is not the same size as the database image,
   44345       ** then use pager_truncate to grow or shrink the file here.
   44346       */
   44347       if( pPager->dbSize!=pPager->dbFileSize ){
   44348         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   44349         assert( pPager->eState==PAGER_WRITER_DBMOD );
   44350         rc = pager_truncate(pPager, nNew);
   44351         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   44352       }
   44353 
   44354       /* Finally, sync the database file. */
   44355       if( !noSync ){
   44356         rc = sqlite3PagerSync(pPager);
   44357       }
   44358       IOTRACE(("DBSYNC %p\n", pPager))
   44359     }
   44360   }
   44361 
   44362 commit_phase_one_exit:
   44363   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   44364     pPager->eState = PAGER_WRITER_FINISHED;
   44365   }
   44366   return rc;
   44367 }
   44368 
   44369 
   44370 /*
   44371 ** When this function is called, the database file has been completely
   44372 ** updated to reflect the changes made by the current transaction and
   44373 ** synced to disk. The journal file still exists in the file-system
   44374 ** though, and if a failure occurs at this point it will eventually
   44375 ** be used as a hot-journal and the current transaction rolled back.
   44376 **
   44377 ** This function finalizes the journal file, either by deleting,
   44378 ** truncating or partially zeroing it, so that it cannot be used
   44379 ** for hot-journal rollback. Once this is done the transaction is
   44380 ** irrevocably committed.
   44381 **
   44382 ** If an error occurs, an IO error code is returned and the pager
   44383 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   44384 */
   44385 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   44386   int rc = SQLITE_OK;                  /* Return code */
   44387 
   44388   /* This routine should not be called if a prior error has occurred.
   44389   ** But if (due to a coding error elsewhere in the system) it does get
   44390   ** called, just return the same error code without doing anything. */
   44391   if( NEVER(pPager->errCode) ) return pPager->errCode;
   44392 
   44393   assert( pPager->eState==PAGER_WRITER_LOCKED
   44394        || pPager->eState==PAGER_WRITER_FINISHED
   44395        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   44396   );
   44397   assert( assert_pager_state(pPager) );
   44398 
   44399   /* An optimization. If the database was not actually modified during
   44400   ** this transaction, the pager is running in exclusive-mode and is
   44401   ** using persistent journals, then this function is a no-op.
   44402   **
   44403   ** The start of the journal file currently contains a single journal
   44404   ** header with the nRec field set to 0. If such a journal is used as
   44405   ** a hot-journal during hot-journal rollback, 0 changes will be made
   44406   ** to the database file. So there is no need to zero the journal
   44407   ** header. Since the pager is in exclusive mode, there is no need
   44408   ** to drop any locks either.
   44409   */
   44410   if( pPager->eState==PAGER_WRITER_LOCKED
   44411    && pPager->exclusiveMode
   44412    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   44413   ){
   44414     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   44415     pPager->eState = PAGER_READER;
   44416     return SQLITE_OK;
   44417   }
   44418 
   44419   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   44420   rc = pager_end_transaction(pPager, pPager->setMaster);
   44421   return pager_error(pPager, rc);
   44422 }
   44423 
   44424 /*
   44425 ** If a write transaction is open, then all changes made within the
   44426 ** transaction are reverted and the current write-transaction is closed.
   44427 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   44428 ** state if an error occurs.
   44429 **
   44430 ** If the pager is already in PAGER_ERROR state when this function is called,
   44431 ** it returns Pager.errCode immediately. No work is performed in this case.
   44432 **
   44433 ** Otherwise, in rollback mode, this function performs two functions:
   44434 **
   44435 **   1) It rolls back the journal file, restoring all database file and
   44436 **      in-memory cache pages to the state they were in when the transaction
   44437 **      was opened, and
   44438 **
   44439 **   2) It finalizes the journal file, so that it is not used for hot
   44440 **      rollback at any point in the future.
   44441 **
   44442 ** Finalization of the journal file (task 2) is only performed if the
   44443 ** rollback is successful.
   44444 **
   44445 ** In WAL mode, all cache-entries containing data modified within the
   44446 ** current transaction are either expelled from the cache or reverted to
   44447 ** their pre-transaction state by re-reading data from the database or
   44448 ** WAL files. The WAL transaction is then closed.
   44449 */
   44450 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   44451   int rc = SQLITE_OK;                  /* Return code */
   44452   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   44453 
   44454   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   44455   ** the pager is already in the ERROR state, the rollback is not
   44456   ** attempted here. Instead, the error code is returned to the caller.
   44457   */
   44458   assert( assert_pager_state(pPager) );
   44459   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   44460   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   44461 
   44462   if( pagerUseWal(pPager) ){
   44463     int rc2;
   44464     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   44465     rc2 = pager_end_transaction(pPager, pPager->setMaster);
   44466     if( rc==SQLITE_OK ) rc = rc2;
   44467   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   44468     int eState = pPager->eState;
   44469     rc = pager_end_transaction(pPager, 0);
   44470     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
   44471       /* This can happen using journal_mode=off. Move the pager to the error
   44472       ** state to indicate that the contents of the cache may not be trusted.
   44473       ** Any active readers will get SQLITE_ABORT.
   44474       */
   44475       pPager->errCode = SQLITE_ABORT;
   44476       pPager->eState = PAGER_ERROR;
   44477       return rc;
   44478     }
   44479   }else{
   44480     rc = pager_playback(pPager, 0);
   44481   }
   44482 
   44483   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   44484   assert( rc==SQLITE_OK || rc==SQLITE_FULL
   44485           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
   44486 
   44487   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   44488   ** cache. So call pager_error() on the way out to make any error persistent.
   44489   */
   44490   return pager_error(pPager, rc);
   44491 }
   44492 
   44493 /*
   44494 ** Return TRUE if the database file is opened read-only.  Return FALSE
   44495 ** if the database is (in theory) writable.
   44496 */
   44497 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   44498   return pPager->readOnly;
   44499 }
   44500 
   44501 /*
   44502 ** Return the number of references to the pager.
   44503 */
   44504 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   44505   return sqlite3PcacheRefCount(pPager->pPCache);
   44506 }
   44507 
   44508 /*
   44509 ** Return the approximate number of bytes of memory currently
   44510 ** used by the pager and its associated cache.
   44511 */
   44512 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   44513   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   44514                                      + 5*sizeof(void*);
   44515   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   44516            + sqlite3MallocSize(pPager)
   44517            + pPager->pageSize;
   44518 }
   44519 
   44520 /*
   44521 ** Return the number of references to the specified page.
   44522 */
   44523 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   44524   return sqlite3PcachePageRefcount(pPage);
   44525 }
   44526 
   44527 #ifdef SQLITE_TEST
   44528 /*
   44529 ** This routine is used for testing and analysis only.
   44530 */
   44531 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   44532   static int a[11];
   44533   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   44534   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   44535   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   44536   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   44537   a[4] = pPager->eState;
   44538   a[5] = pPager->errCode;
   44539   a[6] = pPager->nHit;
   44540   a[7] = pPager->nMiss;
   44541   a[8] = 0;  /* Used to be pPager->nOvfl */
   44542   a[9] = pPager->nRead;
   44543   a[10] = pPager->nWrite;
   44544   return a;
   44545 }
   44546 #endif
   44547 
   44548 /*
   44549 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
   44550 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
   44551 ** current cache hit or miss count, according to the value of eStat. If the
   44552 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
   44553 ** returning.
   44554 */
   44555 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
   44556   int *piStat;
   44557 
   44558   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
   44559        || eStat==SQLITE_DBSTATUS_CACHE_MISS
   44560   );
   44561   if( eStat==SQLITE_DBSTATUS_CACHE_HIT ){
   44562     piStat = &pPager->nHit;
   44563   }else{
   44564     piStat = &pPager->nMiss;
   44565   }
   44566 
   44567   *pnVal += *piStat;
   44568   if( reset ){
   44569     *piStat = 0;
   44570   }
   44571 }
   44572 
   44573 /*
   44574 ** Return true if this is an in-memory pager.
   44575 */
   44576 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   44577   return MEMDB;
   44578 }
   44579 
   44580 /*
   44581 ** Check that there are at least nSavepoint savepoints open. If there are
   44582 ** currently less than nSavepoints open, then open one or more savepoints
   44583 ** to make up the difference. If the number of savepoints is already
   44584 ** equal to nSavepoint, then this function is a no-op.
   44585 **
   44586 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   44587 ** occurs while opening the sub-journal file, then an IO error code is
   44588 ** returned. Otherwise, SQLITE_OK.
   44589 */
   44590 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   44591   int rc = SQLITE_OK;                       /* Return code */
   44592   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   44593 
   44594   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   44595   assert( assert_pager_state(pPager) );
   44596 
   44597   if( nSavepoint>nCurrent && pPager->useJournal ){
   44598     int ii;                                 /* Iterator variable */
   44599     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   44600 
   44601     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   44602     ** if the allocation fails. Otherwise, zero the new portion in case a
   44603     ** malloc failure occurs while populating it in the for(...) loop below.
   44604     */
   44605     aNew = (PagerSavepoint *)sqlite3Realloc(
   44606         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   44607     );
   44608     if( !aNew ){
   44609       return SQLITE_NOMEM;
   44610     }
   44611     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   44612     pPager->aSavepoint = aNew;
   44613 
   44614     /* Populate the PagerSavepoint structures just allocated. */
   44615     for(ii=nCurrent; ii<nSavepoint; ii++){
   44616       aNew[ii].nOrig = pPager->dbSize;
   44617       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   44618         aNew[ii].iOffset = pPager->journalOff;
   44619       }else{
   44620         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   44621       }
   44622       aNew[ii].iSubRec = pPager->nSubRec;
   44623       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   44624       if( !aNew[ii].pInSavepoint ){
   44625         return SQLITE_NOMEM;
   44626       }
   44627       if( pagerUseWal(pPager) ){
   44628         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   44629       }
   44630       pPager->nSavepoint = ii+1;
   44631     }
   44632     assert( pPager->nSavepoint==nSavepoint );
   44633     assertTruncateConstraint(pPager);
   44634   }
   44635 
   44636   return rc;
   44637 }
   44638 
   44639 /*
   44640 ** This function is called to rollback or release (commit) a savepoint.
   44641 ** The savepoint to release or rollback need not be the most recently
   44642 ** created savepoint.
   44643 **
   44644 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   44645 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   44646 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   44647 ** that have occurred since the specified savepoint was created.
   44648 **
   44649 ** The savepoint to rollback or release is identified by parameter
   44650 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   44651 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   44652 ** on the most recently created savepoint. If iSavepoint is greater than
   44653 ** (Pager.nSavepoint-1), then this function is a no-op.
   44654 **
   44655 ** If a negative value is passed to this function, then the current
   44656 ** transaction is rolled back. This is different to calling
   44657 ** sqlite3PagerRollback() because this function does not terminate
   44658 ** the transaction or unlock the database, it just restores the
   44659 ** contents of the database to its original state.
   44660 **
   44661 ** In any case, all savepoints with an index greater than iSavepoint
   44662 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   44663 ** then savepoint iSavepoint is also destroyed.
   44664 **
   44665 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   44666 ** or an IO error code if an IO error occurs while rolling back a
   44667 ** savepoint. If no errors occur, SQLITE_OK is returned.
   44668 */
   44669 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   44670   int rc = pPager->errCode;       /* Return code */
   44671 
   44672   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   44673   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   44674 
   44675   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   44676     int ii;            /* Iterator variable */
   44677     int nNew;          /* Number of remaining savepoints after this op. */
   44678 
   44679     /* Figure out how many savepoints will still be active after this
   44680     ** operation. Store this value in nNew. Then free resources associated
   44681     ** with any savepoints that are destroyed by this operation.
   44682     */
   44683     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   44684     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   44685       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   44686     }
   44687     pPager->nSavepoint = nNew;
   44688 
   44689     /* If this is a release of the outermost savepoint, truncate
   44690     ** the sub-journal to zero bytes in size. */
   44691     if( op==SAVEPOINT_RELEASE ){
   44692       if( nNew==0 && isOpen(pPager->sjfd) ){
   44693         /* Only truncate if it is an in-memory sub-journal. */
   44694         if( sqlite3IsMemJournal(pPager->sjfd) ){
   44695           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   44696           assert( rc==SQLITE_OK );
   44697         }
   44698         pPager->nSubRec = 0;
   44699       }
   44700     }
   44701     /* Else this is a rollback operation, playback the specified savepoint.
   44702     ** If this is a temp-file, it is possible that the journal file has
   44703     ** not yet been opened. In this case there have been no changes to
   44704     ** the database file, so the playback operation can be skipped.
   44705     */
   44706     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   44707       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   44708       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   44709       assert(rc!=SQLITE_DONE);
   44710     }
   44711   }
   44712 
   44713   return rc;
   44714 }
   44715 
   44716 /*
   44717 ** Return the full pathname of the database file.
   44718 */
   44719 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
   44720   return pPager->zFilename;
   44721 }
   44722 
   44723 /*
   44724 ** Return the VFS structure for the pager.
   44725 */
   44726 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   44727   return pPager->pVfs;
   44728 }
   44729 
   44730 /*
   44731 ** Return the file handle for the database file associated
   44732 ** with the pager.  This might return NULL if the file has
   44733 ** not yet been opened.
   44734 */
   44735 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   44736   return pPager->fd;
   44737 }
   44738 
   44739 /*
   44740 ** Return the full pathname of the journal file.
   44741 */
   44742 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   44743   return pPager->zJournal;
   44744 }
   44745 
   44746 /*
   44747 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   44748 ** if fsync()s are executed normally.
   44749 */
   44750 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   44751   return pPager->noSync;
   44752 }
   44753 
   44754 #ifdef SQLITE_HAS_CODEC
   44755 /*
   44756 ** Set or retrieve the codec for this pager
   44757 */
   44758 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   44759   Pager *pPager,
   44760   void *(*xCodec)(void*,void*,Pgno,int),
   44761   void (*xCodecSizeChng)(void*,int,int),
   44762   void (*xCodecFree)(void*),
   44763   void *pCodec
   44764 ){
   44765   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   44766   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   44767   pPager->xCodecSizeChng = xCodecSizeChng;
   44768   pPager->xCodecFree = xCodecFree;
   44769   pPager->pCodec = pCodec;
   44770   pagerReportSize(pPager);
   44771 }
   44772 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   44773   return pPager->pCodec;
   44774 }
   44775 #endif
   44776 
   44777 #ifndef SQLITE_OMIT_AUTOVACUUM
   44778 /*
   44779 ** Move the page pPg to location pgno in the file.
   44780 **
   44781 ** There must be no references to the page previously located at
   44782 ** pgno (which we call pPgOld) though that page is allowed to be
   44783 ** in cache.  If the page previously located at pgno is not already
   44784 ** in the rollback journal, it is not put there by by this routine.
   44785 **
   44786 ** References to the page pPg remain valid. Updating any
   44787 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   44788 ** allocated along with the page) is the responsibility of the caller.
   44789 **
   44790 ** A transaction must be active when this routine is called. It used to be
   44791 ** required that a statement transaction was not active, but this restriction
   44792 ** has been removed (CREATE INDEX needs to move a page when a statement
   44793 ** transaction is active).
   44794 **
   44795 ** If the fourth argument, isCommit, is non-zero, then this page is being
   44796 ** moved as part of a database reorganization just before the transaction
   44797 ** is being committed. In this case, it is guaranteed that the database page
   44798 ** pPg refers to will not be written to again within this transaction.
   44799 **
   44800 ** This function may return SQLITE_NOMEM or an IO error code if an error
   44801 ** occurs. Otherwise, it returns SQLITE_OK.
   44802 */
   44803 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   44804   PgHdr *pPgOld;               /* The page being overwritten. */
   44805   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   44806   int rc;                      /* Return code */
   44807   Pgno origPgno;               /* The original page number */
   44808 
   44809   assert( pPg->nRef>0 );
   44810   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   44811        || pPager->eState==PAGER_WRITER_DBMOD
   44812   );
   44813   assert( assert_pager_state(pPager) );
   44814 
   44815   /* In order to be able to rollback, an in-memory database must journal
   44816   ** the page we are moving from.
   44817   */
   44818   if( MEMDB ){
   44819     rc = sqlite3PagerWrite(pPg);
   44820     if( rc ) return rc;
   44821   }
   44822 
   44823   /* If the page being moved is dirty and has not been saved by the latest
   44824   ** savepoint, then save the current contents of the page into the
   44825   ** sub-journal now. This is required to handle the following scenario:
   44826   **
   44827   **   BEGIN;
   44828   **     <journal page X, then modify it in memory>
   44829   **     SAVEPOINT one;
   44830   **       <Move page X to location Y>
   44831   **     ROLLBACK TO one;
   44832   **
   44833   ** If page X were not written to the sub-journal here, it would not
   44834   ** be possible to restore its contents when the "ROLLBACK TO one"
   44835   ** statement were is processed.
   44836   **
   44837   ** subjournalPage() may need to allocate space to store pPg->pgno into
   44838   ** one or more savepoint bitvecs. This is the reason this function
   44839   ** may return SQLITE_NOMEM.
   44840   */
   44841   if( pPg->flags&PGHDR_DIRTY
   44842    && subjRequiresPage(pPg)
   44843    && SQLITE_OK!=(rc = subjournalPage(pPg))
   44844   ){
   44845     return rc;
   44846   }
   44847 
   44848   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   44849       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   44850   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   44851 
   44852   /* If the journal needs to be sync()ed before page pPg->pgno can
   44853   ** be written to, store pPg->pgno in local variable needSyncPgno.
   44854   **
   44855   ** If the isCommit flag is set, there is no need to remember that
   44856   ** the journal needs to be sync()ed before database page pPg->pgno
   44857   ** can be written to. The caller has already promised not to write to it.
   44858   */
   44859   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   44860     needSyncPgno = pPg->pgno;
   44861     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
   44862     assert( pPg->flags&PGHDR_DIRTY );
   44863   }
   44864 
   44865   /* If the cache contains a page with page-number pgno, remove it
   44866   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   44867   ** page pgno before the 'move' operation, it needs to be retained
   44868   ** for the page moved there.
   44869   */
   44870   pPg->flags &= ~PGHDR_NEED_SYNC;
   44871   pPgOld = pager_lookup(pPager, pgno);
   44872   assert( !pPgOld || pPgOld->nRef==1 );
   44873   if( pPgOld ){
   44874     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   44875     if( MEMDB ){
   44876       /* Do not discard pages from an in-memory database since we might
   44877       ** need to rollback later.  Just move the page out of the way. */
   44878       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   44879     }else{
   44880       sqlite3PcacheDrop(pPgOld);
   44881     }
   44882   }
   44883 
   44884   origPgno = pPg->pgno;
   44885   sqlite3PcacheMove(pPg, pgno);
   44886   sqlite3PcacheMakeDirty(pPg);
   44887 
   44888   /* For an in-memory database, make sure the original page continues
   44889   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   44890   ** as the original page since it has already been allocated.
   44891   */
   44892   if( MEMDB ){
   44893     assert( pPgOld );
   44894     sqlite3PcacheMove(pPgOld, origPgno);
   44895     sqlite3PagerUnref(pPgOld);
   44896   }
   44897 
   44898   if( needSyncPgno ){
   44899     /* If needSyncPgno is non-zero, then the journal file needs to be
   44900     ** sync()ed before any data is written to database file page needSyncPgno.
   44901     ** Currently, no such page exists in the page-cache and the
   44902     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   44903     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   44904     ** flag.
   44905     **
   44906     ** If the attempt to load the page into the page-cache fails, (due
   44907     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   44908     ** array. Otherwise, if the page is loaded and written again in
   44909     ** this transaction, it may be written to the database file before
   44910     ** it is synced into the journal file. This way, it may end up in
   44911     ** the journal file twice, but that is not a problem.
   44912     */
   44913     PgHdr *pPgHdr;
   44914     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   44915     if( rc!=SQLITE_OK ){
   44916       if( needSyncPgno<=pPager->dbOrigSize ){
   44917         assert( pPager->pTmpSpace!=0 );
   44918         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   44919       }
   44920       return rc;
   44921     }
   44922     pPgHdr->flags |= PGHDR_NEED_SYNC;
   44923     sqlite3PcacheMakeDirty(pPgHdr);
   44924     sqlite3PagerUnref(pPgHdr);
   44925   }
   44926 
   44927   return SQLITE_OK;
   44928 }
   44929 #endif
   44930 
   44931 /*
   44932 ** Return a pointer to the data for the specified page.
   44933 */
   44934 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   44935   assert( pPg->nRef>0 || pPg->pPager->memDb );
   44936   return pPg->pData;
   44937 }
   44938 
   44939 /*
   44940 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   44941 ** allocated along with the specified page.
   44942 */
   44943 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   44944   return pPg->pExtra;
   44945 }
   44946 
   44947 /*
   44948 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   44949 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   44950 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   44951 ** the locking-mode is set to the value specified.
   44952 **
   44953 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   44954 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   44955 ** locking-mode.
   44956 */
   44957 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   44958   assert( eMode==PAGER_LOCKINGMODE_QUERY
   44959             || eMode==PAGER_LOCKINGMODE_NORMAL
   44960             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   44961   assert( PAGER_LOCKINGMODE_QUERY<0 );
   44962   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   44963   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   44964   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   44965     pPager->exclusiveMode = (u8)eMode;
   44966   }
   44967   return (int)pPager->exclusiveMode;
   44968 }
   44969 
   44970 /*
   44971 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   44972 **
   44973 **    PAGER_JOURNALMODE_DELETE
   44974 **    PAGER_JOURNALMODE_TRUNCATE
   44975 **    PAGER_JOURNALMODE_PERSIST
   44976 **    PAGER_JOURNALMODE_OFF
   44977 **    PAGER_JOURNALMODE_MEMORY
   44978 **    PAGER_JOURNALMODE_WAL
   44979 **
   44980 ** The journalmode is set to the value specified if the change is allowed.
   44981 ** The change may be disallowed for the following reasons:
   44982 **
   44983 **   *  An in-memory database can only have its journal_mode set to _OFF
   44984 **      or _MEMORY.
   44985 **
   44986 **   *  Temporary databases cannot have _WAL journalmode.
   44987 **
   44988 ** The returned indicate the current (possibly updated) journal-mode.
   44989 */
   44990 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   44991   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   44992 
   44993 #ifdef SQLITE_DEBUG
   44994   /* The print_pager_state() routine is intended to be used by the debugger
   44995   ** only.  We invoke it once here to suppress a compiler warning. */
   44996   print_pager_state(pPager);
   44997 #endif
   44998 
   44999 
   45000   /* The eMode parameter is always valid */
   45001   assert(      eMode==PAGER_JOURNALMODE_DELETE
   45002             || eMode==PAGER_JOURNALMODE_TRUNCATE
   45003             || eMode==PAGER_JOURNALMODE_PERSIST
   45004             || eMode==PAGER_JOURNALMODE_OFF
   45005             || eMode==PAGER_JOURNALMODE_WAL
   45006             || eMode==PAGER_JOURNALMODE_MEMORY );
   45007 
   45008   /* This routine is only called from the OP_JournalMode opcode, and
   45009   ** the logic there will never allow a temporary file to be changed
   45010   ** to WAL mode.
   45011   */
   45012   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   45013 
   45014   /* Do allow the journalmode of an in-memory database to be set to
   45015   ** anything other than MEMORY or OFF
   45016   */
   45017   if( MEMDB ){
   45018     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   45019     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   45020       eMode = eOld;
   45021     }
   45022   }
   45023 
   45024   if( eMode!=eOld ){
   45025 
   45026     /* Change the journal mode. */
   45027     assert( pPager->eState!=PAGER_ERROR );
   45028     pPager->journalMode = (u8)eMode;
   45029 
   45030     /* When transistioning from TRUNCATE or PERSIST to any other journal
   45031     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   45032     ** delete the journal file.
   45033     */
   45034     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   45035     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   45036     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   45037     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   45038     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   45039     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   45040 
   45041     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   45042     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   45043 
   45044       /* In this case we would like to delete the journal file. If it is
   45045       ** not possible, then that is not a problem. Deleting the journal file
   45046       ** here is an optimization only.
   45047       **
   45048       ** Before deleting the journal file, obtain a RESERVED lock on the
   45049       ** database file. This ensures that the journal file is not deleted
   45050       ** while it is in use by some other client.
   45051       */
   45052       sqlite3OsClose(pPager->jfd);
   45053       if( pPager->eLock>=RESERVED_LOCK ){
   45054         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   45055       }else{
   45056         int rc = SQLITE_OK;
   45057         int state = pPager->eState;
   45058         assert( state==PAGER_OPEN || state==PAGER_READER );
   45059         if( state==PAGER_OPEN ){
   45060           rc = sqlite3PagerSharedLock(pPager);
   45061         }
   45062         if( pPager->eState==PAGER_READER ){
   45063           assert( rc==SQLITE_OK );
   45064           rc = pagerLockDb(pPager, RESERVED_LOCK);
   45065         }
   45066         if( rc==SQLITE_OK ){
   45067           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   45068         }
   45069         if( rc==SQLITE_OK && state==PAGER_READER ){
   45070           pagerUnlockDb(pPager, SHARED_LOCK);
   45071         }else if( state==PAGER_OPEN ){
   45072           pager_unlock(pPager);
   45073         }
   45074         assert( state==pPager->eState );
   45075       }
   45076     }
   45077   }
   45078 
   45079   /* Return the new journal mode */
   45080   return (int)pPager->journalMode;
   45081 }
   45082 
   45083 /*
   45084 ** Return the current journal mode.
   45085 */
   45086 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   45087   return (int)pPager->journalMode;
   45088 }
   45089 
   45090 /*
   45091 ** Return TRUE if the pager is in a state where it is OK to change the
   45092 ** journalmode.  Journalmode changes can only happen when the database
   45093 ** is unmodified.
   45094 */
   45095 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   45096   assert( assert_pager_state(pPager) );
   45097   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   45098   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   45099   return 1;
   45100 }
   45101 
   45102 /*
   45103 ** Get/set the size-limit used for persistent journal files.
   45104 **
   45105 ** Setting the size limit to -1 means no limit is enforced.
   45106 ** An attempt to set a limit smaller than -1 is a no-op.
   45107 */
   45108 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   45109   if( iLimit>=-1 ){
   45110     pPager->journalSizeLimit = iLimit;
   45111     sqlite3WalLimit(pPager->pWal, iLimit);
   45112   }
   45113   return pPager->journalSizeLimit;
   45114 }
   45115 
   45116 /*
   45117 ** Return a pointer to the pPager->pBackup variable. The backup module
   45118 ** in backup.c maintains the content of this variable. This module
   45119 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   45120 ** sqlite3BackupUpdate() only.
   45121 */
   45122 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   45123   return &pPager->pBackup;
   45124 }
   45125 
   45126 #ifndef SQLITE_OMIT_VACUUM
   45127 /*
   45128 ** Unless this is an in-memory or temporary database, clear the pager cache.
   45129 */
   45130 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
   45131   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
   45132 }
   45133 #endif
   45134 
   45135 #ifndef SQLITE_OMIT_WAL
   45136 /*
   45137 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
   45138 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
   45139 ** or wal_blocking_checkpoint() API functions.
   45140 **
   45141 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   45142 */
   45143 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
   45144   int rc = SQLITE_OK;
   45145   if( pPager->pWal ){
   45146     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
   45147         pPager->xBusyHandler, pPager->pBusyHandlerArg,
   45148         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
   45149         pnLog, pnCkpt
   45150     );
   45151   }
   45152   return rc;
   45153 }
   45154 
   45155 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   45156   return sqlite3WalCallback(pPager->pWal);
   45157 }
   45158 
   45159 /*
   45160 ** Return true if the underlying VFS for the given pager supports the
   45161 ** primitives necessary for write-ahead logging.
   45162 */
   45163 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   45164   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   45165   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   45166 }
   45167 
   45168 /*
   45169 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   45170 ** is obtained instead, immediately release it.
   45171 */
   45172 static int pagerExclusiveLock(Pager *pPager){
   45173   int rc;                         /* Return code */
   45174 
   45175   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   45176   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   45177   if( rc!=SQLITE_OK ){
   45178     /* If the attempt to grab the exclusive lock failed, release the
   45179     ** pending lock that may have been obtained instead.  */
   45180     pagerUnlockDb(pPager, SHARED_LOCK);
   45181   }
   45182 
   45183   return rc;
   45184 }
   45185 
   45186 /*
   45187 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   45188 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   45189 ** lock on the database file and use heap-memory to store the wal-index
   45190 ** in. Otherwise, use the normal shared-memory.
   45191 */
   45192 static int pagerOpenWal(Pager *pPager){
   45193   int rc = SQLITE_OK;
   45194 
   45195   assert( pPager->pWal==0 && pPager->tempFile==0 );
   45196   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   45197 
   45198   /* If the pager is already in exclusive-mode, the WAL module will use
   45199   ** heap-memory for the wal-index instead of the VFS shared-memory
   45200   ** implementation. Take the exclusive lock now, before opening the WAL
   45201   ** file, to make sure this is safe.
   45202   */
   45203   if( pPager->exclusiveMode ){
   45204     rc = pagerExclusiveLock(pPager);
   45205   }
   45206 
   45207   /* Open the connection to the log file. If this operation fails,
   45208   ** (e.g. due to malloc() failure), return an error code.
   45209   */
   45210   if( rc==SQLITE_OK ){
   45211     rc = sqlite3WalOpen(pPager->pVfs,
   45212         pPager->fd, pPager->zWal, pPager->exclusiveMode,
   45213         pPager->journalSizeLimit, &pPager->pWal
   45214     );
   45215   }
   45216 
   45217   return rc;
   45218 }
   45219 
   45220 
   45221 /*
   45222 ** The caller must be holding a SHARED lock on the database file to call
   45223 ** this function.
   45224 **
   45225 ** If the pager passed as the first argument is open on a real database
   45226 ** file (not a temp file or an in-memory database), and the WAL file
   45227 ** is not already open, make an attempt to open it now. If successful,
   45228 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   45229 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   45230 ** not modified in either case.
   45231 **
   45232 ** If the pager is open on a temp-file (or in-memory database), or if
   45233 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   45234 ** without doing anything.
   45235 */
   45236 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   45237   Pager *pPager,                  /* Pager object */
   45238   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   45239 ){
   45240   int rc = SQLITE_OK;             /* Return code */
   45241 
   45242   assert( assert_pager_state(pPager) );
   45243   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   45244   assert( pPager->eState==PAGER_READER || !pbOpen );
   45245   assert( pbOpen==0 || *pbOpen==0 );
   45246   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   45247 
   45248   if( !pPager->tempFile && !pPager->pWal ){
   45249     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   45250 
   45251     /* Close any rollback journal previously open */
   45252     sqlite3OsClose(pPager->jfd);
   45253 
   45254     rc = pagerOpenWal(pPager);
   45255     if( rc==SQLITE_OK ){
   45256       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   45257       pPager->eState = PAGER_OPEN;
   45258     }
   45259   }else{
   45260     *pbOpen = 1;
   45261   }
   45262 
   45263   return rc;
   45264 }
   45265 
   45266 /*
   45267 ** This function is called to close the connection to the log file prior
   45268 ** to switching from WAL to rollback mode.
   45269 **
   45270 ** Before closing the log file, this function attempts to take an
   45271 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   45272 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   45273 ** If successful, the EXCLUSIVE lock is not released before returning.
   45274 */
   45275 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
   45276   int rc = SQLITE_OK;
   45277 
   45278   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   45279 
   45280   /* If the log file is not already open, but does exist in the file-system,
   45281   ** it may need to be checkpointed before the connection can switch to
   45282   ** rollback mode. Open it now so this can happen.
   45283   */
   45284   if( !pPager->pWal ){
   45285     int logexists = 0;
   45286     rc = pagerLockDb(pPager, SHARED_LOCK);
   45287     if( rc==SQLITE_OK ){
   45288       rc = sqlite3OsAccess(
   45289           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   45290       );
   45291     }
   45292     if( rc==SQLITE_OK && logexists ){
   45293       rc = pagerOpenWal(pPager);
   45294     }
   45295   }
   45296 
   45297   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   45298   ** the database file, the log and log-summary files will be deleted.
   45299   */
   45300   if( rc==SQLITE_OK && pPager->pWal ){
   45301     rc = pagerExclusiveLock(pPager);
   45302     if( rc==SQLITE_OK ){
   45303       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
   45304                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   45305       pPager->pWal = 0;
   45306     }
   45307   }
   45308   return rc;
   45309 }
   45310 
   45311 #ifdef SQLITE_ENABLE_ZIPVFS
   45312 /*
   45313 ** A read-lock must be held on the pager when this function is called. If
   45314 ** the pager is in WAL mode and the WAL file currently contains one or more
   45315 ** frames, return the size in bytes of the page images stored within the
   45316 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
   45317 ** is empty, return 0.
   45318 */
   45319 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
   45320   assert( pPager->eState==PAGER_READER );
   45321   return sqlite3WalFramesize(pPager->pWal);
   45322 }
   45323 #endif
   45324 
   45325 #ifdef SQLITE_HAS_CODEC
   45326 /*
   45327 ** This function is called by the wal module when writing page content
   45328 ** into the log file.
   45329 **
   45330 ** This function returns a pointer to a buffer containing the encrypted
   45331 ** page content. If a malloc fails, this function may return NULL.
   45332 */
   45333 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   45334   void *aData = 0;
   45335   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   45336   return aData;
   45337 }
   45338 #endif /* SQLITE_HAS_CODEC */
   45339 
   45340 #endif /* !SQLITE_OMIT_WAL */
   45341 
   45342 #endif /* SQLITE_OMIT_DISKIO */
   45343 
   45344 /************** End of pager.c ***********************************************/
   45345 /************** Begin file wal.c *********************************************/
   45346 /*
   45347 ** 2010 February 1
   45348 **
   45349 ** The author disclaims copyright to this source code.  In place of
   45350 ** a legal notice, here is a blessing:
   45351 **
   45352 **    May you do good and not evil.
   45353 **    May you find forgiveness for yourself and forgive others.
   45354 **    May you share freely, never taking more than you give.
   45355 **
   45356 *************************************************************************
   45357 **
   45358 ** This file contains the implementation of a write-ahead log (WAL) used in
   45359 ** "journal_mode=WAL" mode.
   45360 **
   45361 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   45362 **
   45363 ** A WAL file consists of a header followed by zero or more "frames".
   45364 ** Each frame records the revised content of a single page from the
   45365 ** database file.  All changes to the database are recorded by writing
   45366 ** frames into the WAL.  Transactions commit when a frame is written that
   45367 ** contains a commit marker.  A single WAL can and usually does record
   45368 ** multiple transactions.  Periodically, the content of the WAL is
   45369 ** transferred back into the database file in an operation called a
   45370 ** "checkpoint".
   45371 **
   45372 ** A single WAL file can be used multiple times.  In other words, the
   45373 ** WAL can fill up with frames and then be checkpointed and then new
   45374 ** frames can overwrite the old ones.  A WAL always grows from beginning
   45375 ** toward the end.  Checksums and counters attached to each frame are
   45376 ** used to determine which frames within the WAL are valid and which
   45377 ** are leftovers from prior checkpoints.
   45378 **
   45379 ** The WAL header is 32 bytes in size and consists of the following eight
   45380 ** big-endian 32-bit unsigned integer values:
   45381 **
   45382 **     0: Magic number.  0x377f0682 or 0x377f0683
   45383 **     4: File format version.  Currently 3007000
   45384 **     8: Database page size.  Example: 1024
   45385 **    12: Checkpoint sequence number
   45386 **    16: Salt-1, random integer incremented with each checkpoint
   45387 **    20: Salt-2, a different random integer changing with each ckpt
   45388 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   45389 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   45390 **
   45391 ** Immediately following the wal-header are zero or more frames. Each
   45392 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   45393 ** of page data. The frame-header is six big-endian 32-bit unsigned
   45394 ** integer values, as follows:
   45395 **
   45396 **     0: Page number.
   45397 **     4: For commit records, the size of the database image in pages
   45398 **        after the commit. For all other records, zero.
   45399 **     8: Salt-1 (copied from the header)
   45400 **    12: Salt-2 (copied from the header)
   45401 **    16: Checksum-1.
   45402 **    20: Checksum-2.
   45403 **
   45404 ** A frame is considered valid if and only if the following conditions are
   45405 ** true:
   45406 **
   45407 **    (1) The salt-1 and salt-2 values in the frame-header match
   45408 **        salt values in the wal-header
   45409 **
   45410 **    (2) The checksum values in the final 8 bytes of the frame-header
   45411 **        exactly match the checksum computed consecutively on the
   45412 **        WAL header and the first 8 bytes and the content of all frames
   45413 **        up to and including the current frame.
   45414 **
   45415 ** The checksum is computed using 32-bit big-endian integers if the
   45416 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   45417 ** is computed using little-endian if the magic number is 0x377f0682.
   45418 ** The checksum values are always stored in the frame header in a
   45419 ** big-endian format regardless of which byte order is used to compute
   45420 ** the checksum.  The checksum is computed by interpreting the input as
   45421 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   45422 ** algorithm used for the checksum is as follows:
   45423 **
   45424 **   for i from 0 to n-1 step 2:
   45425 **     s0 += x[i] + s1;
   45426 **     s1 += x[i+1] + s0;
   45427 **   endfor
   45428 **
   45429 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   45430 ** in reverse order (the largest fibonacci weight occurs on the first element
   45431 ** of the sequence being summed.)  The s1 value spans all 32-bit
   45432 ** terms of the sequence whereas s0 omits the final term.
   45433 **
   45434 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   45435 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   45436 ** The VFS.xSync operations serve as write barriers - all writes launched
   45437 ** before the xSync must complete before any write that launches after the
   45438 ** xSync begins.
   45439 **
   45440 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   45441 ** value is randomized.  This prevents old and new frames in the WAL from
   45442 ** being considered valid at the same time and being checkpointing together
   45443 ** following a crash.
   45444 **
   45445 ** READER ALGORITHM
   45446 **
   45447 ** To read a page from the database (call it page number P), a reader
   45448 ** first checks the WAL to see if it contains page P.  If so, then the
   45449 ** last valid instance of page P that is a followed by a commit frame
   45450 ** or is a commit frame itself becomes the value read.  If the WAL
   45451 ** contains no copies of page P that are valid and which are a commit
   45452 ** frame or are followed by a commit frame, then page P is read from
   45453 ** the database file.
   45454 **
   45455 ** To start a read transaction, the reader records the index of the last
   45456 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   45457 ** for all subsequent read operations.  New transactions can be appended
   45458 ** to the WAL, but as long as the reader uses its original mxFrame value
   45459 ** and ignores the newly appended content, it will see a consistent snapshot
   45460 ** of the database from a single point in time.  This technique allows
   45461 ** multiple concurrent readers to view different versions of the database
   45462 ** content simultaneously.
   45463 **
   45464 ** The reader algorithm in the previous paragraphs works correctly, but
   45465 ** because frames for page P can appear anywhere within the WAL, the
   45466 ** reader has to scan the entire WAL looking for page P frames.  If the
   45467 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   45468 ** and read performance suffers.  To overcome this problem, a separate
   45469 ** data structure called the wal-index is maintained to expedite the
   45470 ** search for frames of a particular page.
   45471 **
   45472 ** WAL-INDEX FORMAT
   45473 **
   45474 ** Conceptually, the wal-index is shared memory, though VFS implementations
   45475 ** might choose to implement the wal-index using a mmapped file.  Because
   45476 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   45477 ** on a network filesystem.  All users of the database must be able to
   45478 ** share memory.
   45479 **
   45480 ** The wal-index is transient.  After a crash, the wal-index can (and should
   45481 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   45482 ** to either truncate or zero the header of the wal-index when the last
   45483 ** connection to it closes.  Because the wal-index is transient, it can
   45484 ** use an architecture-specific format; it does not have to be cross-platform.
   45485 ** Hence, unlike the database and WAL file formats which store all values
   45486 ** as big endian, the wal-index can store multi-byte values in the native
   45487 ** byte order of the host computer.
   45488 **
   45489 ** The purpose of the wal-index is to answer this question quickly:  Given
   45490 ** a page number P, return the index of the last frame for page P in the WAL,
   45491 ** or return NULL if there are no frames for page P in the WAL.
   45492 **
   45493 ** The wal-index consists of a header region, followed by an one or
   45494 ** more index blocks.
   45495 **
   45496 ** The wal-index header contains the total number of frames within the WAL
   45497 ** in the the mxFrame field.
   45498 **
   45499 ** Each index block except for the first contains information on
   45500 ** HASHTABLE_NPAGE frames. The first index block contains information on
   45501 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   45502 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   45503 ** first index block are the same size as all other index blocks in the
   45504 ** wal-index.
   45505 **
   45506 ** Each index block contains two sections, a page-mapping that contains the
   45507 ** database page number associated with each wal frame, and a hash-table
   45508 ** that allows readers to query an index block for a specific page number.
   45509 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   45510 ** for the first index block) 32-bit page numbers. The first entry in the
   45511 ** first index-block contains the database page number corresponding to the
   45512 ** first frame in the WAL file. The first entry in the second index block
   45513 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   45514 ** the log, and so on.
   45515 **
   45516 ** The last index block in a wal-index usually contains less than the full
   45517 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   45518 ** depending on the contents of the WAL file. This does not change the
   45519 ** allocated size of the page-mapping array - the page-mapping array merely
   45520 ** contains unused entries.
   45521 **
   45522 ** Even without using the hash table, the last frame for page P
   45523 ** can be found by scanning the page-mapping sections of each index block
   45524 ** starting with the last index block and moving toward the first, and
   45525 ** within each index block, starting at the end and moving toward the
   45526 ** beginning.  The first entry that equals P corresponds to the frame
   45527 ** holding the content for that page.
   45528 **
   45529 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   45530 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   45531 ** hash table for each page number in the mapping section, so the hash
   45532 ** table is never more than half full.  The expected number of collisions
   45533 ** prior to finding a match is 1.  Each entry of the hash table is an
   45534 ** 1-based index of an entry in the mapping section of the same
   45535 ** index block.   Let K be the 1-based index of the largest entry in
   45536 ** the mapping section.  (For index blocks other than the last, K will
   45537 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   45538 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   45539 ** contain a value of 0.
   45540 **
   45541 ** To look for page P in the hash table, first compute a hash iKey on
   45542 ** P as follows:
   45543 **
   45544 **      iKey = (P * 383) % HASHTABLE_NSLOT
   45545 **
   45546 ** Then start scanning entries of the hash table, starting with iKey
   45547 ** (wrapping around to the beginning when the end of the hash table is
   45548 ** reached) until an unused hash slot is found. Let the first unused slot
   45549 ** be at index iUnused.  (iUnused might be less than iKey if there was
   45550 ** wrap-around.) Because the hash table is never more than half full,
   45551 ** the search is guaranteed to eventually hit an unused entry.  Let
   45552 ** iMax be the value between iKey and iUnused, closest to iUnused,
   45553 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   45554 ** no hash slot such that aHash[i]==p) then page P is not in the
   45555 ** current index block.  Otherwise the iMax-th mapping entry of the
   45556 ** current index block corresponds to the last entry that references
   45557 ** page P.
   45558 **
   45559 ** A hash search begins with the last index block and moves toward the
   45560 ** first index block, looking for entries corresponding to page P.  On
   45561 ** average, only two or three slots in each index block need to be
   45562 ** examined in order to either find the last entry for page P, or to
   45563 ** establish that no such entry exists in the block.  Each index block
   45564 ** holds over 4000 entries.  So two or three index blocks are sufficient
   45565 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   45566 ** comparisons (on average) suffice to either locate a frame in the
   45567 ** WAL or to establish that the frame does not exist in the WAL.  This
   45568 ** is much faster than scanning the entire 10MB WAL.
   45569 **
   45570 ** Note that entries are added in order of increasing K.  Hence, one
   45571 ** reader might be using some value K0 and a second reader that started
   45572 ** at a later time (after additional transactions were added to the WAL
   45573 ** and to the wal-index) might be using a different value K1, where K1>K0.
   45574 ** Both readers can use the same hash table and mapping section to get
   45575 ** the correct result.  There may be entries in the hash table with
   45576 ** K>K0 but to the first reader, those entries will appear to be unused
   45577 ** slots in the hash table and so the first reader will get an answer as
   45578 ** if no values greater than K0 had ever been inserted into the hash table
   45579 ** in the first place - which is what reader one wants.  Meanwhile, the
   45580 ** second reader using K1 will see additional values that were inserted
   45581 ** later, which is exactly what reader two wants.
   45582 **
   45583 ** When a rollback occurs, the value of K is decreased. Hash table entries
   45584 ** that correspond to frames greater than the new K value are removed
   45585 ** from the hash table at this point.
   45586 */
   45587 #ifndef SQLITE_OMIT_WAL
   45588 
   45589 
   45590 /*
   45591 ** Trace output macros
   45592 */
   45593 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   45594 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   45595 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   45596 #else
   45597 # define WALTRACE(X)
   45598 #endif
   45599 
   45600 /*
   45601 ** The maximum (and only) versions of the wal and wal-index formats
   45602 ** that may be interpreted by this version of SQLite.
   45603 **
   45604 ** If a client begins recovering a WAL file and finds that (a) the checksum
   45605 ** values in the wal-header are correct and (b) the version field is not
   45606 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   45607 **
   45608 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   45609 ** checksum test is successful) and finds that the version field is not
   45610 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   45611 ** returns SQLITE_CANTOPEN.
   45612 */
   45613 #define WAL_MAX_VERSION      3007000
   45614 #define WALINDEX_MAX_VERSION 3007000
   45615 
   45616 /*
   45617 ** Indices of various locking bytes.   WAL_NREADER is the number
   45618 ** of available reader locks and should be at least 3.
   45619 */
   45620 #define WAL_WRITE_LOCK         0
   45621 #define WAL_ALL_BUT_WRITE      1
   45622 #define WAL_CKPT_LOCK          1
   45623 #define WAL_RECOVER_LOCK       2
   45624 #define WAL_READ_LOCK(I)       (3+(I))
   45625 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   45626 
   45627 
   45628 /* Object declarations */
   45629 typedef struct WalIndexHdr WalIndexHdr;
   45630 typedef struct WalIterator WalIterator;
   45631 typedef struct WalCkptInfo WalCkptInfo;
   45632 
   45633 
   45634 /*
   45635 ** The following object holds a copy of the wal-index header content.
   45636 **
   45637 ** The actual header in the wal-index consists of two copies of this
   45638 ** object.
   45639 **
   45640 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   45641 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   45642 ** added in 3.7.1 when support for 64K pages was added.
   45643 */
   45644 struct WalIndexHdr {
   45645   u32 iVersion;                   /* Wal-index version */
   45646   u32 unused;                     /* Unused (padding) field */
   45647   u32 iChange;                    /* Counter incremented each transaction */
   45648   u8 isInit;                      /* 1 when initialized */
   45649   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   45650   u16 szPage;                     /* Database page size in bytes. 1==64K */
   45651   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   45652   u32 nPage;                      /* Size of database in pages */
   45653   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   45654   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   45655   u32 aCksum[2];                  /* Checksum over all prior fields */
   45656 };
   45657 
   45658 /*
   45659 ** A copy of the following object occurs in the wal-index immediately
   45660 ** following the second copy of the WalIndexHdr.  This object stores
   45661 ** information used by checkpoint.
   45662 **
   45663 ** nBackfill is the number of frames in the WAL that have been written
   45664 ** back into the database. (We call the act of moving content from WAL to
   45665 ** database "backfilling".)  The nBackfill number is never greater than
   45666 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   45667 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   45668 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   45669 ** mxFrame back to zero when the WAL is reset.
   45670 **
   45671 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   45672 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   45673 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   45674 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   45675 ** a special case; its value is never used and it exists as a place-holder
   45676 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   45677 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   45678 ** directly from the database.
   45679 **
   45680 ** The value of aReadMark[K] may only be changed by a thread that
   45681 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   45682 ** aReadMark[K] cannot changed while there is a reader is using that mark
   45683 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   45684 **
   45685 ** The checkpointer may only transfer frames from WAL to database where
   45686 ** the frame numbers are less than or equal to every aReadMark[] that is
   45687 ** in use (that is, every aReadMark[j] for which there is a corresponding
   45688 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   45689 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   45690 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   45691 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   45692 ** in the WAL has been backfilled into the database) then new readers
   45693 ** will choose aReadMark[0] which has value 0 and hence such reader will
   45694 ** get all their all content directly from the database file and ignore
   45695 ** the WAL.
   45696 **
   45697 ** Writers normally append new frames to the end of the WAL.  However,
   45698 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   45699 ** written back into the database) and if no readers are using the WAL
   45700 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   45701 ** the writer will first "reset" the WAL back to the beginning and start
   45702 ** writing new content beginning at frame 1.
   45703 **
   45704 ** We assume that 32-bit loads are atomic and so no locks are needed in
   45705 ** order to read from any aReadMark[] entries.
   45706 */
   45707 struct WalCkptInfo {
   45708   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   45709   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   45710 };
   45711 #define READMARK_NOT_USED  0xffffffff
   45712 
   45713 
   45714 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   45715 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   45716 ** only support mandatory file-locks, we do not read or write data
   45717 ** from the region of the file on which locks are applied.
   45718 */
   45719 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
   45720 #define WALINDEX_LOCK_RESERVED 16
   45721 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
   45722 
   45723 /* Size of header before each frame in wal */
   45724 #define WAL_FRAME_HDRSIZE 24
   45725 
   45726 /* Size of write ahead log header, including checksum. */
   45727 /* #define WAL_HDRSIZE 24 */
   45728 #define WAL_HDRSIZE 32
   45729 
   45730 /* WAL magic value. Either this value, or the same value with the least
   45731 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   45732 ** big-endian format in the first 4 bytes of a WAL file.
   45733 **
   45734 ** If the LSB is set, then the checksums for each frame within the WAL
   45735 ** file are calculated by treating all data as an array of 32-bit
   45736 ** big-endian words. Otherwise, they are calculated by interpreting
   45737 ** all data as 32-bit little-endian words.
   45738 */
   45739 #define WAL_MAGIC 0x377f0682
   45740 
   45741 /*
   45742 ** Return the offset of frame iFrame in the write-ahead log file,
   45743 ** assuming a database page size of szPage bytes. The offset returned
   45744 ** is to the start of the write-ahead log frame-header.
   45745 */
   45746 #define walFrameOffset(iFrame, szPage) (                               \
   45747   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   45748 )
   45749 
   45750 /*
   45751 ** An open write-ahead log file is represented by an instance of the
   45752 ** following object.
   45753 */
   45754 struct Wal {
   45755   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   45756   sqlite3_file *pDbFd;       /* File handle for the database file */
   45757   sqlite3_file *pWalFd;      /* File handle for WAL file */
   45758   u32 iCallback;             /* Value to pass to log callback (or 0) */
   45759   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
   45760   int nWiData;               /* Size of array apWiData */
   45761   int szFirstBlock;          /* Size of first block written to WAL file */
   45762   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   45763   u32 szPage;                /* Database page size */
   45764   i16 readLock;              /* Which read lock is being held.  -1 for none */
   45765   u8 syncFlags;              /* Flags to use to sync header writes */
   45766   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   45767   u8 writeLock;              /* True if in a write transaction */
   45768   u8 ckptLock;               /* True if holding a checkpoint lock */
   45769   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
   45770   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
   45771   u8 syncHeader;             /* Fsync the WAL header if true */
   45772   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
   45773   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   45774   const char *zWalName;      /* Name of WAL file */
   45775   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   45776 #ifdef SQLITE_DEBUG
   45777   u8 lockError;              /* True if a locking error has occurred */
   45778 #endif
   45779 };
   45780 
   45781 /*
   45782 ** Candidate values for Wal.exclusiveMode.
   45783 */
   45784 #define WAL_NORMAL_MODE     0
   45785 #define WAL_EXCLUSIVE_MODE  1
   45786 #define WAL_HEAPMEMORY_MODE 2
   45787 
   45788 /*
   45789 ** Possible values for WAL.readOnly
   45790 */
   45791 #define WAL_RDWR        0    /* Normal read/write connection */
   45792 #define WAL_RDONLY      1    /* The WAL file is readonly */
   45793 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
   45794 
   45795 /*
   45796 ** Each page of the wal-index mapping contains a hash-table made up of
   45797 ** an array of HASHTABLE_NSLOT elements of the following type.
   45798 */
   45799 typedef u16 ht_slot;
   45800 
   45801 /*
   45802 ** This structure is used to implement an iterator that loops through
   45803 ** all frames in the WAL in database page order. Where two or more frames
   45804 ** correspond to the same database page, the iterator visits only the
   45805 ** frame most recently written to the WAL (in other words, the frame with
   45806 ** the largest index).
   45807 **
   45808 ** The internals of this structure are only accessed by:
   45809 **
   45810 **   walIteratorInit() - Create a new iterator,
   45811 **   walIteratorNext() - Step an iterator,
   45812 **   walIteratorFree() - Free an iterator.
   45813 **
   45814 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   45815 */
   45816 struct WalIterator {
   45817   int iPrior;                     /* Last result returned from the iterator */
   45818   int nSegment;                   /* Number of entries in aSegment[] */
   45819   struct WalSegment {
   45820     int iNext;                    /* Next slot in aIndex[] not yet returned */
   45821     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   45822     u32 *aPgno;                   /* Array of page numbers. */
   45823     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
   45824     int iZero;                    /* Frame number associated with aPgno[0] */
   45825   } aSegment[1];                  /* One for every 32KB page in the wal-index */
   45826 };
   45827 
   45828 /*
   45829 ** Define the parameters of the hash tables in the wal-index file. There
   45830 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   45831 ** wal-index.
   45832 **
   45833 ** Changing any of these constants will alter the wal-index format and
   45834 ** create incompatibilities.
   45835 */
   45836 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   45837 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   45838 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   45839 
   45840 /*
   45841 ** The block of page numbers associated with the first hash-table in a
   45842 ** wal-index is smaller than usual. This is so that there is a complete
   45843 ** hash-table on each aligned 32KB page of the wal-index.
   45844 */
   45845 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   45846 
   45847 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   45848 #define WALINDEX_PGSZ   (                                         \
   45849     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   45850 )
   45851 
   45852 /*
   45853 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   45854 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   45855 ** numbered from zero.
   45856 **
   45857 ** If this call is successful, *ppPage is set to point to the wal-index
   45858 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   45859 ** then an SQLite error code is returned and *ppPage is set to 0.
   45860 */
   45861 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   45862   int rc = SQLITE_OK;
   45863 
   45864   /* Enlarge the pWal->apWiData[] array if required */
   45865   if( pWal->nWiData<=iPage ){
   45866     int nByte = sizeof(u32*)*(iPage+1);
   45867     volatile u32 **apNew;
   45868     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
   45869     if( !apNew ){
   45870       *ppPage = 0;
   45871       return SQLITE_NOMEM;
   45872     }
   45873     memset((void*)&apNew[pWal->nWiData], 0,
   45874            sizeof(u32*)*(iPage+1-pWal->nWiData));
   45875     pWal->apWiData = apNew;
   45876     pWal->nWiData = iPage+1;
   45877   }
   45878 
   45879   /* Request a pointer to the required page from the VFS */
   45880   if( pWal->apWiData[iPage]==0 ){
   45881     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   45882       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   45883       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
   45884     }else{
   45885       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   45886           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   45887       );
   45888       if( rc==SQLITE_READONLY ){
   45889         pWal->readOnly |= WAL_SHM_RDONLY;
   45890         rc = SQLITE_OK;
   45891       }
   45892     }
   45893   }
   45894 
   45895   *ppPage = pWal->apWiData[iPage];
   45896   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   45897   return rc;
   45898 }
   45899 
   45900 /*
   45901 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   45902 */
   45903 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   45904   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   45905   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   45906 }
   45907 
   45908 /*
   45909 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   45910 */
   45911 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   45912   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   45913   return (volatile WalIndexHdr*)pWal->apWiData[0];
   45914 }
   45915 
   45916 /*
   45917 ** The argument to this macro must be of type u32. On a little-endian
   45918 ** architecture, it returns the u32 value that results from interpreting
   45919 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   45920 ** returns the value that would be produced by intepreting the 4 bytes
   45921 ** of the input value as a little-endian integer.
   45922 */
   45923 #define BYTESWAP32(x) ( \
   45924     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   45925   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   45926 )
   45927 
   45928 /*
   45929 ** Generate or extend an 8 byte checksum based on the data in
   45930 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   45931 ** initial values of 0 and 0 if aIn==NULL).
   45932 **
   45933 ** The checksum is written back into aOut[] before returning.
   45934 **
   45935 ** nByte must be a positive multiple of 8.
   45936 */
   45937 static void walChecksumBytes(
   45938   int nativeCksum, /* True for native byte-order, false for non-native */
   45939   u8 *a,           /* Content to be checksummed */
   45940   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   45941   const u32 *aIn,  /* Initial checksum value input */
   45942   u32 *aOut        /* OUT: Final checksum value output */
   45943 ){
   45944   u32 s1, s2;
   45945   u32 *aData = (u32 *)a;
   45946   u32 *aEnd = (u32 *)&a[nByte];
   45947 
   45948   if( aIn ){
   45949     s1 = aIn[0];
   45950     s2 = aIn[1];
   45951   }else{
   45952     s1 = s2 = 0;
   45953   }
   45954 
   45955   assert( nByte>=8 );
   45956   assert( (nByte&0x00000007)==0 );
   45957 
   45958   if( nativeCksum ){
   45959     do {
   45960       s1 += *aData++ + s2;
   45961       s2 += *aData++ + s1;
   45962     }while( aData<aEnd );
   45963   }else{
   45964     do {
   45965       s1 += BYTESWAP32(aData[0]) + s2;
   45966       s2 += BYTESWAP32(aData[1]) + s1;
   45967       aData += 2;
   45968     }while( aData<aEnd );
   45969   }
   45970 
   45971   aOut[0] = s1;
   45972   aOut[1] = s2;
   45973 }
   45974 
   45975 static void walShmBarrier(Wal *pWal){
   45976   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   45977     sqlite3OsShmBarrier(pWal->pDbFd);
   45978   }
   45979 }
   45980 
   45981 /*
   45982 ** Write the header information in pWal->hdr into the wal-index.
   45983 **
   45984 ** The checksum on pWal->hdr is updated before it is written.
   45985 */
   45986 static void walIndexWriteHdr(Wal *pWal){
   45987   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   45988   const int nCksum = offsetof(WalIndexHdr, aCksum);
   45989 
   45990   assert( pWal->writeLock );
   45991   pWal->hdr.isInit = 1;
   45992   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   45993   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   45994   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   45995   walShmBarrier(pWal);
   45996   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   45997 }
   45998 
   45999 /*
   46000 ** This function encodes a single frame header and writes it to a buffer
   46001 ** supplied by the caller. A frame-header is made up of a series of
   46002 ** 4-byte big-endian integers, as follows:
   46003 **
   46004 **     0: Page number.
   46005 **     4: For commit records, the size of the database image in pages
   46006 **        after the commit. For all other records, zero.
   46007 **     8: Salt-1 (copied from the wal-header)
   46008 **    12: Salt-2 (copied from the wal-header)
   46009 **    16: Checksum-1.
   46010 **    20: Checksum-2.
   46011 */
   46012 static void walEncodeFrame(
   46013   Wal *pWal,                      /* The write-ahead log */
   46014   u32 iPage,                      /* Database page number for frame */
   46015   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   46016   u8 *aData,                      /* Pointer to page data */
   46017   u8 *aFrame                      /* OUT: Write encoded frame here */
   46018 ){
   46019   int nativeCksum;                /* True for native byte-order checksums */
   46020   u32 *aCksum = pWal->hdr.aFrameCksum;
   46021   assert( WAL_FRAME_HDRSIZE==24 );
   46022   sqlite3Put4byte(&aFrame[0], iPage);
   46023   sqlite3Put4byte(&aFrame[4], nTruncate);
   46024   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   46025 
   46026   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   46027   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   46028   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   46029 
   46030   sqlite3Put4byte(&aFrame[16], aCksum[0]);
   46031   sqlite3Put4byte(&aFrame[20], aCksum[1]);
   46032 }
   46033 
   46034 /*
   46035 ** Check to see if the frame with header in aFrame[] and content
   46036 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   46037 ** *pnTruncate and return true.  Return if the frame is not valid.
   46038 */
   46039 static int walDecodeFrame(
   46040   Wal *pWal,                      /* The write-ahead log */
   46041   u32 *piPage,                    /* OUT: Database page number for frame */
   46042   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   46043   u8 *aData,                      /* Pointer to page data (for checksum) */
   46044   u8 *aFrame                      /* Frame data */
   46045 ){
   46046   int nativeCksum;                /* True for native byte-order checksums */
   46047   u32 *aCksum = pWal->hdr.aFrameCksum;
   46048   u32 pgno;                       /* Page number of the frame */
   46049   assert( WAL_FRAME_HDRSIZE==24 );
   46050 
   46051   /* A frame is only valid if the salt values in the frame-header
   46052   ** match the salt values in the wal-header.
   46053   */
   46054   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   46055     return 0;
   46056   }
   46057 
   46058   /* A frame is only valid if the page number is creater than zero.
   46059   */
   46060   pgno = sqlite3Get4byte(&aFrame[0]);
   46061   if( pgno==0 ){
   46062     return 0;
   46063   }
   46064 
   46065   /* A frame is only valid if a checksum of the WAL header,
   46066   ** all prior frams, the first 16 bytes of this frame-header,
   46067   ** and the frame-data matches the checksum in the last 8
   46068   ** bytes of this frame-header.
   46069   */
   46070   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   46071   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   46072   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   46073   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   46074    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   46075   ){
   46076     /* Checksum failed. */
   46077     return 0;
   46078   }
   46079 
   46080   /* If we reach this point, the frame is valid.  Return the page number
   46081   ** and the new database size.
   46082   */
   46083   *piPage = pgno;
   46084   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   46085   return 1;
   46086 }
   46087 
   46088 
   46089 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   46090 /*
   46091 ** Names of locks.  This routine is used to provide debugging output and is not
   46092 ** a part of an ordinary build.
   46093 */
   46094 static const char *walLockName(int lockIdx){
   46095   if( lockIdx==WAL_WRITE_LOCK ){
   46096     return "WRITE-LOCK";
   46097   }else if( lockIdx==WAL_CKPT_LOCK ){
   46098     return "CKPT-LOCK";
   46099   }else if( lockIdx==WAL_RECOVER_LOCK ){
   46100     return "RECOVER-LOCK";
   46101   }else{
   46102     static char zName[15];
   46103     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   46104                      lockIdx-WAL_READ_LOCK(0));
   46105     return zName;
   46106   }
   46107 }
   46108 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   46109 
   46110 
   46111 /*
   46112 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   46113 ** A lock cannot be moved directly between shared and exclusive - it must go
   46114 ** through the unlocked state first.
   46115 **
   46116 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   46117 */
   46118 static int walLockShared(Wal *pWal, int lockIdx){
   46119   int rc;
   46120   if( pWal->exclusiveMode ) return SQLITE_OK;
   46121   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   46122                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   46123   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   46124             walLockName(lockIdx), rc ? "failed" : "ok"));
   46125   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   46126   return rc;
   46127 }
   46128 static void walUnlockShared(Wal *pWal, int lockIdx){
   46129   if( pWal->exclusiveMode ) return;
   46130   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   46131                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   46132   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   46133 }
   46134 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   46135   int rc;
   46136   if( pWal->exclusiveMode ) return SQLITE_OK;
   46137   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   46138                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   46139   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   46140             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   46141   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   46142   return rc;
   46143 }
   46144 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   46145   if( pWal->exclusiveMode ) return;
   46146   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   46147                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   46148   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   46149              walLockName(lockIdx), n));
   46150 }
   46151 
   46152 /*
   46153 ** Compute a hash on a page number.  The resulting hash value must land
   46154 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   46155 ** the hash to the next value in the event of a collision.
   46156 */
   46157 static int walHash(u32 iPage){
   46158   assert( iPage>0 );
   46159   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   46160   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   46161 }
   46162 static int walNextHash(int iPriorHash){
   46163   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   46164 }
   46165 
   46166 /*
   46167 ** Return pointers to the hash table and page number array stored on
   46168 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   46169 ** numbered starting from 0.
   46170 **
   46171 ** Set output variable *paHash to point to the start of the hash table
   46172 ** in the wal-index file. Set *piZero to one less than the frame
   46173 ** number of the first frame indexed by this hash table. If a
   46174 ** slot in the hash table is set to N, it refers to frame number
   46175 ** (*piZero+N) in the log.
   46176 **
   46177 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   46178 ** first frame indexed by the hash table, frame (*piZero+1).
   46179 */
   46180 static int walHashGet(
   46181   Wal *pWal,                      /* WAL handle */
   46182   int iHash,                      /* Find the iHash'th table */
   46183   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   46184   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   46185   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   46186 ){
   46187   int rc;                         /* Return code */
   46188   volatile u32 *aPgno;
   46189 
   46190   rc = walIndexPage(pWal, iHash, &aPgno);
   46191   assert( rc==SQLITE_OK || iHash>0 );
   46192 
   46193   if( rc==SQLITE_OK ){
   46194     u32 iZero;
   46195     volatile ht_slot *aHash;
   46196 
   46197     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   46198     if( iHash==0 ){
   46199       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   46200       iZero = 0;
   46201     }else{
   46202       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   46203     }
   46204 
   46205     *paPgno = &aPgno[-1];
   46206     *paHash = aHash;
   46207     *piZero = iZero;
   46208   }
   46209   return rc;
   46210 }
   46211 
   46212 /*
   46213 ** Return the number of the wal-index page that contains the hash-table
   46214 ** and page-number array that contain entries corresponding to WAL frame
   46215 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   46216 ** are numbered starting from 0.
   46217 */
   46218 static int walFramePage(u32 iFrame){
   46219   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   46220   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   46221        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   46222        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   46223        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   46224        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   46225   );
   46226   return iHash;
   46227 }
   46228 
   46229 /*
   46230 ** Return the page number associated with frame iFrame in this WAL.
   46231 */
   46232 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   46233   int iHash = walFramePage(iFrame);
   46234   if( iHash==0 ){
   46235     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   46236   }
   46237   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   46238 }
   46239 
   46240 /*
   46241 ** Remove entries from the hash table that point to WAL slots greater
   46242 ** than pWal->hdr.mxFrame.
   46243 **
   46244 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   46245 ** to a rollback or savepoint.
   46246 **
   46247 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   46248 ** updated.  Any later hash tables will be automatically cleared when
   46249 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   46250 ** actually needed.
   46251 */
   46252 static void walCleanupHash(Wal *pWal){
   46253   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   46254   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   46255   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   46256   int iLimit = 0;                 /* Zero values greater than this */
   46257   int nByte;                      /* Number of bytes to zero in aPgno[] */
   46258   int i;                          /* Used to iterate through aHash[] */
   46259 
   46260   assert( pWal->writeLock );
   46261   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   46262   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   46263   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   46264 
   46265   if( pWal->hdr.mxFrame==0 ) return;
   46266 
   46267   /* Obtain pointers to the hash-table and page-number array containing
   46268   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   46269   ** that the page said hash-table and array reside on is already mapped.
   46270   */
   46271   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   46272   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   46273   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   46274 
   46275   /* Zero all hash-table entries that correspond to frame numbers greater
   46276   ** than pWal->hdr.mxFrame.
   46277   */
   46278   iLimit = pWal->hdr.mxFrame - iZero;
   46279   assert( iLimit>0 );
   46280   for(i=0; i<HASHTABLE_NSLOT; i++){
   46281     if( aHash[i]>iLimit ){
   46282       aHash[i] = 0;
   46283     }
   46284   }
   46285 
   46286   /* Zero the entries in the aPgno array that correspond to frames with
   46287   ** frame numbers greater than pWal->hdr.mxFrame.
   46288   */
   46289   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   46290   memset((void *)&aPgno[iLimit+1], 0, nByte);
   46291 
   46292 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   46293   /* Verify that the every entry in the mapping region is still reachable
   46294   ** via the hash table even after the cleanup.
   46295   */
   46296   if( iLimit ){
   46297     int i;           /* Loop counter */
   46298     int iKey;        /* Hash key */
   46299     for(i=1; i<=iLimit; i++){
   46300       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   46301         if( aHash[iKey]==i ) break;
   46302       }
   46303       assert( aHash[iKey]==i );
   46304     }
   46305   }
   46306 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   46307 }
   46308 
   46309 
   46310 /*
   46311 ** Set an entry in the wal-index that will map database page number
   46312 ** pPage into WAL frame iFrame.
   46313 */
   46314 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   46315   int rc;                         /* Return code */
   46316   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   46317   volatile u32 *aPgno = 0;        /* Page number array */
   46318   volatile ht_slot *aHash = 0;    /* Hash table */
   46319 
   46320   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   46321 
   46322   /* Assuming the wal-index file was successfully mapped, populate the
   46323   ** page number array and hash table entry.
   46324   */
   46325   if( rc==SQLITE_OK ){
   46326     int iKey;                     /* Hash table key */
   46327     int idx;                      /* Value to write to hash-table slot */
   46328     int nCollide;                 /* Number of hash collisions */
   46329 
   46330     idx = iFrame - iZero;
   46331     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   46332 
   46333     /* If this is the first entry to be added to this hash-table, zero the
   46334     ** entire hash table and aPgno[] array before proceding.
   46335     */
   46336     if( idx==1 ){
   46337       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   46338       memset((void*)&aPgno[1], 0, nByte);
   46339     }
   46340 
   46341     /* If the entry in aPgno[] is already set, then the previous writer
   46342     ** must have exited unexpectedly in the middle of a transaction (after
   46343     ** writing one or more dirty pages to the WAL to free up memory).
   46344     ** Remove the remnants of that writers uncommitted transaction from
   46345     ** the hash-table before writing any new entries.
   46346     */
   46347     if( aPgno[idx] ){
   46348       walCleanupHash(pWal);
   46349       assert( !aPgno[idx] );
   46350     }
   46351 
   46352     /* Write the aPgno[] array entry and the hash-table slot. */
   46353     nCollide = idx;
   46354     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   46355       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   46356     }
   46357     aPgno[idx] = iPage;
   46358     aHash[iKey] = (ht_slot)idx;
   46359 
   46360 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   46361     /* Verify that the number of entries in the hash table exactly equals
   46362     ** the number of entries in the mapping region.
   46363     */
   46364     {
   46365       int i;           /* Loop counter */
   46366       int nEntry = 0;  /* Number of entries in the hash table */
   46367       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   46368       assert( nEntry==idx );
   46369     }
   46370 
   46371     /* Verify that the every entry in the mapping region is reachable
   46372     ** via the hash table.  This turns out to be a really, really expensive
   46373     ** thing to check, so only do this occasionally - not on every
   46374     ** iteration.
   46375     */
   46376     if( (idx&0x3ff)==0 ){
   46377       int i;           /* Loop counter */
   46378       for(i=1; i<=idx; i++){
   46379         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   46380           if( aHash[iKey]==i ) break;
   46381         }
   46382         assert( aHash[iKey]==i );
   46383       }
   46384     }
   46385 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   46386   }
   46387 
   46388 
   46389   return rc;
   46390 }
   46391 
   46392 
   46393 /*
   46394 ** Recover the wal-index by reading the write-ahead log file.
   46395 **
   46396 ** This routine first tries to establish an exclusive lock on the
   46397 ** wal-index to prevent other threads/processes from doing anything
   46398 ** with the WAL or wal-index while recovery is running.  The
   46399 ** WAL_RECOVER_LOCK is also held so that other threads will know
   46400 ** that this thread is running recovery.  If unable to establish
   46401 ** the necessary locks, this routine returns SQLITE_BUSY.
   46402 */
   46403 static int walIndexRecover(Wal *pWal){
   46404   int rc;                         /* Return Code */
   46405   i64 nSize;                      /* Size of log file */
   46406   u32 aFrameCksum[2] = {0, 0};
   46407   int iLock;                      /* Lock offset to lock for checkpoint */
   46408   int nLock;                      /* Number of locks to hold */
   46409 
   46410   /* Obtain an exclusive lock on all byte in the locking range not already
   46411   ** locked by the caller. The caller is guaranteed to have locked the
   46412   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   46413   ** If successful, the same bytes that are locked here are unlocked before
   46414   ** this function returns.
   46415   */
   46416   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   46417   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   46418   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   46419   assert( pWal->writeLock );
   46420   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   46421   nLock = SQLITE_SHM_NLOCK - iLock;
   46422   rc = walLockExclusive(pWal, iLock, nLock);
   46423   if( rc ){
   46424     return rc;
   46425   }
   46426   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   46427 
   46428   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   46429 
   46430   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   46431   if( rc!=SQLITE_OK ){
   46432     goto recovery_error;
   46433   }
   46434 
   46435   if( nSize>WAL_HDRSIZE ){
   46436     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   46437     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   46438     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   46439     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   46440     int iFrame;                   /* Index of last frame read */
   46441     i64 iOffset;                  /* Next offset to read from log file */
   46442     int szPage;                   /* Page size according to the log */
   46443     u32 magic;                    /* Magic value read from WAL header */
   46444     u32 version;                  /* Magic value read from WAL header */
   46445     int isValid;                  /* True if this frame is valid */
   46446 
   46447     /* Read in the WAL header. */
   46448     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   46449     if( rc!=SQLITE_OK ){
   46450       goto recovery_error;
   46451     }
   46452 
   46453     /* If the database page size is not a power of two, or is greater than
   46454     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   46455     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   46456     ** WAL file.
   46457     */
   46458     magic = sqlite3Get4byte(&aBuf[0]);
   46459     szPage = sqlite3Get4byte(&aBuf[8]);
   46460     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   46461      || szPage&(szPage-1)
   46462      || szPage>SQLITE_MAX_PAGE_SIZE
   46463      || szPage<512
   46464     ){
   46465       goto finished;
   46466     }
   46467     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   46468     pWal->szPage = szPage;
   46469     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   46470     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   46471 
   46472     /* Verify that the WAL header checksum is correct */
   46473     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   46474         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   46475     );
   46476     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   46477      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   46478     ){
   46479       goto finished;
   46480     }
   46481 
   46482     /* Verify that the version number on the WAL format is one that
   46483     ** are able to understand */
   46484     version = sqlite3Get4byte(&aBuf[4]);
   46485     if( version!=WAL_MAX_VERSION ){
   46486       rc = SQLITE_CANTOPEN_BKPT;
   46487       goto finished;
   46488     }
   46489 
   46490     /* Malloc a buffer to read frames into. */
   46491     szFrame = szPage + WAL_FRAME_HDRSIZE;
   46492     aFrame = (u8 *)sqlite3_malloc(szFrame);
   46493     if( !aFrame ){
   46494       rc = SQLITE_NOMEM;
   46495       goto recovery_error;
   46496     }
   46497     aData = &aFrame[WAL_FRAME_HDRSIZE];
   46498 
   46499     /* Read all frames from the log file. */
   46500     iFrame = 0;
   46501     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   46502       u32 pgno;                   /* Database page number for frame */
   46503       u32 nTruncate;              /* dbsize field from frame header */
   46504 
   46505       /* Read and decode the next log frame. */
   46506       iFrame++;
   46507       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   46508       if( rc!=SQLITE_OK ) break;
   46509       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   46510       if( !isValid ) break;
   46511       rc = walIndexAppend(pWal, iFrame, pgno);
   46512       if( rc!=SQLITE_OK ) break;
   46513 
   46514       /* If nTruncate is non-zero, this is a commit record. */
   46515       if( nTruncate ){
   46516         pWal->hdr.mxFrame = iFrame;
   46517         pWal->hdr.nPage = nTruncate;
   46518         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   46519         testcase( szPage<=32768 );
   46520         testcase( szPage>=65536 );
   46521         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   46522         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   46523       }
   46524     }
   46525 
   46526     sqlite3_free(aFrame);
   46527   }
   46528 
   46529 finished:
   46530   if( rc==SQLITE_OK ){
   46531     volatile WalCkptInfo *pInfo;
   46532     int i;
   46533     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   46534     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   46535     walIndexWriteHdr(pWal);
   46536 
   46537     /* Reset the checkpoint-header. This is safe because this thread is
   46538     ** currently holding locks that exclude all other readers, writers and
   46539     ** checkpointers.
   46540     */
   46541     pInfo = walCkptInfo(pWal);
   46542     pInfo->nBackfill = 0;
   46543     pInfo->aReadMark[0] = 0;
   46544     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   46545 
   46546     /* If more than one frame was recovered from the log file, report an
   46547     ** event via sqlite3_log(). This is to help with identifying performance
   46548     ** problems caused by applications routinely shutting down without
   46549     ** checkpointing the log file.
   46550     */
   46551     if( pWal->hdr.nPage ){
   46552       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
   46553           pWal->hdr.nPage, pWal->zWalName
   46554       );
   46555     }
   46556   }
   46557 
   46558 recovery_error:
   46559   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   46560   walUnlockExclusive(pWal, iLock, nLock);
   46561   return rc;
   46562 }
   46563 
   46564 /*
   46565 ** Close an open wal-index.
   46566 */
   46567 static void walIndexClose(Wal *pWal, int isDelete){
   46568   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   46569     int i;
   46570     for(i=0; i<pWal->nWiData; i++){
   46571       sqlite3_free((void *)pWal->apWiData[i]);
   46572       pWal->apWiData[i] = 0;
   46573     }
   46574   }else{
   46575     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   46576   }
   46577 }
   46578 
   46579 /*
   46580 ** Open a connection to the WAL file zWalName. The database file must
   46581 ** already be opened on connection pDbFd. The buffer that zWalName points
   46582 ** to must remain valid for the lifetime of the returned Wal* handle.
   46583 **
   46584 ** A SHARED lock should be held on the database file when this function
   46585 ** is called. The purpose of this SHARED lock is to prevent any other
   46586 ** client from unlinking the WAL or wal-index file. If another process
   46587 ** were to do this just after this client opened one of these files, the
   46588 ** system would be badly broken.
   46589 **
   46590 ** If the log file is successfully opened, SQLITE_OK is returned and
   46591 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   46592 ** an SQLite error code is returned and *ppWal is left unmodified.
   46593 */
   46594 SQLITE_PRIVATE int sqlite3WalOpen(
   46595   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   46596   sqlite3_file *pDbFd,            /* The open database file */
   46597   const char *zWalName,           /* Name of the WAL file */
   46598   int bNoShm,                     /* True to run in heap-memory mode */
   46599   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
   46600   Wal **ppWal                     /* OUT: Allocated Wal handle */
   46601 ){
   46602   int rc;                         /* Return Code */
   46603   Wal *pRet;                      /* Object to allocate and return */
   46604   int flags;                      /* Flags passed to OsOpen() */
   46605 
   46606   assert( zWalName && zWalName[0] );
   46607   assert( pDbFd );
   46608 
   46609   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   46610   ** this source file.  Verify that the #defines of the locking byte offsets
   46611   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   46612   */
   46613 #ifdef WIN_SHM_BASE
   46614   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   46615 #endif
   46616 #ifdef UNIX_SHM_BASE
   46617   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   46618 #endif
   46619 
   46620 
   46621   /* Allocate an instance of struct Wal to return. */
   46622   *ppWal = 0;
   46623   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   46624   if( !pRet ){
   46625     return SQLITE_NOMEM;
   46626   }
   46627 
   46628   pRet->pVfs = pVfs;
   46629   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   46630   pRet->pDbFd = pDbFd;
   46631   pRet->readLock = -1;
   46632   pRet->mxWalSize = mxWalSize;
   46633   pRet->zWalName = zWalName;
   46634   pRet->syncHeader = 1;
   46635   pRet->padToSectorBoundary = 1;
   46636   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   46637 
   46638   /* Open file handle on the write-ahead log file. */
   46639   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   46640   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   46641   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   46642     pRet->readOnly = WAL_RDONLY;
   46643   }
   46644 
   46645   if( rc!=SQLITE_OK ){
   46646     walIndexClose(pRet, 0);
   46647     sqlite3OsClose(pRet->pWalFd);
   46648     sqlite3_free(pRet);
   46649   }else{
   46650     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
   46651     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
   46652     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
   46653       pRet->padToSectorBoundary = 0;
   46654     }
   46655     *ppWal = pRet;
   46656     WALTRACE(("WAL%d: opened\n", pRet));
   46657   }
   46658   return rc;
   46659 }
   46660 
   46661 /*
   46662 ** Change the size to which the WAL file is trucated on each reset.
   46663 */
   46664 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
   46665   if( pWal ) pWal->mxWalSize = iLimit;
   46666 }
   46667 
   46668 /*
   46669 ** Find the smallest page number out of all pages held in the WAL that
   46670 ** has not been returned by any prior invocation of this method on the
   46671 ** same WalIterator object.   Write into *piFrame the frame index where
   46672 ** that page was last written into the WAL.  Write into *piPage the page
   46673 ** number.
   46674 **
   46675 ** Return 0 on success.  If there are no pages in the WAL with a page
   46676 ** number larger than *piPage, then return 1.
   46677 */
   46678 static int walIteratorNext(
   46679   WalIterator *p,               /* Iterator */
   46680   u32 *piPage,                  /* OUT: The page number of the next page */
   46681   u32 *piFrame                  /* OUT: Wal frame index of next page */
   46682 ){
   46683   u32 iMin;                     /* Result pgno must be greater than iMin */
   46684   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   46685   int i;                        /* For looping through segments */
   46686 
   46687   iMin = p->iPrior;
   46688   assert( iMin<0xffffffff );
   46689   for(i=p->nSegment-1; i>=0; i--){
   46690     struct WalSegment *pSegment = &p->aSegment[i];
   46691     while( pSegment->iNext<pSegment->nEntry ){
   46692       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   46693       if( iPg>iMin ){
   46694         if( iPg<iRet ){
   46695           iRet = iPg;
   46696           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   46697         }
   46698         break;
   46699       }
   46700       pSegment->iNext++;
   46701     }
   46702   }
   46703 
   46704   *piPage = p->iPrior = iRet;
   46705   return (iRet==0xFFFFFFFF);
   46706 }
   46707 
   46708 /*
   46709 ** This function merges two sorted lists into a single sorted list.
   46710 **
   46711 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
   46712 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
   46713 ** is guaranteed for all J<K:
   46714 **
   46715 **        aContent[aLeft[J]] < aContent[aLeft[K]]
   46716 **        aContent[aRight[J]] < aContent[aRight[K]]
   46717 **
   46718 ** This routine overwrites aRight[] with a new (probably longer) sequence
   46719 ** of indices such that the aRight[] contains every index that appears in
   46720 ** either aLeft[] or the old aRight[] and such that the second condition
   46721 ** above is still met.
   46722 **
   46723 ** The aContent[aLeft[X]] values will be unique for all X.  And the
   46724 ** aContent[aRight[X]] values will be unique too.  But there might be
   46725 ** one or more combinations of X and Y such that
   46726 **
   46727 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
   46728 **
   46729 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
   46730 */
   46731 static void walMerge(
   46732   const u32 *aContent,            /* Pages in wal - keys for the sort */
   46733   ht_slot *aLeft,                 /* IN: Left hand input list */
   46734   int nLeft,                      /* IN: Elements in array *paLeft */
   46735   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   46736   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   46737   ht_slot *aTmp                   /* Temporary buffer */
   46738 ){
   46739   int iLeft = 0;                  /* Current index in aLeft */
   46740   int iRight = 0;                 /* Current index in aRight */
   46741   int iOut = 0;                   /* Current index in output buffer */
   46742   int nRight = *pnRight;
   46743   ht_slot *aRight = *paRight;
   46744 
   46745   assert( nLeft>0 && nRight>0 );
   46746   while( iRight<nRight || iLeft<nLeft ){
   46747     ht_slot logpage;
   46748     Pgno dbpage;
   46749 
   46750     if( (iLeft<nLeft)
   46751      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   46752     ){
   46753       logpage = aLeft[iLeft++];
   46754     }else{
   46755       logpage = aRight[iRight++];
   46756     }
   46757     dbpage = aContent[logpage];
   46758 
   46759     aTmp[iOut++] = logpage;
   46760     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   46761 
   46762     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   46763     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   46764   }
   46765 
   46766   *paRight = aLeft;
   46767   *pnRight = iOut;
   46768   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   46769 }
   46770 
   46771 /*
   46772 ** Sort the elements in list aList using aContent[] as the sort key.
   46773 ** Remove elements with duplicate keys, preferring to keep the
   46774 ** larger aList[] values.
   46775 **
   46776 ** The aList[] entries are indices into aContent[].  The values in
   46777 ** aList[] are to be sorted so that for all J<K:
   46778 **
   46779 **      aContent[aList[J]] < aContent[aList[K]]
   46780 **
   46781 ** For any X and Y such that
   46782 **
   46783 **      aContent[aList[X]] == aContent[aList[Y]]
   46784 **
   46785 ** Keep the larger of the two values aList[X] and aList[Y] and discard
   46786 ** the smaller.
   46787 */
   46788 static void walMergesort(
   46789   const u32 *aContent,            /* Pages in wal */
   46790   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   46791   ht_slot *aList,                 /* IN/OUT: List to sort */
   46792   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   46793 ){
   46794   struct Sublist {
   46795     int nList;                    /* Number of elements in aList */
   46796     ht_slot *aList;               /* Pointer to sub-list content */
   46797   };
   46798 
   46799   const int nList = *pnList;      /* Size of input list */
   46800   int nMerge = 0;                 /* Number of elements in list aMerge */
   46801   ht_slot *aMerge = 0;            /* List to be merged */
   46802   int iList;                      /* Index into input list */
   46803   int iSub = 0;                   /* Index into aSub array */
   46804   struct Sublist aSub[13];        /* Array of sub-lists */
   46805 
   46806   memset(aSub, 0, sizeof(aSub));
   46807   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   46808   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   46809 
   46810   for(iList=0; iList<nList; iList++){
   46811     nMerge = 1;
   46812     aMerge = &aList[iList];
   46813     for(iSub=0; iList & (1<<iSub); iSub++){
   46814       struct Sublist *p = &aSub[iSub];
   46815       assert( p->aList && p->nList<=(1<<iSub) );
   46816       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   46817       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   46818     }
   46819     aSub[iSub].aList = aMerge;
   46820     aSub[iSub].nList = nMerge;
   46821   }
   46822 
   46823   for(iSub++; iSub<ArraySize(aSub); iSub++){
   46824     if( nList & (1<<iSub) ){
   46825       struct Sublist *p = &aSub[iSub];
   46826       assert( p->nList<=(1<<iSub) );
   46827       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   46828       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   46829     }
   46830   }
   46831   assert( aMerge==aList );
   46832   *pnList = nMerge;
   46833 
   46834 #ifdef SQLITE_DEBUG
   46835   {
   46836     int i;
   46837     for(i=1; i<*pnList; i++){
   46838       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   46839     }
   46840   }
   46841 #endif
   46842 }
   46843 
   46844 /*
   46845 ** Free an iterator allocated by walIteratorInit().
   46846 */
   46847 static void walIteratorFree(WalIterator *p){
   46848   sqlite3ScratchFree(p);
   46849 }
   46850 
   46851 /*
   46852 ** Construct a WalInterator object that can be used to loop over all
   46853 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   46854 ** lock.
   46855 **
   46856 ** On success, make *pp point to the newly allocated WalInterator object
   46857 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   46858 ** returns an error, the value of *pp is undefined.
   46859 **
   46860 ** The calling routine should invoke walIteratorFree() to destroy the
   46861 ** WalIterator object when it has finished with it.
   46862 */
   46863 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   46864   WalIterator *p;                 /* Return value */
   46865   int nSegment;                   /* Number of segments to merge */
   46866   u32 iLast;                      /* Last frame in log */
   46867   int nByte;                      /* Number of bytes to allocate */
   46868   int i;                          /* Iterator variable */
   46869   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   46870   int rc = SQLITE_OK;             /* Return Code */
   46871 
   46872   /* This routine only runs while holding the checkpoint lock. And
   46873   ** it only runs if there is actually content in the log (mxFrame>0).
   46874   */
   46875   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   46876   iLast = pWal->hdr.mxFrame;
   46877 
   46878   /* Allocate space for the WalIterator object. */
   46879   nSegment = walFramePage(iLast) + 1;
   46880   nByte = sizeof(WalIterator)
   46881         + (nSegment-1)*sizeof(struct WalSegment)
   46882         + iLast*sizeof(ht_slot);
   46883   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
   46884   if( !p ){
   46885     return SQLITE_NOMEM;
   46886   }
   46887   memset(p, 0, nByte);
   46888   p->nSegment = nSegment;
   46889 
   46890   /* Allocate temporary space used by the merge-sort routine. This block
   46891   ** of memory will be freed before this function returns.
   46892   */
   46893   aTmp = (ht_slot *)sqlite3ScratchMalloc(
   46894       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   46895   );
   46896   if( !aTmp ){
   46897     rc = SQLITE_NOMEM;
   46898   }
   46899 
   46900   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   46901     volatile ht_slot *aHash;
   46902     u32 iZero;
   46903     volatile u32 *aPgno;
   46904 
   46905     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   46906     if( rc==SQLITE_OK ){
   46907       int j;                      /* Counter variable */
   46908       int nEntry;                 /* Number of entries in this segment */
   46909       ht_slot *aIndex;            /* Sorted index for this segment */
   46910 
   46911       aPgno++;
   46912       if( (i+1)==nSegment ){
   46913         nEntry = (int)(iLast - iZero);
   46914       }else{
   46915         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   46916       }
   46917       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   46918       iZero++;
   46919 
   46920       for(j=0; j<nEntry; j++){
   46921         aIndex[j] = (ht_slot)j;
   46922       }
   46923       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   46924       p->aSegment[i].iZero = iZero;
   46925       p->aSegment[i].nEntry = nEntry;
   46926       p->aSegment[i].aIndex = aIndex;
   46927       p->aSegment[i].aPgno = (u32 *)aPgno;
   46928     }
   46929   }
   46930   sqlite3ScratchFree(aTmp);
   46931 
   46932   if( rc!=SQLITE_OK ){
   46933     walIteratorFree(p);
   46934   }
   46935   *pp = p;
   46936   return rc;
   46937 }
   46938 
   46939 /*
   46940 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
   46941 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
   46942 ** busy-handler function. Invoke it and retry the lock until either the
   46943 ** lock is successfully obtained or the busy-handler returns 0.
   46944 */
   46945 static int walBusyLock(
   46946   Wal *pWal,                      /* WAL connection */
   46947   int (*xBusy)(void*),            /* Function to call when busy */
   46948   void *pBusyArg,                 /* Context argument for xBusyHandler */
   46949   int lockIdx,                    /* Offset of first byte to lock */
   46950   int n                           /* Number of bytes to lock */
   46951 ){
   46952   int rc;
   46953   do {
   46954     rc = walLockExclusive(pWal, lockIdx, n);
   46955   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
   46956   return rc;
   46957 }
   46958 
   46959 /*
   46960 ** The cache of the wal-index header must be valid to call this function.
   46961 ** Return the page-size in bytes used by the database.
   46962 */
   46963 static int walPagesize(Wal *pWal){
   46964   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   46965 }
   46966 
   46967 /*
   46968 ** Copy as much content as we can from the WAL back into the database file
   46969 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   46970 **
   46971 ** The amount of information copies from WAL to database might be limited
   46972 ** by active readers.  This routine will never overwrite a database page
   46973 ** that a concurrent reader might be using.
   46974 **
   46975 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   46976 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   46977 ** checkpoints are always run by a background thread or background
   46978 ** process, foreground threads will never block on a lengthy fsync call.
   46979 **
   46980 ** Fsync is called on the WAL before writing content out of the WAL and
   46981 ** into the database.  This ensures that if the new content is persistent
   46982 ** in the WAL and can be recovered following a power-loss or hard reset.
   46983 **
   46984 ** Fsync is also called on the database file if (and only if) the entire
   46985 ** WAL content is copied into the database file.  This second fsync makes
   46986 ** it safe to delete the WAL since the new content will persist in the
   46987 ** database file.
   46988 **
   46989 ** This routine uses and updates the nBackfill field of the wal-index header.
   46990 ** This is the only routine tha will increase the value of nBackfill.
   46991 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   46992 ** its value.)
   46993 **
   46994 ** The caller must be holding sufficient locks to ensure that no other
   46995 ** checkpoint is running (in any other thread or process) at the same
   46996 ** time.
   46997 */
   46998 static int walCheckpoint(
   46999   Wal *pWal,                      /* Wal connection */
   47000   int eMode,                      /* One of PASSIVE, FULL or RESTART */
   47001   int (*xBusyCall)(void*),        /* Function to call when busy */
   47002   void *pBusyArg,                 /* Context argument for xBusyHandler */
   47003   int sync_flags,                 /* Flags for OsSync() (or 0) */
   47004   u8 *zBuf                        /* Temporary buffer to use */
   47005 ){
   47006   int rc;                         /* Return code */
   47007   int szPage;                     /* Database page-size */
   47008   WalIterator *pIter = 0;         /* Wal iterator context */
   47009   u32 iDbpage = 0;                /* Next database page to write */
   47010   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   47011   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   47012   u32 mxPage;                     /* Max database page to write */
   47013   int i;                          /* Loop counter */
   47014   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   47015   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
   47016 
   47017   szPage = walPagesize(pWal);
   47018   testcase( szPage<=32768 );
   47019   testcase( szPage>=65536 );
   47020   pInfo = walCkptInfo(pWal);
   47021   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
   47022 
   47023   /* Allocate the iterator */
   47024   rc = walIteratorInit(pWal, &pIter);
   47025   if( rc!=SQLITE_OK ){
   47026     return rc;
   47027   }
   47028   assert( pIter );
   47029 
   47030   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
   47031 
   47032   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   47033   ** safe to write into the database.  Frames beyond mxSafeFrame might
   47034   ** overwrite database pages that are in use by active readers and thus
   47035   ** cannot be backfilled from the WAL.
   47036   */
   47037   mxSafeFrame = pWal->hdr.mxFrame;
   47038   mxPage = pWal->hdr.nPage;
   47039   for(i=1; i<WAL_NREADER; i++){
   47040     u32 y = pInfo->aReadMark[i];
   47041     if( mxSafeFrame>y ){
   47042       assert( y<=pWal->hdr.mxFrame );
   47043       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
   47044       if( rc==SQLITE_OK ){
   47045         pInfo->aReadMark[i] = READMARK_NOT_USED;
   47046         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47047       }else if( rc==SQLITE_BUSY ){
   47048         mxSafeFrame = y;
   47049         xBusy = 0;
   47050       }else{
   47051         goto walcheckpoint_out;
   47052       }
   47053     }
   47054   }
   47055 
   47056   if( pInfo->nBackfill<mxSafeFrame
   47057    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
   47058   ){
   47059     i64 nSize;                    /* Current size of database file */
   47060     u32 nBackfill = pInfo->nBackfill;
   47061 
   47062     /* Sync the WAL to disk */
   47063     if( sync_flags ){
   47064       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   47065     }
   47066 
   47067     /* If the database file may grow as a result of this checkpoint, hint
   47068     ** about the eventual size of the db file to the VFS layer.
   47069     */
   47070     if( rc==SQLITE_OK ){
   47071       i64 nReq = ((i64)mxPage * szPage);
   47072       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   47073       if( rc==SQLITE_OK && nSize<nReq ){
   47074         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   47075       }
   47076     }
   47077 
   47078     /* Iterate through the contents of the WAL, copying data to the db file. */
   47079     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   47080       i64 iOffset;
   47081       assert( walFramePgno(pWal, iFrame)==iDbpage );
   47082       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
   47083       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   47084       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   47085       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   47086       if( rc!=SQLITE_OK ) break;
   47087       iOffset = (iDbpage-1)*(i64)szPage;
   47088       testcase( IS_BIG_INT(iOffset) );
   47089       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   47090       if( rc!=SQLITE_OK ) break;
   47091     }
   47092 
   47093     /* If work was actually accomplished... */
   47094     if( rc==SQLITE_OK ){
   47095       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   47096         i64 szDb = pWal->hdr.nPage*(i64)szPage;
   47097         testcase( IS_BIG_INT(szDb) );
   47098         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   47099         if( rc==SQLITE_OK && sync_flags ){
   47100           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
   47101         }
   47102       }
   47103       if( rc==SQLITE_OK ){
   47104         pInfo->nBackfill = mxSafeFrame;
   47105       }
   47106     }
   47107 
   47108     /* Release the reader lock held while backfilling */
   47109     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   47110   }
   47111 
   47112   if( rc==SQLITE_BUSY ){
   47113     /* Reset the return code so as not to report a checkpoint failure
   47114     ** just because there are active readers.  */
   47115     rc = SQLITE_OK;
   47116   }
   47117 
   47118   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
   47119   ** file has been copied into the database file, then block until all
   47120   ** readers have finished using the wal file. This ensures that the next
   47121   ** process to write to the database restarts the wal file.
   47122   */
   47123   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   47124     assert( pWal->writeLock );
   47125     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
   47126       rc = SQLITE_BUSY;
   47127     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
   47128       assert( mxSafeFrame==pWal->hdr.mxFrame );
   47129       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
   47130       if( rc==SQLITE_OK ){
   47131         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47132       }
   47133     }
   47134   }
   47135 
   47136  walcheckpoint_out:
   47137   walIteratorFree(pIter);
   47138   return rc;
   47139 }
   47140 
   47141 /*
   47142 ** If the WAL file is currently larger than nMax bytes in size, truncate
   47143 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
   47144 */
   47145 static void walLimitSize(Wal *pWal, i64 nMax){
   47146   i64 sz;
   47147   int rx;
   47148   sqlite3BeginBenignMalloc();
   47149   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
   47150   if( rx==SQLITE_OK && (sz > nMax ) ){
   47151     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
   47152   }
   47153   sqlite3EndBenignMalloc();
   47154   if( rx ){
   47155     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
   47156   }
   47157 }
   47158 
   47159 /*
   47160 ** Close a connection to a log file.
   47161 */
   47162 SQLITE_PRIVATE int sqlite3WalClose(
   47163   Wal *pWal,                      /* Wal to close */
   47164   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   47165   int nBuf,
   47166   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   47167 ){
   47168   int rc = SQLITE_OK;
   47169   if( pWal ){
   47170     int isDelete = 0;             /* True to unlink wal and wal-index files */
   47171 
   47172     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   47173     ** ordinary, rollback-mode locking methods, this guarantees that the
   47174     ** connection associated with this log file is the only connection to
   47175     ** the database. In this case checkpoint the database and unlink both
   47176     ** the wal and wal-index files.
   47177     **
   47178     ** The EXCLUSIVE lock is not released before returning.
   47179     */
   47180     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
   47181     if( rc==SQLITE_OK ){
   47182       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   47183         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   47184       }
   47185       rc = sqlite3WalCheckpoint(
   47186           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
   47187       );
   47188       if( rc==SQLITE_OK ){
   47189         int bPersist = -1;
   47190         sqlite3OsFileControlHint(
   47191             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
   47192         );
   47193         if( bPersist!=1 ){
   47194           /* Try to delete the WAL file if the checkpoint completed and
   47195           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
   47196           ** mode (!bPersist) */
   47197           isDelete = 1;
   47198         }else if( pWal->mxWalSize>=0 ){
   47199           /* Try to truncate the WAL file to zero bytes if the checkpoint
   47200           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
   47201           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
   47202           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
   47203           ** to zero bytes as truncating to the journal_size_limit might
   47204           ** leave a corrupt WAL file on disk. */
   47205           walLimitSize(pWal, 0);
   47206         }
   47207       }
   47208     }
   47209 
   47210     walIndexClose(pWal, isDelete);
   47211     sqlite3OsClose(pWal->pWalFd);
   47212     if( isDelete ){
   47213       sqlite3BeginBenignMalloc();
   47214       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   47215       sqlite3EndBenignMalloc();
   47216     }
   47217     WALTRACE(("WAL%p: closed\n", pWal));
   47218     sqlite3_free((void *)pWal->apWiData);
   47219     sqlite3_free(pWal);
   47220   }
   47221   return rc;
   47222 }
   47223 
   47224 /*
   47225 ** Try to read the wal-index header.  Return 0 on success and 1 if
   47226 ** there is a problem.
   47227 **
   47228 ** The wal-index is in shared memory.  Another thread or process might
   47229 ** be writing the header at the same time this procedure is trying to
   47230 ** read it, which might result in inconsistency.  A dirty read is detected
   47231 ** by verifying that both copies of the header are the same and also by
   47232 ** a checksum on the header.
   47233 **
   47234 ** If and only if the read is consistent and the header is different from
   47235 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   47236 ** and *pChanged is set to 1.
   47237 **
   47238 ** If the checksum cannot be verified return non-zero. If the header
   47239 ** is read successfully and the checksum verified, return zero.
   47240 */
   47241 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   47242   u32 aCksum[2];                  /* Checksum on the header content */
   47243   WalIndexHdr h1, h2;             /* Two copies of the header content */
   47244   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   47245 
   47246   /* The first page of the wal-index must be mapped at this point. */
   47247   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   47248 
   47249   /* Read the header. This might happen concurrently with a write to the
   47250   ** same area of shared memory on a different CPU in a SMP,
   47251   ** meaning it is possible that an inconsistent snapshot is read
   47252   ** from the file. If this happens, return non-zero.
   47253   **
   47254   ** There are two copies of the header at the beginning of the wal-index.
   47255   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   47256   ** Memory barriers are used to prevent the compiler or the hardware from
   47257   ** reordering the reads and writes.
   47258   */
   47259   aHdr = walIndexHdr(pWal);
   47260   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   47261   walShmBarrier(pWal);
   47262   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   47263 
   47264   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   47265     return 1;   /* Dirty read */
   47266   }
   47267   if( h1.isInit==0 ){
   47268     return 1;   /* Malformed header - probably all zeros */
   47269   }
   47270   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   47271   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   47272     return 1;   /* Checksum does not match */
   47273   }
   47274 
   47275   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   47276     *pChanged = 1;
   47277     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   47278     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   47279     testcase( pWal->szPage<=32768 );
   47280     testcase( pWal->szPage>=65536 );
   47281   }
   47282 
   47283   /* The header was successfully read. Return zero. */
   47284   return 0;
   47285 }
   47286 
   47287 /*
   47288 ** Read the wal-index header from the wal-index and into pWal->hdr.
   47289 ** If the wal-header appears to be corrupt, try to reconstruct the
   47290 ** wal-index from the WAL before returning.
   47291 **
   47292 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   47293 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
   47294 ** to 0.
   47295 **
   47296 ** If the wal-index header is successfully read, return SQLITE_OK.
   47297 ** Otherwise an SQLite error code.
   47298 */
   47299 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   47300   int rc;                         /* Return code */
   47301   int badHdr;                     /* True if a header read failed */
   47302   volatile u32 *page0;            /* Chunk of wal-index containing header */
   47303 
   47304   /* Ensure that page 0 of the wal-index (the page that contains the
   47305   ** wal-index header) is mapped. Return early if an error occurs here.
   47306   */
   47307   assert( pChanged );
   47308   rc = walIndexPage(pWal, 0, &page0);
   47309   if( rc!=SQLITE_OK ){
   47310     return rc;
   47311   };
   47312   assert( page0 || pWal->writeLock==0 );
   47313 
   47314   /* If the first page of the wal-index has been mapped, try to read the
   47315   ** wal-index header immediately, without holding any lock. This usually
   47316   ** works, but may fail if the wal-index header is corrupt or currently
   47317   ** being modified by another thread or process.
   47318   */
   47319   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   47320 
   47321   /* If the first attempt failed, it might have been due to a race
   47322   ** with a writer.  So get a WRITE lock and try again.
   47323   */
   47324   assert( badHdr==0 || pWal->writeLock==0 );
   47325   if( badHdr ){
   47326     if( pWal->readOnly & WAL_SHM_RDONLY ){
   47327       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
   47328         walUnlockShared(pWal, WAL_WRITE_LOCK);
   47329         rc = SQLITE_READONLY_RECOVERY;
   47330       }
   47331     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   47332       pWal->writeLock = 1;
   47333       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   47334         badHdr = walIndexTryHdr(pWal, pChanged);
   47335         if( badHdr ){
   47336           /* If the wal-index header is still malformed even while holding
   47337           ** a WRITE lock, it can only mean that the header is corrupted and
   47338           ** needs to be reconstructed.  So run recovery to do exactly that.
   47339           */
   47340           rc = walIndexRecover(pWal);
   47341           *pChanged = 1;
   47342         }
   47343       }
   47344       pWal->writeLock = 0;
   47345       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47346     }
   47347   }
   47348 
   47349   /* If the header is read successfully, check the version number to make
   47350   ** sure the wal-index was not constructed with some future format that
   47351   ** this version of SQLite cannot understand.
   47352   */
   47353   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   47354     rc = SQLITE_CANTOPEN_BKPT;
   47355   }
   47356 
   47357   return rc;
   47358 }
   47359 
   47360 /*
   47361 ** This is the value that walTryBeginRead returns when it needs to
   47362 ** be retried.
   47363 */
   47364 #define WAL_RETRY  (-1)
   47365 
   47366 /*
   47367 ** Attempt to start a read transaction.  This might fail due to a race or
   47368 ** other transient condition.  When that happens, it returns WAL_RETRY to
   47369 ** indicate to the caller that it is safe to retry immediately.
   47370 **
   47371 ** On success return SQLITE_OK.  On a permanent failure (such an
   47372 ** I/O error or an SQLITE_BUSY because another process is running
   47373 ** recovery) return a positive error code.
   47374 **
   47375 ** The useWal parameter is true to force the use of the WAL and disable
   47376 ** the case where the WAL is bypassed because it has been completely
   47377 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   47378 ** to make a copy of the wal-index header into pWal->hdr.  If the
   47379 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   47380 ** to the caller that the local paget cache is obsolete and needs to be
   47381 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   47382 ** be loaded and the pChanged parameter is unused.
   47383 **
   47384 ** The caller must set the cnt parameter to the number of prior calls to
   47385 ** this routine during the current read attempt that returned WAL_RETRY.
   47386 ** This routine will start taking more aggressive measures to clear the
   47387 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   47388 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   47389 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   47390 ** and is not honoring the locking protocol.  There is a vanishingly small
   47391 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   47392 ** bad luck when there is lots of contention for the wal-index, but that
   47393 ** possibility is so small that it can be safely neglected, we believe.
   47394 **
   47395 ** On success, this routine obtains a read lock on
   47396 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   47397 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   47398 ** that means the Wal does not hold any read lock.  The reader must not
   47399 ** access any database page that is modified by a WAL frame up to and
   47400 ** including frame number aReadMark[pWal->readLock].  The reader will
   47401 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   47402 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   47403 ** completely and get all content directly from the database file.
   47404 ** If the useWal parameter is 1 then the WAL will never be ignored and
   47405 ** this routine will always set pWal->readLock>0 on success.
   47406 ** When the read transaction is completed, the caller must release the
   47407 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   47408 **
   47409 ** This routine uses the nBackfill and aReadMark[] fields of the header
   47410 ** to select a particular WAL_READ_LOCK() that strives to let the
   47411 ** checkpoint process do as much work as possible.  This routine might
   47412 ** update values of the aReadMark[] array in the header, but if it does
   47413 ** so it takes care to hold an exclusive lock on the corresponding
   47414 ** WAL_READ_LOCK() while changing values.
   47415 */
   47416 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   47417   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   47418   u32 mxReadMark;                 /* Largest aReadMark[] value */
   47419   int mxI;                        /* Index of largest aReadMark[] value */
   47420   int i;                          /* Loop counter */
   47421   int rc = SQLITE_OK;             /* Return code  */
   47422 
   47423   assert( pWal->readLock<0 );     /* Not currently locked */
   47424 
   47425   /* Take steps to avoid spinning forever if there is a protocol error.
   47426   **
   47427   ** Circumstances that cause a RETRY should only last for the briefest
   47428   ** instances of time.  No I/O or other system calls are done while the
   47429   ** locks are held, so the locks should not be held for very long. But
   47430   ** if we are unlucky, another process that is holding a lock might get
   47431   ** paged out or take a page-fault that is time-consuming to resolve,
   47432   ** during the few nanoseconds that it is holding the lock.  In that case,
   47433   ** it might take longer than normal for the lock to free.
   47434   **
   47435   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   47436   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   47437   ** is more of a scheduler yield than an actual delay.  But on the 10th
   47438   ** an subsequent retries, the delays start becoming longer and longer,
   47439   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
   47440   ** The total delay time before giving up is less than 1 second.
   47441   */
   47442   if( cnt>5 ){
   47443     int nDelay = 1;                      /* Pause time in microseconds */
   47444     if( cnt>100 ){
   47445       VVA_ONLY( pWal->lockError = 1; )
   47446       return SQLITE_PROTOCOL;
   47447     }
   47448     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
   47449     sqlite3OsSleep(pWal->pVfs, nDelay);
   47450   }
   47451 
   47452   if( !useWal ){
   47453     rc = walIndexReadHdr(pWal, pChanged);
   47454     if( rc==SQLITE_BUSY ){
   47455       /* If there is not a recovery running in another thread or process
   47456       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   47457       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   47458       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   47459       ** would be technically correct.  But the race is benign since with
   47460       ** WAL_RETRY this routine will be called again and will probably be
   47461       ** right on the second iteration.
   47462       */
   47463       if( pWal->apWiData[0]==0 ){
   47464         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   47465         ** We assume this is a transient condition, so return WAL_RETRY. The
   47466         ** xShmMap() implementation used by the default unix and win32 VFS
   47467         ** modules may return SQLITE_BUSY due to a race condition in the
   47468         ** code that determines whether or not the shared-memory region
   47469         ** must be zeroed before the requested page is returned.
   47470         */
   47471         rc = WAL_RETRY;
   47472       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   47473         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   47474         rc = WAL_RETRY;
   47475       }else if( rc==SQLITE_BUSY ){
   47476         rc = SQLITE_BUSY_RECOVERY;
   47477       }
   47478     }
   47479     if( rc!=SQLITE_OK ){
   47480       return rc;
   47481     }
   47482   }
   47483 
   47484   pInfo = walCkptInfo(pWal);
   47485   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
   47486     /* The WAL has been completely backfilled (or it is empty).
   47487     ** and can be safely ignored.
   47488     */
   47489     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   47490     walShmBarrier(pWal);
   47491     if( rc==SQLITE_OK ){
   47492       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   47493         /* It is not safe to allow the reader to continue here if frames
   47494         ** may have been appended to the log before READ_LOCK(0) was obtained.
   47495         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   47496         ** which implies that the database file contains a trustworthy
   47497         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
   47498         ** happening, this is usually correct.
   47499         **
   47500         ** However, if frames have been appended to the log (or if the log
   47501         ** is wrapped and written for that matter) before the READ_LOCK(0)
   47502         ** is obtained, that is not necessarily true. A checkpointer may
   47503         ** have started to backfill the appended frames but crashed before
   47504         ** it finished. Leaving a corrupt image in the database file.
   47505         */
   47506         walUnlockShared(pWal, WAL_READ_LOCK(0));
   47507         return WAL_RETRY;
   47508       }
   47509       pWal->readLock = 0;
   47510       return SQLITE_OK;
   47511     }else if( rc!=SQLITE_BUSY ){
   47512       return rc;
   47513     }
   47514   }
   47515 
   47516   /* If we get this far, it means that the reader will want to use
   47517   ** the WAL to get at content from recent commits.  The job now is
   47518   ** to select one of the aReadMark[] entries that is closest to
   47519   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   47520   */
   47521   mxReadMark = 0;
   47522   mxI = 0;
   47523   for(i=1; i<WAL_NREADER; i++){
   47524     u32 thisMark = pInfo->aReadMark[i];
   47525     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
   47526       assert( thisMark!=READMARK_NOT_USED );
   47527       mxReadMark = thisMark;
   47528       mxI = i;
   47529     }
   47530   }
   47531   /* There was once an "if" here. The extra "{" is to preserve indentation. */
   47532   {
   47533     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
   47534      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
   47535     ){
   47536       for(i=1; i<WAL_NREADER; i++){
   47537         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47538         if( rc==SQLITE_OK ){
   47539           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
   47540           mxI = i;
   47541           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   47542           break;
   47543         }else if( rc!=SQLITE_BUSY ){
   47544           return rc;
   47545         }
   47546       }
   47547     }
   47548     if( mxI==0 ){
   47549       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
   47550       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
   47551     }
   47552 
   47553     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   47554     if( rc ){
   47555       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   47556     }
   47557     /* Now that the read-lock has been obtained, check that neither the
   47558     ** value in the aReadMark[] array or the contents of the wal-index
   47559     ** header have changed.
   47560     **
   47561     ** It is necessary to check that the wal-index header did not change
   47562     ** between the time it was read and when the shared-lock was obtained
   47563     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   47564     ** that the log file may have been wrapped by a writer, or that frames
   47565     ** that occur later in the log than pWal->hdr.mxFrame may have been
   47566     ** copied into the database by a checkpointer. If either of these things
   47567     ** happened, then reading the database with the current value of
   47568     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   47569     ** instead.
   47570     **
   47571     ** This does not guarantee that the copy of the wal-index header is up to
   47572     ** date before proceeding. That would not be possible without somehow
   47573     ** blocking writers. It only guarantees that a dangerous checkpoint or
   47574     ** log-wrap (either of which would require an exclusive lock on
   47575     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
   47576     */
   47577     walShmBarrier(pWal);
   47578     if( pInfo->aReadMark[mxI]!=mxReadMark
   47579      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   47580     ){
   47581       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   47582       return WAL_RETRY;
   47583     }else{
   47584       assert( mxReadMark<=pWal->hdr.mxFrame );
   47585       pWal->readLock = (i16)mxI;
   47586     }
   47587   }
   47588   return rc;
   47589 }
   47590 
   47591 /*
   47592 ** Begin a read transaction on the database.
   47593 **
   47594 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   47595 ** it takes a snapshot of the state of the WAL and wal-index for the current
   47596 ** instant in time.  The current thread will continue to use this snapshot.
   47597 ** Other threads might append new content to the WAL and wal-index but
   47598 ** that extra content is ignored by the current thread.
   47599 **
   47600 ** If the database contents have changes since the previous read
   47601 ** transaction, then *pChanged is set to 1 before returning.  The
   47602 ** Pager layer will use this to know that is cache is stale and
   47603 ** needs to be flushed.
   47604 */
   47605 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   47606   int rc;                         /* Return code */
   47607   int cnt = 0;                    /* Number of TryBeginRead attempts */
   47608 
   47609   do{
   47610     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   47611   }while( rc==WAL_RETRY );
   47612   testcase( (rc&0xff)==SQLITE_BUSY );
   47613   testcase( (rc&0xff)==SQLITE_IOERR );
   47614   testcase( rc==SQLITE_PROTOCOL );
   47615   testcase( rc==SQLITE_OK );
   47616   return rc;
   47617 }
   47618 
   47619 /*
   47620 ** Finish with a read transaction.  All this does is release the
   47621 ** read-lock.
   47622 */
   47623 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   47624   sqlite3WalEndWriteTransaction(pWal);
   47625   if( pWal->readLock>=0 ){
   47626     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   47627     pWal->readLock = -1;
   47628   }
   47629 }
   47630 
   47631 /*
   47632 ** Read a page from the WAL, if it is present in the WAL and if the
   47633 ** current read transaction is configured to use the WAL.
   47634 **
   47635 ** The *pInWal is set to 1 if the requested page is in the WAL and
   47636 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
   47637 ** the WAL and needs to be read out of the database.
   47638 */
   47639 SQLITE_PRIVATE int sqlite3WalRead(
   47640   Wal *pWal,                      /* WAL handle */
   47641   Pgno pgno,                      /* Database page number to read data for */
   47642   int *pInWal,                    /* OUT: True if data is read from WAL */
   47643   int nOut,                       /* Size of buffer pOut in bytes */
   47644   u8 *pOut                        /* Buffer to write page data to */
   47645 ){
   47646   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   47647   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   47648   int iHash;                      /* Used to loop through N hash tables */
   47649 
   47650   /* This routine is only be called from within a read transaction. */
   47651   assert( pWal->readLock>=0 || pWal->lockError );
   47652 
   47653   /* If the "last page" field of the wal-index header snapshot is 0, then
   47654   ** no data will be read from the wal under any circumstances. Return early
   47655   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   47656   ** then the WAL is ignored by the reader so return early, as if the
   47657   ** WAL were empty.
   47658   */
   47659   if( iLast==0 || pWal->readLock==0 ){
   47660     *pInWal = 0;
   47661     return SQLITE_OK;
   47662   }
   47663 
   47664   /* Search the hash table or tables for an entry matching page number
   47665   ** pgno. Each iteration of the following for() loop searches one
   47666   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   47667   **
   47668   ** This code might run concurrently to the code in walIndexAppend()
   47669   ** that adds entries to the wal-index (and possibly to this hash
   47670   ** table). This means the value just read from the hash
   47671   ** slot (aHash[iKey]) may have been added before or after the
   47672   ** current read transaction was opened. Values added after the
   47673   ** read transaction was opened may have been written incorrectly -
   47674   ** i.e. these slots may contain garbage data. However, we assume
   47675   ** that any slots written before the current read transaction was
   47676   ** opened remain unmodified.
   47677   **
   47678   ** For the reasons above, the if(...) condition featured in the inner
   47679   ** loop of the following block is more stringent that would be required
   47680   ** if we had exclusive access to the hash-table:
   47681   **
   47682   **   (aPgno[iFrame]==pgno):
   47683   **     This condition filters out normal hash-table collisions.
   47684   **
   47685   **   (iFrame<=iLast):
   47686   **     This condition filters out entries that were added to the hash
   47687   **     table after the current read-transaction had started.
   47688   */
   47689   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
   47690     volatile ht_slot *aHash;      /* Pointer to hash table */
   47691     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   47692     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   47693     int iKey;                     /* Hash slot index */
   47694     int nCollide;                 /* Number of hash collisions remaining */
   47695     int rc;                       /* Error code */
   47696 
   47697     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   47698     if( rc!=SQLITE_OK ){
   47699       return rc;
   47700     }
   47701     nCollide = HASHTABLE_NSLOT;
   47702     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   47703       u32 iFrame = aHash[iKey] + iZero;
   47704       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
   47705         /* assert( iFrame>iRead ); -- not true if there is corruption */
   47706         iRead = iFrame;
   47707       }
   47708       if( (nCollide--)==0 ){
   47709         return SQLITE_CORRUPT_BKPT;
   47710       }
   47711     }
   47712   }
   47713 
   47714 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   47715   /* If expensive assert() statements are available, do a linear search
   47716   ** of the wal-index file content. Make sure the results agree with the
   47717   ** result obtained using the hash indexes above.  */
   47718   {
   47719     u32 iRead2 = 0;
   47720     u32 iTest;
   47721     for(iTest=iLast; iTest>0; iTest--){
   47722       if( walFramePgno(pWal, iTest)==pgno ){
   47723         iRead2 = iTest;
   47724         break;
   47725       }
   47726     }
   47727     assert( iRead==iRead2 );
   47728   }
   47729 #endif
   47730 
   47731   /* If iRead is non-zero, then it is the log frame number that contains the
   47732   ** required page. Read and return data from the log file.
   47733   */
   47734   if( iRead ){
   47735     int sz;
   47736     i64 iOffset;
   47737     sz = pWal->hdr.szPage;
   47738     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
   47739     testcase( sz<=32768 );
   47740     testcase( sz>=65536 );
   47741     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   47742     *pInWal = 1;
   47743     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   47744     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
   47745   }
   47746 
   47747   *pInWal = 0;
   47748   return SQLITE_OK;
   47749 }
   47750 
   47751 
   47752 /*
   47753 ** Return the size of the database in pages (or zero, if unknown).
   47754 */
   47755 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   47756   if( pWal && ALWAYS(pWal->readLock>=0) ){
   47757     return pWal->hdr.nPage;
   47758   }
   47759   return 0;
   47760 }
   47761 
   47762 
   47763 /*
   47764 ** This function starts a write transaction on the WAL.
   47765 **
   47766 ** A read transaction must have already been started by a prior call
   47767 ** to sqlite3WalBeginReadTransaction().
   47768 **
   47769 ** If another thread or process has written into the database since
   47770 ** the read transaction was started, then it is not possible for this
   47771 ** thread to write as doing so would cause a fork.  So this routine
   47772 ** returns SQLITE_BUSY in that case and no write transaction is started.
   47773 **
   47774 ** There can only be a single writer active at a time.
   47775 */
   47776 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   47777   int rc;
   47778 
   47779   /* Cannot start a write transaction without first holding a read
   47780   ** transaction. */
   47781   assert( pWal->readLock>=0 );
   47782 
   47783   if( pWal->readOnly ){
   47784     return SQLITE_READONLY;
   47785   }
   47786 
   47787   /* Only one writer allowed at a time.  Get the write lock.  Return
   47788   ** SQLITE_BUSY if unable.
   47789   */
   47790   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47791   if( rc ){
   47792     return rc;
   47793   }
   47794   pWal->writeLock = 1;
   47795 
   47796   /* If another connection has written to the database file since the
   47797   ** time the read transaction on this connection was started, then
   47798   ** the write is disallowed.
   47799   */
   47800   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   47801     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47802     pWal->writeLock = 0;
   47803     rc = SQLITE_BUSY;
   47804   }
   47805 
   47806   return rc;
   47807 }
   47808 
   47809 /*
   47810 ** End a write transaction.  The commit has already been done.  This
   47811 ** routine merely releases the lock.
   47812 */
   47813 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   47814   if( pWal->writeLock ){
   47815     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   47816     pWal->writeLock = 0;
   47817     pWal->truncateOnCommit = 0;
   47818   }
   47819   return SQLITE_OK;
   47820 }
   47821 
   47822 /*
   47823 ** If any data has been written (but not committed) to the log file, this
   47824 ** function moves the write-pointer back to the start of the transaction.
   47825 **
   47826 ** Additionally, the callback function is invoked for each frame written
   47827 ** to the WAL since the start of the transaction. If the callback returns
   47828 ** other than SQLITE_OK, it is not invoked again and the error code is
   47829 ** returned to the caller.
   47830 **
   47831 ** Otherwise, if the callback function does not return an error, this
   47832 ** function returns SQLITE_OK.
   47833 */
   47834 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   47835   int rc = SQLITE_OK;
   47836   if( ALWAYS(pWal->writeLock) ){
   47837     Pgno iMax = pWal->hdr.mxFrame;
   47838     Pgno iFrame;
   47839 
   47840     /* Restore the clients cache of the wal-index header to the state it
   47841     ** was in before the client began writing to the database.
   47842     */
   47843     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   47844 
   47845     for(iFrame=pWal->hdr.mxFrame+1;
   47846         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   47847         iFrame++
   47848     ){
   47849       /* This call cannot fail. Unless the page for which the page number
   47850       ** is passed as the second argument is (a) in the cache and
   47851       ** (b) has an outstanding reference, then xUndo is either a no-op
   47852       ** (if (a) is false) or simply expels the page from the cache (if (b)
   47853       ** is false).
   47854       **
   47855       ** If the upper layer is doing a rollback, it is guaranteed that there
   47856       ** are no outstanding references to any page other than page 1. And
   47857       ** page 1 is never written to the log until the transaction is
   47858       ** committed. As a result, the call to xUndo may not fail.
   47859       */
   47860       assert( walFramePgno(pWal, iFrame)!=1 );
   47861       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   47862     }
   47863     walCleanupHash(pWal);
   47864   }
   47865   assert( rc==SQLITE_OK );
   47866   return rc;
   47867 }
   47868 
   47869 /*
   47870 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   47871 ** values. This function populates the array with values required to
   47872 ** "rollback" the write position of the WAL handle back to the current
   47873 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   47874 */
   47875 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   47876   assert( pWal->writeLock );
   47877   aWalData[0] = pWal->hdr.mxFrame;
   47878   aWalData[1] = pWal->hdr.aFrameCksum[0];
   47879   aWalData[2] = pWal->hdr.aFrameCksum[1];
   47880   aWalData[3] = pWal->nCkpt;
   47881 }
   47882 
   47883 /*
   47884 ** Move the write position of the WAL back to the point identified by
   47885 ** the values in the aWalData[] array. aWalData must point to an array
   47886 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   47887 ** by a call to WalSavepoint().
   47888 */
   47889 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   47890   int rc = SQLITE_OK;
   47891 
   47892   assert( pWal->writeLock );
   47893   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   47894 
   47895   if( aWalData[3]!=pWal->nCkpt ){
   47896     /* This savepoint was opened immediately after the write-transaction
   47897     ** was started. Right after that, the writer decided to wrap around
   47898     ** to the start of the log. Update the savepoint values to match.
   47899     */
   47900     aWalData[0] = 0;
   47901     aWalData[3] = pWal->nCkpt;
   47902   }
   47903 
   47904   if( aWalData[0]<pWal->hdr.mxFrame ){
   47905     pWal->hdr.mxFrame = aWalData[0];
   47906     pWal->hdr.aFrameCksum[0] = aWalData[1];
   47907     pWal->hdr.aFrameCksum[1] = aWalData[2];
   47908     walCleanupHash(pWal);
   47909   }
   47910 
   47911   return rc;
   47912 }
   47913 
   47914 
   47915 /*
   47916 ** This function is called just before writing a set of frames to the log
   47917 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   47918 ** to the current log file, it is possible to overwrite the start of the
   47919 ** existing log file with the new frames (i.e. "reset" the log). If so,
   47920 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   47921 ** unchanged.
   47922 **
   47923 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   47924 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   47925 ** if an error occurs.
   47926 */
   47927 static int walRestartLog(Wal *pWal){
   47928   int rc = SQLITE_OK;
   47929   int cnt;
   47930 
   47931   if( pWal->readLock==0 ){
   47932     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   47933     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   47934     if( pInfo->nBackfill>0 ){
   47935       u32 salt1;
   47936       sqlite3_randomness(4, &salt1);
   47937       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47938       if( rc==SQLITE_OK ){
   47939         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   47940         ** readers are currently using the WAL), then the transactions
   47941         ** frames will overwrite the start of the existing log. Update the
   47942         ** wal-index header to reflect this.
   47943         **
   47944         ** In theory it would be Ok to update the cache of the header only
   47945         ** at this point. But updating the actual wal-index header is also
   47946         ** safe and means there is no special case for sqlite3WalUndo()
   47947         ** to handle if this transaction is rolled back.
   47948         */
   47949         int i;                    /* Loop counter */
   47950         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
   47951 
   47952         pWal->nCkpt++;
   47953         pWal->hdr.mxFrame = 0;
   47954         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   47955         aSalt[1] = salt1;
   47956         walIndexWriteHdr(pWal);
   47957         pInfo->nBackfill = 0;
   47958         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   47959         assert( pInfo->aReadMark[0]==0 );
   47960         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   47961       }else if( rc!=SQLITE_BUSY ){
   47962         return rc;
   47963       }
   47964     }
   47965     walUnlockShared(pWal, WAL_READ_LOCK(0));
   47966     pWal->readLock = -1;
   47967     cnt = 0;
   47968     do{
   47969       int notUsed;
   47970       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   47971     }while( rc==WAL_RETRY );
   47972     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   47973     testcase( (rc&0xff)==SQLITE_IOERR );
   47974     testcase( rc==SQLITE_PROTOCOL );
   47975     testcase( rc==SQLITE_OK );
   47976   }
   47977   return rc;
   47978 }
   47979 
   47980 /*
   47981 ** Information about the current state of the WAL file and where
   47982 ** the next fsync should occur - passed from sqlite3WalFrames() into
   47983 ** walWriteToLog().
   47984 */
   47985 typedef struct WalWriter {
   47986   Wal *pWal;                   /* The complete WAL information */
   47987   sqlite3_file *pFd;           /* The WAL file to which we write */
   47988   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
   47989   int syncFlags;               /* Flags for the fsync */
   47990   int szPage;                  /* Size of one page */
   47991 } WalWriter;
   47992 
   47993 /*
   47994 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
   47995 ** Do a sync when crossing the p->iSyncPoint boundary.
   47996 **
   47997 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
   47998 ** first write the part before iSyncPoint, then sync, then write the
   47999 ** rest.
   48000 */
   48001 static int walWriteToLog(
   48002   WalWriter *p,              /* WAL to write to */
   48003   void *pContent,            /* Content to be written */
   48004   int iAmt,                  /* Number of bytes to write */
   48005   sqlite3_int64 iOffset      /* Start writing at this offset */
   48006 ){
   48007   int rc;
   48008   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
   48009     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
   48010     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
   48011     if( rc ) return rc;
   48012     iOffset += iFirstAmt;
   48013     iAmt -= iFirstAmt;
   48014     pContent = (void*)(iFirstAmt + (char*)pContent);
   48015     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
   48016     rc = sqlite3OsSync(p->pFd, p->syncFlags);
   48017     if( iAmt==0 || rc ) return rc;
   48018   }
   48019   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
   48020   return rc;
   48021 }
   48022 
   48023 /*
   48024 ** Write out a single frame of the WAL
   48025 */
   48026 static int walWriteOneFrame(
   48027   WalWriter *p,               /* Where to write the frame */
   48028   PgHdr *pPage,               /* The page of the frame to be written */
   48029   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
   48030   sqlite3_int64 iOffset       /* Byte offset at which to write */
   48031 ){
   48032   int rc;                         /* Result code from subfunctions */
   48033   void *pData;                    /* Data actually written */
   48034   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   48035 #if defined(SQLITE_HAS_CODEC)
   48036   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
   48037 #else
   48038   pData = pPage->pData;
   48039 #endif
   48040   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   48041   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   48042   if( rc ) return rc;
   48043   /* Write the page data */
   48044   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
   48045   return rc;
   48046 }
   48047 
   48048 /*
   48049 ** Write a set of frames to the log. The caller must hold the write-lock
   48050 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   48051 */
   48052 SQLITE_PRIVATE int sqlite3WalFrames(
   48053   Wal *pWal,                      /* Wal handle to write to */
   48054   int szPage,                     /* Database page-size in bytes */
   48055   PgHdr *pList,                   /* List of dirty pages to write */
   48056   Pgno nTruncate,                 /* Database size after this commit */
   48057   int isCommit,                   /* True if this is a commit */
   48058   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   48059 ){
   48060   int rc;                         /* Used to catch return codes */
   48061   u32 iFrame;                     /* Next frame address */
   48062   PgHdr *p;                       /* Iterator to run through pList with. */
   48063   PgHdr *pLast = 0;               /* Last frame in list */
   48064   int nExtra = 0;                 /* Number of extra copies of last page */
   48065   int szFrame;                    /* The size of a single frame */
   48066   i64 iOffset;                    /* Next byte to write in WAL file */
   48067   WalWriter w;                    /* The writer */
   48068 
   48069   assert( pList );
   48070   assert( pWal->writeLock );
   48071 
   48072   /* If this frame set completes a transaction, then nTruncate>0.  If
   48073   ** nTruncate==0 then this frame set does not complete the transaction. */
   48074   assert( (isCommit!=0)==(nTruncate!=0) );
   48075 
   48076 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   48077   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   48078     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   48079               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   48080   }
   48081 #endif
   48082 
   48083   /* See if it is possible to write these frames into the start of the
   48084   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   48085   */
   48086   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   48087     return rc;
   48088   }
   48089 
   48090   /* If this is the first frame written into the log, write the WAL
   48091   ** header to the start of the WAL file. See comments at the top of
   48092   ** this source file for a description of the WAL header format.
   48093   */
   48094   iFrame = pWal->hdr.mxFrame;
   48095   if( iFrame==0 ){
   48096     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   48097     u32 aCksum[2];                /* Checksum for wal-header */
   48098 
   48099     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   48100     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   48101     sqlite3Put4byte(&aWalHdr[8], szPage);
   48102     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   48103     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
   48104     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   48105     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   48106     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   48107     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   48108 
   48109     pWal->szPage = szPage;
   48110     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   48111     pWal->hdr.aFrameCksum[0] = aCksum[0];
   48112     pWal->hdr.aFrameCksum[1] = aCksum[1];
   48113     pWal->truncateOnCommit = 1;
   48114 
   48115     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   48116     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   48117     if( rc!=SQLITE_OK ){
   48118       return rc;
   48119     }
   48120 
   48121     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
   48122     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
   48123     ** an out-of-order write following a WAL restart could result in
   48124     ** database corruption.  See the ticket:
   48125     **
   48126     **     http://localhost:591/sqlite/info/ff5be73dee
   48127     */
   48128     if( pWal->syncHeader && sync_flags ){
   48129       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
   48130       if( rc ) return rc;
   48131     }
   48132   }
   48133   assert( (int)pWal->szPage==szPage );
   48134 
   48135   /* Setup information needed to write frames into the WAL */
   48136   w.pWal = pWal;
   48137   w.pFd = pWal->pWalFd;
   48138   w.iSyncPoint = 0;
   48139   w.syncFlags = sync_flags;
   48140   w.szPage = szPage;
   48141   iOffset = walFrameOffset(iFrame+1, szPage);
   48142   szFrame = szPage + WAL_FRAME_HDRSIZE;
   48143 
   48144   /* Write all frames into the log file exactly once */
   48145   for(p=pList; p; p=p->pDirty){
   48146     int nDbSize;   /* 0 normally.  Positive == commit flag */
   48147     iFrame++;
   48148     assert( iOffset==walFrameOffset(iFrame, szPage) );
   48149     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   48150     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
   48151     if( rc ) return rc;
   48152     pLast = p;
   48153     iOffset += szFrame;
   48154   }
   48155 
   48156   /* If this is the end of a transaction, then we might need to pad
   48157   ** the transaction and/or sync the WAL file.
   48158   **
   48159   ** Padding and syncing only occur if this set of frames complete a
   48160   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
   48161   ** or synchonous==OFF, then no padding or syncing are needed.
   48162   **
   48163   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
   48164   ** needed and only the sync is done.  If padding is needed, then the
   48165   ** final frame is repeated (with its commit mark) until the next sector
   48166   ** boundary is crossed.  Only the part of the WAL prior to the last
   48167   ** sector boundary is synced; the part of the last frame that extends
   48168   ** past the sector boundary is written after the sync.
   48169   */
   48170   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
   48171     if( pWal->padToSectorBoundary ){
   48172       int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
   48173       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
   48174       while( iOffset<w.iSyncPoint ){
   48175         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
   48176         if( rc ) return rc;
   48177         iOffset += szFrame;
   48178         nExtra++;
   48179       }
   48180     }else{
   48181       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
   48182     }
   48183   }
   48184 
   48185   /* If this frame set completes the first transaction in the WAL and
   48186   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
   48187   ** journal size limit, if possible.
   48188   */
   48189   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
   48190     i64 sz = pWal->mxWalSize;
   48191     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
   48192       sz = walFrameOffset(iFrame+nExtra+1, szPage);
   48193     }
   48194     walLimitSize(pWal, sz);
   48195     pWal->truncateOnCommit = 0;
   48196   }
   48197 
   48198   /* Append data to the wal-index. It is not necessary to lock the
   48199   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   48200   ** guarantees that there are no other writers, and no data that may
   48201   ** be in use by existing readers is being overwritten.
   48202   */
   48203   iFrame = pWal->hdr.mxFrame;
   48204   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   48205     iFrame++;
   48206     rc = walIndexAppend(pWal, iFrame, p->pgno);
   48207   }
   48208   while( rc==SQLITE_OK && nExtra>0 ){
   48209     iFrame++;
   48210     nExtra--;
   48211     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   48212   }
   48213 
   48214   if( rc==SQLITE_OK ){
   48215     /* Update the private copy of the header. */
   48216     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   48217     testcase( szPage<=32768 );
   48218     testcase( szPage>=65536 );
   48219     pWal->hdr.mxFrame = iFrame;
   48220     if( isCommit ){
   48221       pWal->hdr.iChange++;
   48222       pWal->hdr.nPage = nTruncate;
   48223     }
   48224     /* If this is a commit, update the wal-index header too. */
   48225     if( isCommit ){
   48226       walIndexWriteHdr(pWal);
   48227       pWal->iCallback = iFrame;
   48228     }
   48229   }
   48230 
   48231   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   48232   return rc;
   48233 }
   48234 
   48235 /*
   48236 ** This routine is called to implement sqlite3_wal_checkpoint() and
   48237 ** related interfaces.
   48238 **
   48239 ** Obtain a CHECKPOINT lock and then backfill as much information as
   48240 ** we can from WAL into the database.
   48241 **
   48242 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
   48243 ** callback. In this case this function runs a blocking checkpoint.
   48244 */
   48245 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   48246   Wal *pWal,                      /* Wal connection */
   48247   int eMode,                      /* PASSIVE, FULL or RESTART */
   48248   int (*xBusy)(void*),            /* Function to call when busy */
   48249   void *pBusyArg,                 /* Context argument for xBusyHandler */
   48250   int sync_flags,                 /* Flags to sync db file with (or 0) */
   48251   int nBuf,                       /* Size of temporary buffer */
   48252   u8 *zBuf,                       /* Temporary buffer to use */
   48253   int *pnLog,                     /* OUT: Number of frames in WAL */
   48254   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
   48255 ){
   48256   int rc;                         /* Return code */
   48257   int isChanged = 0;              /* True if a new wal-index header is loaded */
   48258   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
   48259 
   48260   assert( pWal->ckptLock==0 );
   48261   assert( pWal->writeLock==0 );
   48262 
   48263   if( pWal->readOnly ) return SQLITE_READONLY;
   48264   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   48265   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   48266   if( rc ){
   48267     /* Usually this is SQLITE_BUSY meaning that another thread or process
   48268     ** is already running a checkpoint, or maybe a recovery.  But it might
   48269     ** also be SQLITE_IOERR. */
   48270     return rc;
   48271   }
   48272   pWal->ckptLock = 1;
   48273 
   48274   /* If this is a blocking-checkpoint, then obtain the write-lock as well
   48275   ** to prevent any writers from running while the checkpoint is underway.
   48276   ** This has to be done before the call to walIndexReadHdr() below.
   48277   **
   48278   ** If the writer lock cannot be obtained, then a passive checkpoint is
   48279   ** run instead. Since the checkpointer is not holding the writer lock,
   48280   ** there is no point in blocking waiting for any readers. Assuming no
   48281   ** other error occurs, this function will return SQLITE_BUSY to the caller.
   48282   */
   48283   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
   48284     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
   48285     if( rc==SQLITE_OK ){
   48286       pWal->writeLock = 1;
   48287     }else if( rc==SQLITE_BUSY ){
   48288       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
   48289       rc = SQLITE_OK;
   48290     }
   48291   }
   48292 
   48293   /* Read the wal-index header. */
   48294   if( rc==SQLITE_OK ){
   48295     rc = walIndexReadHdr(pWal, &isChanged);
   48296   }
   48297 
   48298   /* Copy data from the log to the database file. */
   48299   if( rc==SQLITE_OK ){
   48300     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
   48301       rc = SQLITE_CORRUPT_BKPT;
   48302     }else{
   48303       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
   48304     }
   48305 
   48306     /* If no error occurred, set the output variables. */
   48307     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
   48308       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
   48309       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
   48310     }
   48311   }
   48312 
   48313   if( isChanged ){
   48314     /* If a new wal-index header was loaded before the checkpoint was
   48315     ** performed, then the pager-cache associated with pWal is now
   48316     ** out of date. So zero the cached wal-index header to ensure that
   48317     ** next time the pager opens a snapshot on this database it knows that
   48318     ** the cache needs to be reset.
   48319     */
   48320     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   48321   }
   48322 
   48323   /* Release the locks. */
   48324   sqlite3WalEndWriteTransaction(pWal);
   48325   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   48326   pWal->ckptLock = 0;
   48327   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   48328   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
   48329 }
   48330 
   48331 /* Return the value to pass to a sqlite3_wal_hook callback, the
   48332 ** number of frames in the WAL at the point of the last commit since
   48333 ** sqlite3WalCallback() was called.  If no commits have occurred since
   48334 ** the last call, then return 0.
   48335 */
   48336 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   48337   u32 ret = 0;
   48338   if( pWal ){
   48339     ret = pWal->iCallback;
   48340     pWal->iCallback = 0;
   48341   }
   48342   return (int)ret;
   48343 }
   48344 
   48345 /*
   48346 ** This function is called to change the WAL subsystem into or out
   48347 ** of locking_mode=EXCLUSIVE.
   48348 **
   48349 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   48350 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   48351 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   48352 ** or if the acquisition of the lock fails, then return 0.  If the
   48353 ** transition out of exclusive-mode is successful, return 1.  This
   48354 ** operation must occur while the pager is still holding the exclusive
   48355 ** lock on the main database file.
   48356 **
   48357 ** If op is one, then change from locking_mode=NORMAL into
   48358 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   48359 ** be released.  Return 1 if the transition is made and 0 if the
   48360 ** WAL is already in exclusive-locking mode - meaning that this
   48361 ** routine is a no-op.  The pager must already hold the exclusive lock
   48362 ** on the main database file before invoking this operation.
   48363 **
   48364 ** If op is negative, then do a dry-run of the op==1 case but do
   48365 ** not actually change anything. The pager uses this to see if it
   48366 ** should acquire the database exclusive lock prior to invoking
   48367 ** the op==1 case.
   48368 */
   48369 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   48370   int rc;
   48371   assert( pWal->writeLock==0 );
   48372   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   48373 
   48374   /* pWal->readLock is usually set, but might be -1 if there was a
   48375   ** prior error while attempting to acquire are read-lock. This cannot
   48376   ** happen if the connection is actually in exclusive mode (as no xShmLock
   48377   ** locks are taken in this case). Nor should the pager attempt to
   48378   ** upgrade to exclusive-mode following such an error.
   48379   */
   48380   assert( pWal->readLock>=0 || pWal->lockError );
   48381   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   48382 
   48383   if( op==0 ){
   48384     if( pWal->exclusiveMode ){
   48385       pWal->exclusiveMode = 0;
   48386       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   48387         pWal->exclusiveMode = 1;
   48388       }
   48389       rc = pWal->exclusiveMode==0;
   48390     }else{
   48391       /* Already in locking_mode=NORMAL */
   48392       rc = 0;
   48393     }
   48394   }else if( op>0 ){
   48395     assert( pWal->exclusiveMode==0 );
   48396     assert( pWal->readLock>=0 );
   48397     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   48398     pWal->exclusiveMode = 1;
   48399     rc = 1;
   48400   }else{
   48401     rc = pWal->exclusiveMode==0;
   48402   }
   48403   return rc;
   48404 }
   48405 
   48406 /*
   48407 ** Return true if the argument is non-NULL and the WAL module is using
   48408 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   48409 ** WAL module is using shared-memory, return false.
   48410 */
   48411 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   48412   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   48413 }
   48414 
   48415 #ifdef SQLITE_ENABLE_ZIPVFS
   48416 /*
   48417 ** If the argument is not NULL, it points to a Wal object that holds a
   48418 ** read-lock. This function returns the database page-size if it is known,
   48419 ** or zero if it is not (or if pWal is NULL).
   48420 */
   48421 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
   48422   assert( pWal==0 || pWal->readLock>=0 );
   48423   return (pWal ? pWal->szPage : 0);
   48424 }
   48425 #endif
   48426 
   48427 #endif /* #ifndef SQLITE_OMIT_WAL */
   48428 
   48429 /************** End of wal.c *************************************************/
   48430 /************** Begin file btmutex.c *****************************************/
   48431 /*
   48432 ** 2007 August 27
   48433 **
   48434 ** The author disclaims copyright to this source code.  In place of
   48435 ** a legal notice, here is a blessing:
   48436 **
   48437 **    May you do good and not evil.
   48438 **    May you find forgiveness for yourself and forgive others.
   48439 **    May you share freely, never taking more than you give.
   48440 **
   48441 *************************************************************************
   48442 **
   48443 ** This file contains code used to implement mutexes on Btree objects.
   48444 ** This code really belongs in btree.c.  But btree.c is getting too
   48445 ** big and we want to break it down some.  This packaged seemed like
   48446 ** a good breakout.
   48447 */
   48448 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   48449 /************** Begin file btreeInt.h ****************************************/
   48450 /*
   48451 ** 2004 April 6
   48452 **
   48453 ** The author disclaims copyright to this source code.  In place of
   48454 ** a legal notice, here is a blessing:
   48455 **
   48456 **    May you do good and not evil.
   48457 **    May you find forgiveness for yourself and forgive others.
   48458 **    May you share freely, never taking more than you give.
   48459 **
   48460 *************************************************************************
   48461 ** This file implements a external (disk-based) database using BTrees.
   48462 ** For a detailed discussion of BTrees, refer to
   48463 **
   48464 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   48465 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   48466 **     Publishing Company, Reading, Massachusetts.
   48467 **
   48468 ** The basic idea is that each page of the file contains N database
   48469 ** entries and N+1 pointers to subpages.
   48470 **
   48471 **   ----------------------------------------------------------------
   48472 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   48473 **   ----------------------------------------------------------------
   48474 **
   48475 ** All of the keys on the page that Ptr(0) points to have values less
   48476 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   48477 ** values greater than Key(0) and less than Key(1).  All of the keys
   48478 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   48479 ** so forth.
   48480 **
   48481 ** Finding a particular key requires reading O(log(M)) pages from the
   48482 ** disk where M is the number of entries in the tree.
   48483 **
   48484 ** In this implementation, a single file can hold one or more separate
   48485 ** BTrees.  Each BTree is identified by the index of its root page.  The
   48486 ** key and data for any entry are combined to form the "payload".  A
   48487 ** fixed amount of payload can be carried directly on the database
   48488 ** page.  If the payload is larger than the preset amount then surplus
   48489 ** bytes are stored on overflow pages.  The payload for an entry
   48490 ** and the preceding pointer are combined to form a "Cell".  Each
   48491 ** page has a small header which contains the Ptr(N) pointer and other
   48492 ** information such as the size of key and data.
   48493 **
   48494 ** FORMAT DETAILS
   48495 **
   48496 ** The file is divided into pages.  The first page is called page 1,
   48497 ** the second is page 2, and so forth.  A page number of zero indicates
   48498 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   48499 ** Each page can be either a btree page, a freelist page, an overflow
   48500 ** page, or a pointer-map page.
   48501 **
   48502 ** The first page is always a btree page.  The first 100 bytes of the first
   48503 ** page contain a special header (the "file header") that describes the file.
   48504 ** The format of the file header is as follows:
   48505 **
   48506 **   OFFSET   SIZE    DESCRIPTION
   48507 **      0      16     Header string: "SQLite format 3\000"
   48508 **     16       2     Page size in bytes.
   48509 **     18       1     File format write version
   48510 **     19       1     File format read version
   48511 **     20       1     Bytes of unused space at the end of each page
   48512 **     21       1     Max embedded payload fraction
   48513 **     22       1     Min embedded payload fraction
   48514 **     23       1     Min leaf payload fraction
   48515 **     24       4     File change counter
   48516 **     28       4     Reserved for future use
   48517 **     32       4     First freelist page
   48518 **     36       4     Number of freelist pages in the file
   48519 **     40      60     15 4-byte meta values passed to higher layers
   48520 **
   48521 **     40       4     Schema cookie
   48522 **     44       4     File format of schema layer
   48523 **     48       4     Size of page cache
   48524 **     52       4     Largest root-page (auto/incr_vacuum)
   48525 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   48526 **     60       4     User version
   48527 **     64       4     Incremental vacuum mode
   48528 **     68       4     unused
   48529 **     72       4     unused
   48530 **     76       4     unused
   48531 **
   48532 ** All of the integer values are big-endian (most significant byte first).
   48533 **
   48534 ** The file change counter is incremented when the database is changed
   48535 ** This counter allows other processes to know when the file has changed
   48536 ** and thus when they need to flush their cache.
   48537 **
   48538 ** The max embedded payload fraction is the amount of the total usable
   48539 ** space in a page that can be consumed by a single cell for standard
   48540 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   48541 ** is to limit the maximum cell size so that at least 4 cells will fit
   48542 ** on one page.  Thus the default max embedded payload fraction is 64.
   48543 **
   48544 ** If the payload for a cell is larger than the max payload, then extra
   48545 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   48546 ** as many bytes as possible are moved into the overflow pages without letting
   48547 ** the cell size drop below the min embedded payload fraction.
   48548 **
   48549 ** The min leaf payload fraction is like the min embedded payload fraction
   48550 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   48551 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   48552 ** not specified in the header.
   48553 **
   48554 ** Each btree pages is divided into three sections:  The header, the
   48555 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   48556 ** file header that occurs before the page header.
   48557 **
   48558 **      |----------------|
   48559 **      | file header    |   100 bytes.  Page 1 only.
   48560 **      |----------------|
   48561 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   48562 **      |----------------|
   48563 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   48564 **      | array          |   |  Grows downward
   48565 **      |                |   v
   48566 **      |----------------|
   48567 **      | unallocated    |
   48568 **      | space          |
   48569 **      |----------------|   ^  Grows upwards
   48570 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   48571 **      | area           |   |  and free space fragments.
   48572 **      |----------------|
   48573 **
   48574 ** The page headers looks like this:
   48575 **
   48576 **   OFFSET   SIZE     DESCRIPTION
   48577 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   48578 **      1       2      byte offset to the first freeblock
   48579 **      3       2      number of cells on this page
   48580 **      5       2      first byte of the cell content area
   48581 **      7       1      number of fragmented free bytes
   48582 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   48583 **
   48584 ** The flags define the format of this btree page.  The leaf flag means that
   48585 ** this page has no children.  The zerodata flag means that this page carries
   48586 ** only keys and no data.  The intkey flag means that the key is a integer
   48587 ** which is stored in the key size entry of the cell header rather than in
   48588 ** the payload area.
   48589 **
   48590 ** The cell pointer array begins on the first byte after the page header.
   48591 ** The cell pointer array contains zero or more 2-byte numbers which are
   48592 ** offsets from the beginning of the page to the cell content in the cell
   48593 ** content area.  The cell pointers occur in sorted order.  The system strives
   48594 ** to keep free space after the last cell pointer so that new cells can
   48595 ** be easily added without having to defragment the page.
   48596 **
   48597 ** Cell content is stored at the very end of the page and grows toward the
   48598 ** beginning of the page.
   48599 **
   48600 ** Unused space within the cell content area is collected into a linked list of
   48601 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   48602 ** to the first freeblock is given in the header.  Freeblocks occur in
   48603 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   48604 ** any group of 3 or fewer unused bytes in the cell content area cannot
   48605 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   48606 ** a fragment.  The total number of bytes in all fragments is recorded.
   48607 ** in the page header at offset 7.
   48608 **
   48609 **    SIZE    DESCRIPTION
   48610 **      2     Byte offset of the next freeblock
   48611 **      2     Bytes in this freeblock
   48612 **
   48613 ** Cells are of variable length.  Cells are stored in the cell content area at
   48614 ** the end of the page.  Pointers to the cells are in the cell pointer array
   48615 ** that immediately follows the page header.  Cells is not necessarily
   48616 ** contiguous or in order, but cell pointers are contiguous and in order.
   48617 **
   48618 ** Cell content makes use of variable length integers.  A variable
   48619 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   48620 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   48621 ** the first byte with bit 8 clear.  The most significant byte of the integer
   48622 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   48623 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   48624 ** allows a 64-bit integer to be encoded in 9 bytes.
   48625 **
   48626 **    0x00                      becomes  0x00000000
   48627 **    0x7f                      becomes  0x0000007f
   48628 **    0x81 0x00                 becomes  0x00000080
   48629 **    0x82 0x00                 becomes  0x00000100
   48630 **    0x80 0x7f                 becomes  0x0000007f
   48631 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   48632 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   48633 **
   48634 ** Variable length integers are used for rowids and to hold the number of
   48635 ** bytes of key and data in a btree cell.
   48636 **
   48637 ** The content of a cell looks like this:
   48638 **
   48639 **    SIZE    DESCRIPTION
   48640 **      4     Page number of the left child. Omitted if leaf flag is set.
   48641 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   48642 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   48643 **      *     Payload
   48644 **      4     First page of the overflow chain.  Omitted if no overflow
   48645 **
   48646 ** Overflow pages form a linked list.  Each page except the last is completely
   48647 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   48648 ** as 1 byte of data.
   48649 **
   48650 **    SIZE    DESCRIPTION
   48651 **      4     Page number of next overflow page
   48652 **      *     Data
   48653 **
   48654 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   48655 ** file header points to the first in a linked list of trunk page.  Each trunk
   48656 ** page points to multiple leaf pages.  The content of a leaf page is
   48657 ** unspecified.  A trunk page looks like this:
   48658 **
   48659 **    SIZE    DESCRIPTION
   48660 **      4     Page number of next trunk page
   48661 **      4     Number of leaf pointers on this page
   48662 **      *     zero or more pages numbers of leaves
   48663 */
   48664 
   48665 
   48666 /* The following value is the maximum cell size assuming a maximum page
   48667 ** size give above.
   48668 */
   48669 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
   48670 
   48671 /* The maximum number of cells on a single page of the database.  This
   48672 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   48673 ** plus 2 bytes for the index to the cell in the page header).  Such
   48674 ** small cells will be rare, but they are possible.
   48675 */
   48676 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   48677 
   48678 /* Forward declarations */
   48679 typedef struct MemPage MemPage;
   48680 typedef struct BtLock BtLock;
   48681 
   48682 /*
   48683 ** This is a magic string that appears at the beginning of every
   48684 ** SQLite database in order to identify the file as a real database.
   48685 **
   48686 ** You can change this value at compile-time by specifying a
   48687 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   48688 ** header must be exactly 16 bytes including the zero-terminator so
   48689 ** the string itself should be 15 characters long.  If you change
   48690 ** the header, then your custom library will not be able to read
   48691 ** databases generated by the standard tools and the standard tools
   48692 ** will not be able to read databases created by your custom library.
   48693 */
   48694 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   48695 #  define SQLITE_FILE_HEADER "SQLite format 3"
   48696 #endif
   48697 
   48698 /*
   48699 ** Page type flags.  An ORed combination of these flags appear as the
   48700 ** first byte of on-disk image of every BTree page.
   48701 */
   48702 #define PTF_INTKEY    0x01
   48703 #define PTF_ZERODATA  0x02
   48704 #define PTF_LEAFDATA  0x04
   48705 #define PTF_LEAF      0x08
   48706 
   48707 /*
   48708 ** As each page of the file is loaded into memory, an instance of the following
   48709 ** structure is appended and initialized to zero.  This structure stores
   48710 ** information about the page that is decoded from the raw file page.
   48711 **
   48712 ** The pParent field points back to the parent page.  This allows us to
   48713 ** walk up the BTree from any leaf to the root.  Care must be taken to
   48714 ** unref() the parent page pointer when this page is no longer referenced.
   48715 ** The pageDestructor() routine handles that chore.
   48716 **
   48717 ** Access to all fields of this structure is controlled by the mutex
   48718 ** stored in MemPage.pBt->mutex.
   48719 */
   48720 struct MemPage {
   48721   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   48722   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   48723   u8 intKey;           /* True if intkey flag is set */
   48724   u8 leaf;             /* True if leaf flag is set */
   48725   u8 hasData;          /* True if this page stores data */
   48726   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   48727   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   48728   u8 max1bytePayload;  /* min(maxLocal,127) */
   48729   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   48730   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   48731   u16 cellOffset;      /* Index in aData of first cell pointer */
   48732   u16 nFree;           /* Number of free bytes on the page */
   48733   u16 nCell;           /* Number of cells on this page, local and ovfl */
   48734   u16 maskPage;        /* Mask for page offset */
   48735   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
   48736                        ** non-overflow cell */
   48737   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
   48738   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   48739   u8 *aData;           /* Pointer to disk image of the page data */
   48740   u8 *aDataEnd;        /* One byte past the end of usable data */
   48741   u8 *aCellIdx;        /* The cell index area */
   48742   DbPage *pDbPage;     /* Pager page handle */
   48743   Pgno pgno;           /* Page number for this page */
   48744 };
   48745 
   48746 /*
   48747 ** The in-memory image of a disk page has the auxiliary information appended
   48748 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   48749 ** that extra information.
   48750 */
   48751 #define EXTRA_SIZE sizeof(MemPage)
   48752 
   48753 /*
   48754 ** A linked list of the following structures is stored at BtShared.pLock.
   48755 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   48756 ** is opened on the table with root page BtShared.iTable. Locks are removed
   48757 ** from this list when a transaction is committed or rolled back, or when
   48758 ** a btree handle is closed.
   48759 */
   48760 struct BtLock {
   48761   Btree *pBtree;        /* Btree handle holding this lock */
   48762   Pgno iTable;          /* Root page of table */
   48763   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   48764   BtLock *pNext;        /* Next in BtShared.pLock list */
   48765 };
   48766 
   48767 /* Candidate values for BtLock.eLock */
   48768 #define READ_LOCK     1
   48769 #define WRITE_LOCK    2
   48770 
   48771 /* A Btree handle
   48772 **
   48773 ** A database connection contains a pointer to an instance of
   48774 ** this object for every database file that it has open.  This structure
   48775 ** is opaque to the database connection.  The database connection cannot
   48776 ** see the internals of this structure and only deals with pointers to
   48777 ** this structure.
   48778 **
   48779 ** For some database files, the same underlying database cache might be
   48780 ** shared between multiple connections.  In that case, each connection
   48781 ** has it own instance of this object.  But each instance of this object
   48782 ** points to the same BtShared object.  The database cache and the
   48783 ** schema associated with the database file are all contained within
   48784 ** the BtShared object.
   48785 **
   48786 ** All fields in this structure are accessed under sqlite3.mutex.
   48787 ** The pBt pointer itself may not be changed while there exists cursors
   48788 ** in the referenced BtShared that point back to this Btree since those
   48789 ** cursors have to go through this Btree to find their BtShared and
   48790 ** they often do so without holding sqlite3.mutex.
   48791 */
   48792 struct Btree {
   48793   sqlite3 *db;       /* The database connection holding this btree */
   48794   BtShared *pBt;     /* Sharable content of this btree */
   48795   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   48796   u8 sharable;       /* True if we can share pBt with another db */
   48797   u8 locked;         /* True if db currently has pBt locked */
   48798   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   48799   int nBackup;       /* Number of backup operations reading this btree */
   48800   Btree *pNext;      /* List of other sharable Btrees from the same db */
   48801   Btree *pPrev;      /* Back pointer of the same list */
   48802 #ifndef SQLITE_OMIT_SHARED_CACHE
   48803   BtLock lock;       /* Object used to lock page 1 */
   48804 #endif
   48805 };
   48806 
   48807 /*
   48808 ** Btree.inTrans may take one of the following values.
   48809 **
   48810 ** If the shared-data extension is enabled, there may be multiple users
   48811 ** of the Btree structure. At most one of these may open a write transaction,
   48812 ** but any number may have active read transactions.
   48813 */
   48814 #define TRANS_NONE  0
   48815 #define TRANS_READ  1
   48816 #define TRANS_WRITE 2
   48817 
   48818 /*
   48819 ** An instance of this object represents a single database file.
   48820 **
   48821 ** A single database file can be in use at the same time by two
   48822 ** or more database connections.  When two or more connections are
   48823 ** sharing the same database file, each connection has it own
   48824 ** private Btree object for the file and each of those Btrees points
   48825 ** to this one BtShared object.  BtShared.nRef is the number of
   48826 ** connections currently sharing this database file.
   48827 **
   48828 ** Fields in this structure are accessed under the BtShared.mutex
   48829 ** mutex, except for nRef and pNext which are accessed under the
   48830 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   48831 ** may not be modified once it is initially set as long as nRef>0.
   48832 ** The pSchema field may be set once under BtShared.mutex and
   48833 ** thereafter is unchanged as long as nRef>0.
   48834 **
   48835 ** isPending:
   48836 **
   48837 **   If a BtShared client fails to obtain a write-lock on a database
   48838 **   table (because there exists one or more read-locks on the table),
   48839 **   the shared-cache enters 'pending-lock' state and isPending is
   48840 **   set to true.
   48841 **
   48842 **   The shared-cache leaves the 'pending lock' state when either of
   48843 **   the following occur:
   48844 **
   48845 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   48846 **     2) The number of locks held by other connections drops to zero.
   48847 **
   48848 **   while in the 'pending-lock' state, no connection may start a new
   48849 **   transaction.
   48850 **
   48851 **   This feature is included to help prevent writer-starvation.
   48852 */
   48853 struct BtShared {
   48854   Pager *pPager;        /* The page cache */
   48855   sqlite3 *db;          /* Database connection currently using this Btree */
   48856   BtCursor *pCursor;    /* A list of all open cursors */
   48857   MemPage *pPage1;      /* First page of the database */
   48858   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   48859 #ifndef SQLITE_OMIT_AUTOVACUUM
   48860   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   48861   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   48862 #endif
   48863   u8 inTransaction;     /* Transaction state */
   48864   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
   48865   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   48866   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   48867   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   48868   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   48869   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   48870   u32 pageSize;         /* Total number of bytes on a page */
   48871   u32 usableSize;       /* Number of usable bytes on each page */
   48872   int nTransaction;     /* Number of open transactions (read + write) */
   48873   u32 nPage;            /* Number of pages in the database */
   48874   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   48875   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   48876   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
   48877   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   48878 #ifndef SQLITE_OMIT_SHARED_CACHE
   48879   int nRef;             /* Number of references to this structure */
   48880   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   48881   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   48882   Btree *pWriter;       /* Btree with currently open write transaction */
   48883 #endif
   48884   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   48885 };
   48886 
   48887 /*
   48888 ** Allowed values for BtShared.btsFlags
   48889 */
   48890 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
   48891 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
   48892 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
   48893 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
   48894 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
   48895 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
   48896 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
   48897 
   48898 /*
   48899 ** An instance of the following structure is used to hold information
   48900 ** about a cell.  The parseCellPtr() function fills in this structure
   48901 ** based on information extract from the raw disk page.
   48902 */
   48903 typedef struct CellInfo CellInfo;
   48904 struct CellInfo {
   48905   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   48906   u8 *pCell;     /* Pointer to the start of cell content */
   48907   u32 nData;     /* Number of bytes of data */
   48908   u32 nPayload;  /* Total amount of payload */
   48909   u16 nHeader;   /* Size of the cell content header in bytes */
   48910   u16 nLocal;    /* Amount of payload held locally */
   48911   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   48912   u16 nSize;     /* Size of the cell content on the main b-tree page */
   48913 };
   48914 
   48915 /*
   48916 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   48917 ** this will be declared corrupt. This value is calculated based on a
   48918 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   48919 ** root-node and 3 for all other internal nodes.
   48920 **
   48921 ** If a tree that appears to be taller than this is encountered, it is
   48922 ** assumed that the database is corrupt.
   48923 */
   48924 #define BTCURSOR_MAX_DEPTH 20
   48925 
   48926 /*
   48927 ** A cursor is a pointer to a particular entry within a particular
   48928 ** b-tree within a database file.
   48929 **
   48930 ** The entry is identified by its MemPage and the index in
   48931 ** MemPage.aCell[] of the entry.
   48932 **
   48933 ** A single database file can be shared by two more database connections,
   48934 ** but cursors cannot be shared.  Each cursor is associated with a
   48935 ** particular database connection identified BtCursor.pBtree.db.
   48936 **
   48937 ** Fields in this structure are accessed under the BtShared.mutex
   48938 ** found at self->pBt->mutex.
   48939 */
   48940 struct BtCursor {
   48941   Btree *pBtree;            /* The Btree to which this cursor belongs */
   48942   BtShared *pBt;            /* The BtShared this cursor points to */
   48943   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   48944   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   48945 #ifndef SQLITE_OMIT_INCRBLOB
   48946   Pgno *aOverflow;          /* Cache of overflow page locations */
   48947 #endif
   48948   Pgno pgnoRoot;            /* The root page of this tree */
   48949   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
   48950   CellInfo info;            /* A parse of the cell we are pointing at */
   48951   i64 nKey;        /* Size of pKey, or last integer key */
   48952   void *pKey;      /* Saved key that was cursor's last known position */
   48953   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   48954   u8 wrFlag;                /* True if writable */
   48955   u8 atLast;                /* Cursor pointing to the last entry */
   48956   u8 validNKey;             /* True if info.nKey is valid */
   48957   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   48958 #ifndef SQLITE_OMIT_INCRBLOB
   48959   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
   48960 #endif
   48961   i16 iPage;                            /* Index of current page in apPage */
   48962   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   48963   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   48964 };
   48965 
   48966 /*
   48967 ** Potential values for BtCursor.eState.
   48968 **
   48969 ** CURSOR_VALID:
   48970 **   Cursor points to a valid entry. getPayload() etc. may be called.
   48971 **
   48972 ** CURSOR_INVALID:
   48973 **   Cursor does not point to a valid entry. This can happen (for example)
   48974 **   because the table is empty or because BtreeCursorFirst() has not been
   48975 **   called.
   48976 **
   48977 ** CURSOR_REQUIRESEEK:
   48978 **   The table that this cursor was opened on still exists, but has been
   48979 **   modified since the cursor was last used. The cursor position is saved
   48980 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   48981 **   this state, restoreCursorPosition() can be called to attempt to
   48982 **   seek the cursor to the saved position.
   48983 **
   48984 ** CURSOR_FAULT:
   48985 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   48986 **   on a different connection that shares the BtShared cache with this
   48987 **   cursor.  The error has left the cache in an inconsistent state.
   48988 **   Do nothing else with this cursor.  Any attempt to use the cursor
   48989 **   should return the error code stored in BtCursor.skip
   48990 */
   48991 #define CURSOR_INVALID           0
   48992 #define CURSOR_VALID             1
   48993 #define CURSOR_REQUIRESEEK       2
   48994 #define CURSOR_FAULT             3
   48995 
   48996 /*
   48997 ** The database page the PENDING_BYTE occupies. This page is never used.
   48998 */
   48999 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   49000 
   49001 /*
   49002 ** These macros define the location of the pointer-map entry for a
   49003 ** database page. The first argument to each is the number of usable
   49004 ** bytes on each page of the database (often 1024). The second is the
   49005 ** page number to look up in the pointer map.
   49006 **
   49007 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   49008 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   49009 ** the offset of the requested map entry.
   49010 **
   49011 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   49012 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   49013 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   49014 ** this test.
   49015 */
   49016 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   49017 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   49018 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   49019 
   49020 /*
   49021 ** The pointer map is a lookup table that identifies the parent page for
   49022 ** each child page in the database file.  The parent page is the page that
   49023 ** contains a pointer to the child.  Every page in the database contains
   49024 ** 0 or 1 parent pages.  (In this context 'database page' refers
   49025 ** to any page that is not part of the pointer map itself.)  Each pointer map
   49026 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   49027 ** The PTRMAP_XXX identifiers below are the valid types.
   49028 **
   49029 ** The purpose of the pointer map is to facility moving pages from one
   49030 ** position in the file to another as part of autovacuum.  When a page
   49031 ** is moved, the pointer in its parent must be updated to point to the
   49032 ** new location.  The pointer map is used to locate the parent page quickly.
   49033 **
   49034 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   49035 **                  used in this case.
   49036 **
   49037 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   49038 **                  is not used in this case.
   49039 **
   49040 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   49041 **                   overflow pages. The page number identifies the page that
   49042 **                   contains the cell with a pointer to this overflow page.
   49043 **
   49044 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   49045 **                   overflow pages. The page-number identifies the previous
   49046 **                   page in the overflow page list.
   49047 **
   49048 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   49049 **               identifies the parent page in the btree.
   49050 */
   49051 #define PTRMAP_ROOTPAGE 1
   49052 #define PTRMAP_FREEPAGE 2
   49053 #define PTRMAP_OVERFLOW1 3
   49054 #define PTRMAP_OVERFLOW2 4
   49055 #define PTRMAP_BTREE 5
   49056 
   49057 /* A bunch of assert() statements to check the transaction state variables
   49058 ** of handle p (type Btree*) are internally consistent.
   49059 */
   49060 #define btreeIntegrity(p) \
   49061   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   49062   assert( p->pBt->inTransaction>=p->inTrans );
   49063 
   49064 
   49065 /*
   49066 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   49067 ** if the database supports auto-vacuum or not. Because it is used
   49068 ** within an expression that is an argument to another macro
   49069 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   49070 ** So, this macro is defined instead.
   49071 */
   49072 #ifndef SQLITE_OMIT_AUTOVACUUM
   49073 #define ISAUTOVACUUM (pBt->autoVacuum)
   49074 #else
   49075 #define ISAUTOVACUUM 0
   49076 #endif
   49077 
   49078 
   49079 /*
   49080 ** This structure is passed around through all the sanity checking routines
   49081 ** in order to keep track of some global state information.
   49082 */
   49083 typedef struct IntegrityCk IntegrityCk;
   49084 struct IntegrityCk {
   49085   BtShared *pBt;    /* The tree being checked out */
   49086   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   49087   int *anRef;       /* Number of times each page is referenced */
   49088   Pgno nPage;       /* Number of pages in the database */
   49089   int mxErr;        /* Stop accumulating errors when this reaches zero */
   49090   int nErr;         /* Number of messages written to zErrMsg so far */
   49091   int mallocFailed; /* A memory allocation error has occurred */
   49092   StrAccum errMsg;  /* Accumulate the error message text here */
   49093 };
   49094 
   49095 /*
   49096 ** Routines to read or write a two- and four-byte big-endian integer values.
   49097 */
   49098 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   49099 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   49100 #define get4byte sqlite3Get4byte
   49101 #define put4byte sqlite3Put4byte
   49102 
   49103 /************** End of btreeInt.h ********************************************/
   49104 /************** Continuing where we left off in btmutex.c ********************/
   49105 #ifndef SQLITE_OMIT_SHARED_CACHE
   49106 #if SQLITE_THREADSAFE
   49107 
   49108 /*
   49109 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   49110 ** set BtShared.db to the database handle associated with p and the
   49111 ** p->locked boolean to true.
   49112 */
   49113 static void lockBtreeMutex(Btree *p){
   49114   assert( p->locked==0 );
   49115   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   49116   assert( sqlite3_mutex_held(p->db->mutex) );
   49117 
   49118   sqlite3_mutex_enter(p->pBt->mutex);
   49119   p->pBt->db = p->db;
   49120   p->locked = 1;
   49121 }
   49122 
   49123 /*
   49124 ** Release the BtShared mutex associated with B-Tree handle p and
   49125 ** clear the p->locked boolean.
   49126 */
   49127 static void unlockBtreeMutex(Btree *p){
   49128   BtShared *pBt = p->pBt;
   49129   assert( p->locked==1 );
   49130   assert( sqlite3_mutex_held(pBt->mutex) );
   49131   assert( sqlite3_mutex_held(p->db->mutex) );
   49132   assert( p->db==pBt->db );
   49133 
   49134   sqlite3_mutex_leave(pBt->mutex);
   49135   p->locked = 0;
   49136 }
   49137 
   49138 /*
   49139 ** Enter a mutex on the given BTree object.
   49140 **
   49141 ** If the object is not sharable, then no mutex is ever required
   49142 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   49143 ** But we keep a reference count in Btree.wantToLock so the behavior
   49144 ** of this interface is recursive.
   49145 **
   49146 ** To avoid deadlocks, multiple Btrees are locked in the same order
   49147 ** by all database connections.  The p->pNext is a list of other
   49148 ** Btrees belonging to the same database connection as the p Btree
   49149 ** which need to be locked after p.  If we cannot get a lock on
   49150 ** p, then first unlock all of the others on p->pNext, then wait
   49151 ** for the lock to become available on p, then relock all of the
   49152 ** subsequent Btrees that desire a lock.
   49153 */
   49154 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   49155   Btree *pLater;
   49156 
   49157   /* Some basic sanity checking on the Btree.  The list of Btrees
   49158   ** connected by pNext and pPrev should be in sorted order by
   49159   ** Btree.pBt value. All elements of the list should belong to
   49160   ** the same connection. Only shared Btrees are on the list. */
   49161   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   49162   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   49163   assert( p->pNext==0 || p->pNext->db==p->db );
   49164   assert( p->pPrev==0 || p->pPrev->db==p->db );
   49165   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   49166 
   49167   /* Check for locking consistency */
   49168   assert( !p->locked || p->wantToLock>0 );
   49169   assert( p->sharable || p->wantToLock==0 );
   49170 
   49171   /* We should already hold a lock on the database connection */
   49172   assert( sqlite3_mutex_held(p->db->mutex) );
   49173 
   49174   /* Unless the database is sharable and unlocked, then BtShared.db
   49175   ** should already be set correctly. */
   49176   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   49177 
   49178   if( !p->sharable ) return;
   49179   p->wantToLock++;
   49180   if( p->locked ) return;
   49181 
   49182   /* In most cases, we should be able to acquire the lock we
   49183   ** want without having to go throught the ascending lock
   49184   ** procedure that follows.  Just be sure not to block.
   49185   */
   49186   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   49187     p->pBt->db = p->db;
   49188     p->locked = 1;
   49189     return;
   49190   }
   49191 
   49192   /* To avoid deadlock, first release all locks with a larger
   49193   ** BtShared address.  Then acquire our lock.  Then reacquire
   49194   ** the other BtShared locks that we used to hold in ascending
   49195   ** order.
   49196   */
   49197   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   49198     assert( pLater->sharable );
   49199     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   49200     assert( !pLater->locked || pLater->wantToLock>0 );
   49201     if( pLater->locked ){
   49202       unlockBtreeMutex(pLater);
   49203     }
   49204   }
   49205   lockBtreeMutex(p);
   49206   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   49207     if( pLater->wantToLock ){
   49208       lockBtreeMutex(pLater);
   49209     }
   49210   }
   49211 }
   49212 
   49213 /*
   49214 ** Exit the recursive mutex on a Btree.
   49215 */
   49216 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   49217   if( p->sharable ){
   49218     assert( p->wantToLock>0 );
   49219     p->wantToLock--;
   49220     if( p->wantToLock==0 ){
   49221       unlockBtreeMutex(p);
   49222     }
   49223   }
   49224 }
   49225 
   49226 #ifndef NDEBUG
   49227 /*
   49228 ** Return true if the BtShared mutex is held on the btree, or if the
   49229 ** B-Tree is not marked as sharable.
   49230 **
   49231 ** This routine is used only from within assert() statements.
   49232 */
   49233 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   49234   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   49235   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   49236   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   49237   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   49238 
   49239   return (p->sharable==0 || p->locked);
   49240 }
   49241 #endif
   49242 
   49243 
   49244 #ifndef SQLITE_OMIT_INCRBLOB
   49245 /*
   49246 ** Enter and leave a mutex on a Btree given a cursor owned by that
   49247 ** Btree.  These entry points are used by incremental I/O and can be
   49248 ** omitted if that module is not used.
   49249 */
   49250 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   49251   sqlite3BtreeEnter(pCur->pBtree);
   49252 }
   49253 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   49254   sqlite3BtreeLeave(pCur->pBtree);
   49255 }
   49256 #endif /* SQLITE_OMIT_INCRBLOB */
   49257 
   49258 
   49259 /*
   49260 ** Enter the mutex on every Btree associated with a database
   49261 ** connection.  This is needed (for example) prior to parsing
   49262 ** a statement since we will be comparing table and column names
   49263 ** against all schemas and we do not want those schemas being
   49264 ** reset out from under us.
   49265 **
   49266 ** There is a corresponding leave-all procedures.
   49267 **
   49268 ** Enter the mutexes in accending order by BtShared pointer address
   49269 ** to avoid the possibility of deadlock when two threads with
   49270 ** two or more btrees in common both try to lock all their btrees
   49271 ** at the same instant.
   49272 */
   49273 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   49274   int i;
   49275   Btree *p;
   49276   assert( sqlite3_mutex_held(db->mutex) );
   49277   for(i=0; i<db->nDb; i++){
   49278     p = db->aDb[i].pBt;
   49279     if( p ) sqlite3BtreeEnter(p);
   49280   }
   49281 }
   49282 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   49283   int i;
   49284   Btree *p;
   49285   assert( sqlite3_mutex_held(db->mutex) );
   49286   for(i=0; i<db->nDb; i++){
   49287     p = db->aDb[i].pBt;
   49288     if( p ) sqlite3BtreeLeave(p);
   49289   }
   49290 }
   49291 
   49292 /*
   49293 ** Return true if a particular Btree requires a lock.  Return FALSE if
   49294 ** no lock is ever required since it is not sharable.
   49295 */
   49296 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
   49297   return p->sharable;
   49298 }
   49299 
   49300 #ifndef NDEBUG
   49301 /*
   49302 ** Return true if the current thread holds the database connection
   49303 ** mutex and all required BtShared mutexes.
   49304 **
   49305 ** This routine is used inside assert() statements only.
   49306 */
   49307 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   49308   int i;
   49309   if( !sqlite3_mutex_held(db->mutex) ){
   49310     return 0;
   49311   }
   49312   for(i=0; i<db->nDb; i++){
   49313     Btree *p;
   49314     p = db->aDb[i].pBt;
   49315     if( p && p->sharable &&
   49316          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   49317       return 0;
   49318     }
   49319   }
   49320   return 1;
   49321 }
   49322 #endif /* NDEBUG */
   49323 
   49324 #ifndef NDEBUG
   49325 /*
   49326 ** Return true if the correct mutexes are held for accessing the
   49327 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
   49328 ** access are:
   49329 **
   49330 **   (1) The mutex on db
   49331 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
   49332 **
   49333 ** If pSchema is not NULL, then iDb is computed from pSchema and
   49334 ** db using sqlite3SchemaToIndex().
   49335 */
   49336 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
   49337   Btree *p;
   49338   assert( db!=0 );
   49339   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
   49340   assert( iDb>=0 && iDb<db->nDb );
   49341   if( !sqlite3_mutex_held(db->mutex) ) return 0;
   49342   if( iDb==1 ) return 1;
   49343   p = db->aDb[iDb].pBt;
   49344   assert( p!=0 );
   49345   return p->sharable==0 || p->locked==1;
   49346 }
   49347 #endif /* NDEBUG */
   49348 
   49349 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
   49350 /*
   49351 ** The following are special cases for mutex enter routines for use
   49352 ** in single threaded applications that use shared cache.  Except for
   49353 ** these two routines, all mutex operations are no-ops in that case and
   49354 ** are null #defines in btree.h.
   49355 **
   49356 ** If shared cache is disabled, then all btree mutex routines, including
   49357 ** the ones below, are no-ops and are null #defines in btree.h.
   49358 */
   49359 
   49360 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   49361   p->pBt->db = p->db;
   49362 }
   49363 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   49364   int i;
   49365   for(i=0; i<db->nDb; i++){
   49366     Btree *p = db->aDb[i].pBt;
   49367     if( p ){
   49368       p->pBt->db = p->db;
   49369     }
   49370   }
   49371 }
   49372 #endif /* if SQLITE_THREADSAFE */
   49373 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   49374 
   49375 /************** End of btmutex.c *********************************************/
   49376 /************** Begin file btree.c *******************************************/
   49377 /*
   49378 ** 2004 April 6
   49379 **
   49380 ** The author disclaims copyright to this source code.  In place of
   49381 ** a legal notice, here is a blessing:
   49382 **
   49383 **    May you do good and not evil.
   49384 **    May you find forgiveness for yourself and forgive others.
   49385 **    May you share freely, never taking more than you give.
   49386 **
   49387 *************************************************************************
   49388 ** This file implements a external (disk-based) database using BTrees.
   49389 ** See the header comment on "btreeInt.h" for additional information.
   49390 ** Including a description of file format and an overview of operation.
   49391 */
   49392 
   49393 /*
   49394 ** The header string that appears at the beginning of every
   49395 ** SQLite database.
   49396 */
   49397 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   49398 
   49399 /*
   49400 ** Set this global variable to 1 to enable tracing using the TRACE
   49401 ** macro.
   49402 */
   49403 #if 0
   49404 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   49405 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   49406 #else
   49407 # define TRACE(X)
   49408 #endif
   49409 
   49410 /*
   49411 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   49412 ** But if the value is zero, make it 65536.
   49413 **
   49414 ** This routine is used to extract the "offset to cell content area" value
   49415 ** from the header of a btree page.  If the page size is 65536 and the page
   49416 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   49417 ** This routine makes the necessary adjustment to 65536.
   49418 */
   49419 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   49420 
   49421 #ifndef SQLITE_OMIT_SHARED_CACHE
   49422 /*
   49423 ** A list of BtShared objects that are eligible for participation
   49424 ** in shared cache.  This variable has file scope during normal builds,
   49425 ** but the test harness needs to access it so we make it global for
   49426 ** test builds.
   49427 **
   49428 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   49429 */
   49430 #ifdef SQLITE_TEST
   49431 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   49432 #else
   49433 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   49434 #endif
   49435 #endif /* SQLITE_OMIT_SHARED_CACHE */
   49436 
   49437 #ifndef SQLITE_OMIT_SHARED_CACHE
   49438 /*
   49439 ** Enable or disable the shared pager and schema features.
   49440 **
   49441 ** This routine has no effect on existing database connections.
   49442 ** The shared cache setting effects only future calls to
   49443 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   49444 */
   49445 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   49446   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   49447   return SQLITE_OK;
   49448 }
   49449 #endif
   49450 
   49451 
   49452 
   49453 #ifdef SQLITE_OMIT_SHARED_CACHE
   49454   /*
   49455   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   49456   ** and clearAllSharedCacheTableLocks()
   49457   ** manipulate entries in the BtShared.pLock linked list used to store
   49458   ** shared-cache table level locks. If the library is compiled with the
   49459   ** shared-cache feature disabled, then there is only ever one user
   49460   ** of each BtShared structure and so this locking is not necessary.
   49461   ** So define the lock related functions as no-ops.
   49462   */
   49463   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   49464   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   49465   #define clearAllSharedCacheTableLocks(a)
   49466   #define downgradeAllSharedCacheTableLocks(a)
   49467   #define hasSharedCacheTableLock(a,b,c,d) 1
   49468   #define hasReadConflicts(a, b) 0
   49469 #endif
   49470 
   49471 #ifndef SQLITE_OMIT_SHARED_CACHE
   49472 
   49473 #ifdef SQLITE_DEBUG
   49474 /*
   49475 **** This function is only used as part of an assert() statement. ***
   49476 **
   49477 ** Check to see if pBtree holds the required locks to read or write to the
   49478 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   49479 **
   49480 ** For example, when writing to a table with root-page iRoot via
   49481 ** Btree connection pBtree:
   49482 **
   49483 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   49484 **
   49485 ** When writing to an index that resides in a sharable database, the
   49486 ** caller should have first obtained a lock specifying the root page of
   49487 ** the corresponding table. This makes things a bit more complicated,
   49488 ** as this module treats each table as a separate structure. To determine
   49489 ** the table corresponding to the index being written, this
   49490 ** function has to search through the database schema.
   49491 **
   49492 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   49493 ** hold a write-lock on the schema table (root page 1). This is also
   49494 ** acceptable.
   49495 */
   49496 static int hasSharedCacheTableLock(
   49497   Btree *pBtree,         /* Handle that must hold lock */
   49498   Pgno iRoot,            /* Root page of b-tree */
   49499   int isIndex,           /* True if iRoot is the root of an index b-tree */
   49500   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   49501 ){
   49502   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   49503   Pgno iTab = 0;
   49504   BtLock *pLock;
   49505 
   49506   /* If this database is not shareable, or if the client is reading
   49507   ** and has the read-uncommitted flag set, then no lock is required.
   49508   ** Return true immediately.
   49509   */
   49510   if( (pBtree->sharable==0)
   49511    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   49512   ){
   49513     return 1;
   49514   }
   49515 
   49516   /* If the client is reading  or writing an index and the schema is
   49517   ** not loaded, then it is too difficult to actually check to see if
   49518   ** the correct locks are held.  So do not bother - just return true.
   49519   ** This case does not come up very often anyhow.
   49520   */
   49521   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
   49522     return 1;
   49523   }
   49524 
   49525   /* Figure out the root-page that the lock should be held on. For table
   49526   ** b-trees, this is just the root page of the b-tree being read or
   49527   ** written. For index b-trees, it is the root page of the associated
   49528   ** table.  */
   49529   if( isIndex ){
   49530     HashElem *p;
   49531     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   49532       Index *pIdx = (Index *)sqliteHashData(p);
   49533       if( pIdx->tnum==(int)iRoot ){
   49534         iTab = pIdx->pTable->tnum;
   49535       }
   49536     }
   49537   }else{
   49538     iTab = iRoot;
   49539   }
   49540 
   49541   /* Search for the required lock. Either a write-lock on root-page iTab, a
   49542   ** write-lock on the schema table, or (if the client is reading) a
   49543   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   49544   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   49545     if( pLock->pBtree==pBtree
   49546      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   49547      && pLock->eLock>=eLockType
   49548     ){
   49549       return 1;
   49550     }
   49551   }
   49552 
   49553   /* Failed to find the required lock. */
   49554   return 0;
   49555 }
   49556 #endif /* SQLITE_DEBUG */
   49557 
   49558 #ifdef SQLITE_DEBUG
   49559 /*
   49560 **** This function may be used as part of assert() statements only. ****
   49561 **
   49562 ** Return true if it would be illegal for pBtree to write into the
   49563 ** table or index rooted at iRoot because other shared connections are
   49564 ** simultaneously reading that same table or index.
   49565 **
   49566 ** It is illegal for pBtree to write if some other Btree object that
   49567 ** shares the same BtShared object is currently reading or writing
   49568 ** the iRoot table.  Except, if the other Btree object has the
   49569 ** read-uncommitted flag set, then it is OK for the other object to
   49570 ** have a read cursor.
   49571 **
   49572 ** For example, before writing to any part of the table or index
   49573 ** rooted at page iRoot, one should call:
   49574 **
   49575 **    assert( !hasReadConflicts(pBtree, iRoot) );
   49576 */
   49577 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   49578   BtCursor *p;
   49579   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   49580     if( p->pgnoRoot==iRoot
   49581      && p->pBtree!=pBtree
   49582      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   49583     ){
   49584       return 1;
   49585     }
   49586   }
   49587   return 0;
   49588 }
   49589 #endif    /* #ifdef SQLITE_DEBUG */
   49590 
   49591 /*
   49592 ** Query to see if Btree handle p may obtain a lock of type eLock
   49593 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   49594 ** SQLITE_OK if the lock may be obtained (by calling
   49595 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   49596 */
   49597 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   49598   BtShared *pBt = p->pBt;
   49599   BtLock *pIter;
   49600 
   49601   assert( sqlite3BtreeHoldsMutex(p) );
   49602   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   49603   assert( p->db!=0 );
   49604   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   49605 
   49606   /* If requesting a write-lock, then the Btree must have an open write
   49607   ** transaction on this file. And, obviously, for this to be so there
   49608   ** must be an open write transaction on the file itself.
   49609   */
   49610   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   49611   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   49612 
   49613   /* This routine is a no-op if the shared-cache is not enabled */
   49614   if( !p->sharable ){
   49615     return SQLITE_OK;
   49616   }
   49617 
   49618   /* If some other connection is holding an exclusive lock, the
   49619   ** requested lock may not be obtained.
   49620   */
   49621   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
   49622     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   49623     return SQLITE_LOCKED_SHAREDCACHE;
   49624   }
   49625 
   49626   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   49627     /* The condition (pIter->eLock!=eLock) in the following if(...)
   49628     ** statement is a simplification of:
   49629     **
   49630     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   49631     **
   49632     ** since we know that if eLock==WRITE_LOCK, then no other connection
   49633     ** may hold a WRITE_LOCK on any table in this file (since there can
   49634     ** only be a single writer).
   49635     */
   49636     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   49637     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   49638     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   49639       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   49640       if( eLock==WRITE_LOCK ){
   49641         assert( p==pBt->pWriter );
   49642         pBt->btsFlags |= BTS_PENDING;
   49643       }
   49644       return SQLITE_LOCKED_SHAREDCACHE;
   49645     }
   49646   }
   49647   return SQLITE_OK;
   49648 }
   49649 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   49650 
   49651 #ifndef SQLITE_OMIT_SHARED_CACHE
   49652 /*
   49653 ** Add a lock on the table with root-page iTable to the shared-btree used
   49654 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   49655 ** WRITE_LOCK.
   49656 **
   49657 ** This function assumes the following:
   49658 **
   49659 **   (a) The specified Btree object p is connected to a sharable
   49660 **       database (one with the BtShared.sharable flag set), and
   49661 **
   49662 **   (b) No other Btree objects hold a lock that conflicts
   49663 **       with the requested lock (i.e. querySharedCacheTableLock() has
   49664 **       already been called and returned SQLITE_OK).
   49665 **
   49666 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   49667 ** is returned if a malloc attempt fails.
   49668 */
   49669 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   49670   BtShared *pBt = p->pBt;
   49671   BtLock *pLock = 0;
   49672   BtLock *pIter;
   49673 
   49674   assert( sqlite3BtreeHoldsMutex(p) );
   49675   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   49676   assert( p->db!=0 );
   49677 
   49678   /* A connection with the read-uncommitted flag set will never try to
   49679   ** obtain a read-lock using this function. The only read-lock obtained
   49680   ** by a connection in read-uncommitted mode is on the sqlite_master
   49681   ** table, and that lock is obtained in BtreeBeginTrans().  */
   49682   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   49683 
   49684   /* This function should only be called on a sharable b-tree after it
   49685   ** has been determined that no other b-tree holds a conflicting lock.  */
   49686   assert( p->sharable );
   49687   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   49688 
   49689   /* First search the list for an existing lock on this table. */
   49690   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   49691     if( pIter->iTable==iTable && pIter->pBtree==p ){
   49692       pLock = pIter;
   49693       break;
   49694     }
   49695   }
   49696 
   49697   /* If the above search did not find a BtLock struct associating Btree p
   49698   ** with table iTable, allocate one and link it into the list.
   49699   */
   49700   if( !pLock ){
   49701     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   49702     if( !pLock ){
   49703       return SQLITE_NOMEM;
   49704     }
   49705     pLock->iTable = iTable;
   49706     pLock->pBtree = p;
   49707     pLock->pNext = pBt->pLock;
   49708     pBt->pLock = pLock;
   49709   }
   49710 
   49711   /* Set the BtLock.eLock variable to the maximum of the current lock
   49712   ** and the requested lock. This means if a write-lock was already held
   49713   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   49714   */
   49715   assert( WRITE_LOCK>READ_LOCK );
   49716   if( eLock>pLock->eLock ){
   49717     pLock->eLock = eLock;
   49718   }
   49719 
   49720   return SQLITE_OK;
   49721 }
   49722 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   49723 
   49724 #ifndef SQLITE_OMIT_SHARED_CACHE
   49725 /*
   49726 ** Release all the table locks (locks obtained via calls to
   49727 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   49728 **
   49729 ** This function assumes that Btree p has an open read or write
   49730 ** transaction. If it does not, then the BTS_PENDING flag
   49731 ** may be incorrectly cleared.
   49732 */
   49733 static void clearAllSharedCacheTableLocks(Btree *p){
   49734   BtShared *pBt = p->pBt;
   49735   BtLock **ppIter = &pBt->pLock;
   49736 
   49737   assert( sqlite3BtreeHoldsMutex(p) );
   49738   assert( p->sharable || 0==*ppIter );
   49739   assert( p->inTrans>0 );
   49740 
   49741   while( *ppIter ){
   49742     BtLock *pLock = *ppIter;
   49743     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
   49744     assert( pLock->pBtree->inTrans>=pLock->eLock );
   49745     if( pLock->pBtree==p ){
   49746       *ppIter = pLock->pNext;
   49747       assert( pLock->iTable!=1 || pLock==&p->lock );
   49748       if( pLock->iTable!=1 ){
   49749         sqlite3_free(pLock);
   49750       }
   49751     }else{
   49752       ppIter = &pLock->pNext;
   49753     }
   49754   }
   49755 
   49756   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
   49757   if( pBt->pWriter==p ){
   49758     pBt->pWriter = 0;
   49759     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   49760   }else if( pBt->nTransaction==2 ){
   49761     /* This function is called when Btree p is concluding its
   49762     ** transaction. If there currently exists a writer, and p is not
   49763     ** that writer, then the number of locks held by connections other
   49764     ** than the writer must be about to drop to zero. In this case
   49765     ** set the BTS_PENDING flag to 0.
   49766     **
   49767     ** If there is not currently a writer, then BTS_PENDING must
   49768     ** be zero already. So this next line is harmless in that case.
   49769     */
   49770     pBt->btsFlags &= ~BTS_PENDING;
   49771   }
   49772 }
   49773 
   49774 /*
   49775 ** This function changes all write-locks held by Btree p into read-locks.
   49776 */
   49777 static void downgradeAllSharedCacheTableLocks(Btree *p){
   49778   BtShared *pBt = p->pBt;
   49779   if( pBt->pWriter==p ){
   49780     BtLock *pLock;
   49781     pBt->pWriter = 0;
   49782     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   49783     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   49784       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   49785       pLock->eLock = READ_LOCK;
   49786     }
   49787   }
   49788 }
   49789 
   49790 #endif /* SQLITE_OMIT_SHARED_CACHE */
   49791 
   49792 static void releasePage(MemPage *pPage);  /* Forward reference */
   49793 
   49794 /*
   49795 ***** This routine is used inside of assert() only ****
   49796 **
   49797 ** Verify that the cursor holds the mutex on its BtShared
   49798 */
   49799 #ifdef SQLITE_DEBUG
   49800 static int cursorHoldsMutex(BtCursor *p){
   49801   return sqlite3_mutex_held(p->pBt->mutex);
   49802 }
   49803 #endif
   49804 
   49805 
   49806 #ifndef SQLITE_OMIT_INCRBLOB
   49807 /*
   49808 ** Invalidate the overflow page-list cache for cursor pCur, if any.
   49809 */
   49810 static void invalidateOverflowCache(BtCursor *pCur){
   49811   assert( cursorHoldsMutex(pCur) );
   49812   sqlite3_free(pCur->aOverflow);
   49813   pCur->aOverflow = 0;
   49814 }
   49815 
   49816 /*
   49817 ** Invalidate the overflow page-list cache for all cursors opened
   49818 ** on the shared btree structure pBt.
   49819 */
   49820 static void invalidateAllOverflowCache(BtShared *pBt){
   49821   BtCursor *p;
   49822   assert( sqlite3_mutex_held(pBt->mutex) );
   49823   for(p=pBt->pCursor; p; p=p->pNext){
   49824     invalidateOverflowCache(p);
   49825   }
   49826 }
   49827 
   49828 /*
   49829 ** This function is called before modifying the contents of a table
   49830 ** to invalidate any incrblob cursors that are open on the
   49831 ** row or one of the rows being modified.
   49832 **
   49833 ** If argument isClearTable is true, then the entire contents of the
   49834 ** table is about to be deleted. In this case invalidate all incrblob
   49835 ** cursors open on any row within the table with root-page pgnoRoot.
   49836 **
   49837 ** Otherwise, if argument isClearTable is false, then the row with
   49838 ** rowid iRow is being replaced or deleted. In this case invalidate
   49839 ** only those incrblob cursors open on that specific row.
   49840 */
   49841 static void invalidateIncrblobCursors(
   49842   Btree *pBtree,          /* The database file to check */
   49843   i64 iRow,               /* The rowid that might be changing */
   49844   int isClearTable        /* True if all rows are being deleted */
   49845 ){
   49846   BtCursor *p;
   49847   BtShared *pBt = pBtree->pBt;
   49848   assert( sqlite3BtreeHoldsMutex(pBtree) );
   49849   for(p=pBt->pCursor; p; p=p->pNext){
   49850     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
   49851       p->eState = CURSOR_INVALID;
   49852     }
   49853   }
   49854 }
   49855 
   49856 #else
   49857   /* Stub functions when INCRBLOB is omitted */
   49858   #define invalidateOverflowCache(x)
   49859   #define invalidateAllOverflowCache(x)
   49860   #define invalidateIncrblobCursors(x,y,z)
   49861 #endif /* SQLITE_OMIT_INCRBLOB */
   49862 
   49863 /*
   49864 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   49865 ** when a page that previously contained data becomes a free-list leaf
   49866 ** page.
   49867 **
   49868 ** The BtShared.pHasContent bitvec exists to work around an obscure
   49869 ** bug caused by the interaction of two useful IO optimizations surrounding
   49870 ** free-list leaf pages:
   49871 **
   49872 **   1) When all data is deleted from a page and the page becomes
   49873 **      a free-list leaf page, the page is not written to the database
   49874 **      (as free-list leaf pages contain no meaningful data). Sometimes
   49875 **      such a page is not even journalled (as it will not be modified,
   49876 **      why bother journalling it?).
   49877 **
   49878 **   2) When a free-list leaf page is reused, its content is not read
   49879 **      from the database or written to the journal file (why should it
   49880 **      be, if it is not at all meaningful?).
   49881 **
   49882 ** By themselves, these optimizations work fine and provide a handy
   49883 ** performance boost to bulk delete or insert operations. However, if
   49884 ** a page is moved to the free-list and then reused within the same
   49885 ** transaction, a problem comes up. If the page is not journalled when
   49886 ** it is moved to the free-list and it is also not journalled when it
   49887 ** is extracted from the free-list and reused, then the original data
   49888 ** may be lost. In the event of a rollback, it may not be possible
   49889 ** to restore the database to its original configuration.
   49890 **
   49891 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   49892 ** moved to become a free-list leaf page, the corresponding bit is
   49893 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   49894 ** optimization 2 above is omitted if the corresponding bit is already
   49895 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   49896 ** at the end of every transaction.
   49897 */
   49898 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   49899   int rc = SQLITE_OK;
   49900   if( !pBt->pHasContent ){
   49901     assert( pgno<=pBt->nPage );
   49902     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   49903     if( !pBt->pHasContent ){
   49904       rc = SQLITE_NOMEM;
   49905     }
   49906   }
   49907   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   49908     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   49909   }
   49910   return rc;
   49911 }
   49912 
   49913 /*
   49914 ** Query the BtShared.pHasContent vector.
   49915 **
   49916 ** This function is called when a free-list leaf page is removed from the
   49917 ** free-list for reuse. It returns false if it is safe to retrieve the
   49918 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   49919 */
   49920 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   49921   Bitvec *p = pBt->pHasContent;
   49922   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   49923 }
   49924 
   49925 /*
   49926 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   49927 ** invoked at the conclusion of each write-transaction.
   49928 */
   49929 static void btreeClearHasContent(BtShared *pBt){
   49930   sqlite3BitvecDestroy(pBt->pHasContent);
   49931   pBt->pHasContent = 0;
   49932 }
   49933 
   49934 /*
   49935 ** Save the current cursor position in the variables BtCursor.nKey
   49936 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   49937 **
   49938 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   49939 ** prior to calling this routine.
   49940 */
   49941 static int saveCursorPosition(BtCursor *pCur){
   49942   int rc;
   49943 
   49944   assert( CURSOR_VALID==pCur->eState );
   49945   assert( 0==pCur->pKey );
   49946   assert( cursorHoldsMutex(pCur) );
   49947 
   49948   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   49949   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   49950 
   49951   /* If this is an intKey table, then the above call to BtreeKeySize()
   49952   ** stores the integer key in pCur->nKey. In this case this value is
   49953   ** all that is required. Otherwise, if pCur is not open on an intKey
   49954   ** table, then malloc space for and store the pCur->nKey bytes of key
   49955   ** data.
   49956   */
   49957   if( 0==pCur->apPage[0]->intKey ){
   49958     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   49959     if( pKey ){
   49960       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   49961       if( rc==SQLITE_OK ){
   49962         pCur->pKey = pKey;
   49963       }else{
   49964         sqlite3_free(pKey);
   49965       }
   49966     }else{
   49967       rc = SQLITE_NOMEM;
   49968     }
   49969   }
   49970   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   49971 
   49972   if( rc==SQLITE_OK ){
   49973     int i;
   49974     for(i=0; i<=pCur->iPage; i++){
   49975       releasePage(pCur->apPage[i]);
   49976       pCur->apPage[i] = 0;
   49977     }
   49978     pCur->iPage = -1;
   49979     pCur->eState = CURSOR_REQUIRESEEK;
   49980   }
   49981 
   49982   invalidateOverflowCache(pCur);
   49983   return rc;
   49984 }
   49985 
   49986 /*
   49987 ** Save the positions of all cursors (except pExcept) that are open on
   49988 ** the table  with root-page iRoot. Usually, this is called just before cursor
   49989 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   49990 */
   49991 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   49992   BtCursor *p;
   49993   assert( sqlite3_mutex_held(pBt->mutex) );
   49994   assert( pExcept==0 || pExcept->pBt==pBt );
   49995   for(p=pBt->pCursor; p; p=p->pNext){
   49996     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
   49997         p->eState==CURSOR_VALID ){
   49998       int rc = saveCursorPosition(p);
   49999       if( SQLITE_OK!=rc ){
   50000         return rc;
   50001       }
   50002     }
   50003   }
   50004   return SQLITE_OK;
   50005 }
   50006 
   50007 /*
   50008 ** Clear the current cursor position.
   50009 */
   50010 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   50011   assert( cursorHoldsMutex(pCur) );
   50012   sqlite3_free(pCur->pKey);
   50013   pCur->pKey = 0;
   50014   pCur->eState = CURSOR_INVALID;
   50015 }
   50016 
   50017 /*
   50018 ** In this version of BtreeMoveto, pKey is a packed index record
   50019 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   50020 ** record and then call BtreeMovetoUnpacked() to do the work.
   50021 */
   50022 static int btreeMoveto(
   50023   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   50024   const void *pKey,   /* Packed key if the btree is an index */
   50025   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   50026   int bias,           /* Bias search to the high end */
   50027   int *pRes           /* Write search results here */
   50028 ){
   50029   int rc;                    /* Status code */
   50030   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   50031   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
   50032   char *pFree = 0;
   50033 
   50034   if( pKey ){
   50035     assert( nKey==(i64)(int)nKey );
   50036     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   50037         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
   50038     );
   50039     if( pIdxKey==0 ) return SQLITE_NOMEM;
   50040     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
   50041   }else{
   50042     pIdxKey = 0;
   50043   }
   50044   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   50045   if( pFree ){
   50046     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
   50047   }
   50048   return rc;
   50049 }
   50050 
   50051 /*
   50052 ** Restore the cursor to the position it was in (or as close to as possible)
   50053 ** when saveCursorPosition() was called. Note that this call deletes the
   50054 ** saved position info stored by saveCursorPosition(), so there can be
   50055 ** at most one effective restoreCursorPosition() call after each
   50056 ** saveCursorPosition().
   50057 */
   50058 static int btreeRestoreCursorPosition(BtCursor *pCur){
   50059   int rc;
   50060   assert( cursorHoldsMutex(pCur) );
   50061   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   50062   if( pCur->eState==CURSOR_FAULT ){
   50063     return pCur->skipNext;
   50064   }
   50065   pCur->eState = CURSOR_INVALID;
   50066   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   50067   if( rc==SQLITE_OK ){
   50068     sqlite3_free(pCur->pKey);
   50069     pCur->pKey = 0;
   50070     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   50071   }
   50072   return rc;
   50073 }
   50074 
   50075 #define restoreCursorPosition(p) \
   50076   (p->eState>=CURSOR_REQUIRESEEK ? \
   50077          btreeRestoreCursorPosition(p) : \
   50078          SQLITE_OK)
   50079 
   50080 /*
   50081 ** Determine whether or not a cursor has moved from the position it
   50082 ** was last placed at.  Cursors can move when the row they are pointing
   50083 ** at is deleted out from under them.
   50084 **
   50085 ** This routine returns an error code if something goes wrong.  The
   50086 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
   50087 */
   50088 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   50089   int rc;
   50090 
   50091   rc = restoreCursorPosition(pCur);
   50092   if( rc ){
   50093     *pHasMoved = 1;
   50094     return rc;
   50095   }
   50096   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
   50097     *pHasMoved = 1;
   50098   }else{
   50099     *pHasMoved = 0;
   50100   }
   50101   return SQLITE_OK;
   50102 }
   50103 
   50104 #ifndef SQLITE_OMIT_AUTOVACUUM
   50105 /*
   50106 ** Given a page number of a regular database page, return the page
   50107 ** number for the pointer-map page that contains the entry for the
   50108 ** input page number.
   50109 **
   50110 ** Return 0 (not a valid page) for pgno==1 since there is
   50111 ** no pointer map associated with page 1.  The integrity_check logic
   50112 ** requires that ptrmapPageno(*,1)!=1.
   50113 */
   50114 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   50115   int nPagesPerMapPage;
   50116   Pgno iPtrMap, ret;
   50117   assert( sqlite3_mutex_held(pBt->mutex) );
   50118   if( pgno<2 ) return 0;
   50119   nPagesPerMapPage = (pBt->usableSize/5)+1;
   50120   iPtrMap = (pgno-2)/nPagesPerMapPage;
   50121   ret = (iPtrMap*nPagesPerMapPage) + 2;
   50122   if( ret==PENDING_BYTE_PAGE(pBt) ){
   50123     ret++;
   50124   }
   50125   return ret;
   50126 }
   50127 
   50128 /*
   50129 ** Write an entry into the pointer map.
   50130 **
   50131 ** This routine updates the pointer map entry for page number 'key'
   50132 ** so that it maps to type 'eType' and parent page number 'pgno'.
   50133 **
   50134 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   50135 ** a no-op.  If an error occurs, the appropriate error code is written
   50136 ** into *pRC.
   50137 */
   50138 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   50139   DbPage *pDbPage;  /* The pointer map page */
   50140   u8 *pPtrmap;      /* The pointer map data */
   50141   Pgno iPtrmap;     /* The pointer map page number */
   50142   int offset;       /* Offset in pointer map page */
   50143   int rc;           /* Return code from subfunctions */
   50144 
   50145   if( *pRC ) return;
   50146 
   50147   assert( sqlite3_mutex_held(pBt->mutex) );
   50148   /* The master-journal page number must never be used as a pointer map page */
   50149   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   50150 
   50151   assert( pBt->autoVacuum );
   50152   if( key==0 ){
   50153     *pRC = SQLITE_CORRUPT_BKPT;
   50154     return;
   50155   }
   50156   iPtrmap = PTRMAP_PAGENO(pBt, key);
   50157   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   50158   if( rc!=SQLITE_OK ){
   50159     *pRC = rc;
   50160     return;
   50161   }
   50162   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   50163   if( offset<0 ){
   50164     *pRC = SQLITE_CORRUPT_BKPT;
   50165     goto ptrmap_exit;
   50166   }
   50167   assert( offset <= (int)pBt->usableSize-5 );
   50168   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   50169 
   50170   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   50171     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   50172     *pRC= rc = sqlite3PagerWrite(pDbPage);
   50173     if( rc==SQLITE_OK ){
   50174       pPtrmap[offset] = eType;
   50175       put4byte(&pPtrmap[offset+1], parent);
   50176     }
   50177   }
   50178 
   50179 ptrmap_exit:
   50180   sqlite3PagerUnref(pDbPage);
   50181 }
   50182 
   50183 /*
   50184 ** Read an entry from the pointer map.
   50185 **
   50186 ** This routine retrieves the pointer map entry for page 'key', writing
   50187 ** the type and parent page number to *pEType and *pPgno respectively.
   50188 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   50189 */
   50190 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   50191   DbPage *pDbPage;   /* The pointer map page */
   50192   int iPtrmap;       /* Pointer map page index */
   50193   u8 *pPtrmap;       /* Pointer map page data */
   50194   int offset;        /* Offset of entry in pointer map */
   50195   int rc;
   50196 
   50197   assert( sqlite3_mutex_held(pBt->mutex) );
   50198 
   50199   iPtrmap = PTRMAP_PAGENO(pBt, key);
   50200   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   50201   if( rc!=0 ){
   50202     return rc;
   50203   }
   50204   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   50205 
   50206   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   50207   if( offset<0 ){
   50208     sqlite3PagerUnref(pDbPage);
   50209     return SQLITE_CORRUPT_BKPT;
   50210   }
   50211   assert( offset <= (int)pBt->usableSize-5 );
   50212   assert( pEType!=0 );
   50213   *pEType = pPtrmap[offset];
   50214   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   50215 
   50216   sqlite3PagerUnref(pDbPage);
   50217   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   50218   return SQLITE_OK;
   50219 }
   50220 
   50221 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   50222   #define ptrmapPut(w,x,y,z,rc)
   50223   #define ptrmapGet(w,x,y,z) SQLITE_OK
   50224   #define ptrmapPutOvflPtr(x, y, rc)
   50225 #endif
   50226 
   50227 /*
   50228 ** Given a btree page and a cell index (0 means the first cell on
   50229 ** the page, 1 means the second cell, and so forth) return a pointer
   50230 ** to the cell content.
   50231 **
   50232 ** This routine works only for pages that do not contain overflow cells.
   50233 */
   50234 #define findCell(P,I) \
   50235   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
   50236 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
   50237 
   50238 
   50239 /*
   50240 ** This a more complex version of findCell() that works for
   50241 ** pages that do contain overflow cells.
   50242 */
   50243 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   50244   int i;
   50245   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50246   for(i=pPage->nOverflow-1; i>=0; i--){
   50247     int k;
   50248     k = pPage->aiOvfl[i];
   50249     if( k<=iCell ){
   50250       if( k==iCell ){
   50251         return pPage->apOvfl[i];
   50252       }
   50253       iCell--;
   50254     }
   50255   }
   50256   return findCell(pPage, iCell);
   50257 }
   50258 
   50259 /*
   50260 ** Parse a cell content block and fill in the CellInfo structure.  There
   50261 ** are two versions of this function.  btreeParseCell() takes a
   50262 ** cell index as the second argument and btreeParseCellPtr()
   50263 ** takes a pointer to the body of the cell as its second argument.
   50264 **
   50265 ** Within this file, the parseCell() macro can be called instead of
   50266 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   50267 */
   50268 static void btreeParseCellPtr(
   50269   MemPage *pPage,         /* Page containing the cell */
   50270   u8 *pCell,              /* Pointer to the cell text. */
   50271   CellInfo *pInfo         /* Fill in this structure */
   50272 ){
   50273   u16 n;                  /* Number bytes in cell content header */
   50274   u32 nPayload;           /* Number of bytes of cell payload */
   50275 
   50276   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50277 
   50278   pInfo->pCell = pCell;
   50279   assert( pPage->leaf==0 || pPage->leaf==1 );
   50280   n = pPage->childPtrSize;
   50281   assert( n==4-4*pPage->leaf );
   50282   if( pPage->intKey ){
   50283     if( pPage->hasData ){
   50284       n += getVarint32(&pCell[n], nPayload);
   50285     }else{
   50286       nPayload = 0;
   50287     }
   50288     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   50289     pInfo->nData = nPayload;
   50290   }else{
   50291     pInfo->nData = 0;
   50292     n += getVarint32(&pCell[n], nPayload);
   50293     pInfo->nKey = nPayload;
   50294   }
   50295   pInfo->nPayload = nPayload;
   50296   pInfo->nHeader = n;
   50297   testcase( nPayload==pPage->maxLocal );
   50298   testcase( nPayload==pPage->maxLocal+1 );
   50299   if( likely(nPayload<=pPage->maxLocal) ){
   50300     /* This is the (easy) common case where the entire payload fits
   50301     ** on the local page.  No overflow is required.
   50302     */
   50303     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
   50304     pInfo->nLocal = (u16)nPayload;
   50305     pInfo->iOverflow = 0;
   50306   }else{
   50307     /* If the payload will not fit completely on the local page, we have
   50308     ** to decide how much to store locally and how much to spill onto
   50309     ** overflow pages.  The strategy is to minimize the amount of unused
   50310     ** space on overflow pages while keeping the amount of local storage
   50311     ** in between minLocal and maxLocal.
   50312     **
   50313     ** Warning:  changing the way overflow payload is distributed in any
   50314     ** way will result in an incompatible file format.
   50315     */
   50316     int minLocal;  /* Minimum amount of payload held locally */
   50317     int maxLocal;  /* Maximum amount of payload held locally */
   50318     int surplus;   /* Overflow payload available for local storage */
   50319 
   50320     minLocal = pPage->minLocal;
   50321     maxLocal = pPage->maxLocal;
   50322     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   50323     testcase( surplus==maxLocal );
   50324     testcase( surplus==maxLocal+1 );
   50325     if( surplus <= maxLocal ){
   50326       pInfo->nLocal = (u16)surplus;
   50327     }else{
   50328       pInfo->nLocal = (u16)minLocal;
   50329     }
   50330     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   50331     pInfo->nSize = pInfo->iOverflow + 4;
   50332   }
   50333 }
   50334 #define parseCell(pPage, iCell, pInfo) \
   50335   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   50336 static void btreeParseCell(
   50337   MemPage *pPage,         /* Page containing the cell */
   50338   int iCell,              /* The cell index.  First cell is 0 */
   50339   CellInfo *pInfo         /* Fill in this structure */
   50340 ){
   50341   parseCell(pPage, iCell, pInfo);
   50342 }
   50343 
   50344 /*
   50345 ** Compute the total number of bytes that a Cell needs in the cell
   50346 ** data area of the btree-page.  The return number includes the cell
   50347 ** data header and the local payload, but not any overflow page or
   50348 ** the space used by the cell pointer.
   50349 */
   50350 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   50351   u8 *pIter = &pCell[pPage->childPtrSize];
   50352   u32 nSize;
   50353 
   50354 #ifdef SQLITE_DEBUG
   50355   /* The value returned by this function should always be the same as
   50356   ** the (CellInfo.nSize) value found by doing a full parse of the
   50357   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   50358   ** this function verifies that this invariant is not violated. */
   50359   CellInfo debuginfo;
   50360   btreeParseCellPtr(pPage, pCell, &debuginfo);
   50361 #endif
   50362 
   50363   if( pPage->intKey ){
   50364     u8 *pEnd;
   50365     if( pPage->hasData ){
   50366       pIter += getVarint32(pIter, nSize);
   50367     }else{
   50368       nSize = 0;
   50369     }
   50370 
   50371     /* pIter now points at the 64-bit integer key value, a variable length
   50372     ** integer. The following block moves pIter to point at the first byte
   50373     ** past the end of the key value. */
   50374     pEnd = &pIter[9];
   50375     while( (*pIter++)&0x80 && pIter<pEnd );
   50376   }else{
   50377     pIter += getVarint32(pIter, nSize);
   50378   }
   50379 
   50380   testcase( nSize==pPage->maxLocal );
   50381   testcase( nSize==pPage->maxLocal+1 );
   50382   if( nSize>pPage->maxLocal ){
   50383     int minLocal = pPage->minLocal;
   50384     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   50385     testcase( nSize==pPage->maxLocal );
   50386     testcase( nSize==pPage->maxLocal+1 );
   50387     if( nSize>pPage->maxLocal ){
   50388       nSize = minLocal;
   50389     }
   50390     nSize += 4;
   50391   }
   50392   nSize += (u32)(pIter - pCell);
   50393 
   50394   /* The minimum size of any cell is 4 bytes. */
   50395   if( nSize<4 ){
   50396     nSize = 4;
   50397   }
   50398 
   50399   assert( nSize==debuginfo.nSize );
   50400   return (u16)nSize;
   50401 }
   50402 
   50403 #ifdef SQLITE_DEBUG
   50404 /* This variation on cellSizePtr() is used inside of assert() statements
   50405 ** only. */
   50406 static u16 cellSize(MemPage *pPage, int iCell){
   50407   return cellSizePtr(pPage, findCell(pPage, iCell));
   50408 }
   50409 #endif
   50410 
   50411 #ifndef SQLITE_OMIT_AUTOVACUUM
   50412 /*
   50413 ** If the cell pCell, part of page pPage contains a pointer
   50414 ** to an overflow page, insert an entry into the pointer-map
   50415 ** for the overflow page.
   50416 */
   50417 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   50418   CellInfo info;
   50419   if( *pRC ) return;
   50420   assert( pCell!=0 );
   50421   btreeParseCellPtr(pPage, pCell, &info);
   50422   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   50423   if( info.iOverflow ){
   50424     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   50425     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   50426   }
   50427 }
   50428 #endif
   50429 
   50430 
   50431 /*
   50432 ** Defragment the page given.  All Cells are moved to the
   50433 ** end of the page and all free space is collected into one
   50434 ** big FreeBlk that occurs in between the header and cell
   50435 ** pointer array and the cell content area.
   50436 */
   50437 static int defragmentPage(MemPage *pPage){
   50438   int i;                     /* Loop counter */
   50439   int pc;                    /* Address of a i-th cell */
   50440   int hdr;                   /* Offset to the page header */
   50441   int size;                  /* Size of a cell */
   50442   int usableSize;            /* Number of usable bytes on a page */
   50443   int cellOffset;            /* Offset to the cell pointer array */
   50444   int cbrk;                  /* Offset to the cell content area */
   50445   int nCell;                 /* Number of cells on the page */
   50446   unsigned char *data;       /* The page data */
   50447   unsigned char *temp;       /* Temp area for cell content */
   50448   int iCellFirst;            /* First allowable cell index */
   50449   int iCellLast;             /* Last possible cell index */
   50450 
   50451 
   50452   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50453   assert( pPage->pBt!=0 );
   50454   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   50455   assert( pPage->nOverflow==0 );
   50456   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50457   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   50458   data = pPage->aData;
   50459   hdr = pPage->hdrOffset;
   50460   cellOffset = pPage->cellOffset;
   50461   nCell = pPage->nCell;
   50462   assert( nCell==get2byte(&data[hdr+3]) );
   50463   usableSize = pPage->pBt->usableSize;
   50464   cbrk = get2byte(&data[hdr+5]);
   50465   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   50466   cbrk = usableSize;
   50467   iCellFirst = cellOffset + 2*nCell;
   50468   iCellLast = usableSize - 4;
   50469   for(i=0; i<nCell; i++){
   50470     u8 *pAddr;     /* The i-th cell pointer */
   50471     pAddr = &data[cellOffset + i*2];
   50472     pc = get2byte(pAddr);
   50473     testcase( pc==iCellFirst );
   50474     testcase( pc==iCellLast );
   50475 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50476     /* These conditions have already been verified in btreeInitPage()
   50477     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   50478     */
   50479     if( pc<iCellFirst || pc>iCellLast ){
   50480       return SQLITE_CORRUPT_BKPT;
   50481     }
   50482 #endif
   50483     assert( pc>=iCellFirst && pc<=iCellLast );
   50484     size = cellSizePtr(pPage, &temp[pc]);
   50485     cbrk -= size;
   50486 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50487     if( cbrk<iCellFirst ){
   50488       return SQLITE_CORRUPT_BKPT;
   50489     }
   50490 #else
   50491     if( cbrk<iCellFirst || pc+size>usableSize ){
   50492       return SQLITE_CORRUPT_BKPT;
   50493     }
   50494 #endif
   50495     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   50496     testcase( cbrk+size==usableSize );
   50497     testcase( pc+size==usableSize );
   50498     memcpy(&data[cbrk], &temp[pc], size);
   50499     put2byte(pAddr, cbrk);
   50500   }
   50501   assert( cbrk>=iCellFirst );
   50502   put2byte(&data[hdr+5], cbrk);
   50503   data[hdr+1] = 0;
   50504   data[hdr+2] = 0;
   50505   data[hdr+7] = 0;
   50506   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   50507   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50508   if( cbrk-iCellFirst!=pPage->nFree ){
   50509     return SQLITE_CORRUPT_BKPT;
   50510   }
   50511   return SQLITE_OK;
   50512 }
   50513 
   50514 /*
   50515 ** Allocate nByte bytes of space from within the B-Tree page passed
   50516 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   50517 ** of the first byte of allocated space. Return either SQLITE_OK or
   50518 ** an error code (usually SQLITE_CORRUPT).
   50519 **
   50520 ** The caller guarantees that there is sufficient space to make the
   50521 ** allocation.  This routine might need to defragment in order to bring
   50522 ** all the space together, however.  This routine will avoid using
   50523 ** the first two bytes past the cell pointer area since presumably this
   50524 ** allocation is being made in order to insert a new cell, so we will
   50525 ** also end up needing a new cell pointer.
   50526 */
   50527 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   50528   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   50529   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   50530   int nFrag;                           /* Number of fragmented bytes on pPage */
   50531   int top;                             /* First byte of cell content area */
   50532   int gap;        /* First byte of gap between cell pointers and cell content */
   50533   int rc;         /* Integer return code */
   50534   int usableSize; /* Usable size of the page */
   50535 
   50536   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50537   assert( pPage->pBt );
   50538   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50539   assert( nByte>=0 );  /* Minimum cell size is 4 */
   50540   assert( pPage->nFree>=nByte );
   50541   assert( pPage->nOverflow==0 );
   50542   usableSize = pPage->pBt->usableSize;
   50543   assert( nByte < usableSize-8 );
   50544 
   50545   nFrag = data[hdr+7];
   50546   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   50547   gap = pPage->cellOffset + 2*pPage->nCell;
   50548   top = get2byteNotZero(&data[hdr+5]);
   50549   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   50550   testcase( gap+2==top );
   50551   testcase( gap+1==top );
   50552   testcase( gap==top );
   50553 
   50554   if( nFrag>=60 ){
   50555     /* Always defragment highly fragmented pages */
   50556     rc = defragmentPage(pPage);
   50557     if( rc ) return rc;
   50558     top = get2byteNotZero(&data[hdr+5]);
   50559   }else if( gap+2<=top ){
   50560     /* Search the freelist looking for a free slot big enough to satisfy
   50561     ** the request. The allocation is made from the first free slot in
   50562     ** the list that is large enough to accomadate it.
   50563     */
   50564     int pc, addr;
   50565     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   50566       int size;            /* Size of the free slot */
   50567       if( pc>usableSize-4 || pc<addr+4 ){
   50568         return SQLITE_CORRUPT_BKPT;
   50569       }
   50570       size = get2byte(&data[pc+2]);
   50571       if( size>=nByte ){
   50572         int x = size - nByte;
   50573         testcase( x==4 );
   50574         testcase( x==3 );
   50575         if( x<4 ){
   50576           /* Remove the slot from the free-list. Update the number of
   50577           ** fragmented bytes within the page. */
   50578           memcpy(&data[addr], &data[pc], 2);
   50579           data[hdr+7] = (u8)(nFrag + x);
   50580         }else if( size+pc > usableSize ){
   50581           return SQLITE_CORRUPT_BKPT;
   50582         }else{
   50583           /* The slot remains on the free-list. Reduce its size to account
   50584           ** for the portion used by the new allocation. */
   50585           put2byte(&data[pc+2], x);
   50586         }
   50587         *pIdx = pc + x;
   50588         return SQLITE_OK;
   50589       }
   50590     }
   50591   }
   50592 
   50593   /* Check to make sure there is enough space in the gap to satisfy
   50594   ** the allocation.  If not, defragment.
   50595   */
   50596   testcase( gap+2+nByte==top );
   50597   if( gap+2+nByte>top ){
   50598     rc = defragmentPage(pPage);
   50599     if( rc ) return rc;
   50600     top = get2byteNotZero(&data[hdr+5]);
   50601     assert( gap+nByte<=top );
   50602   }
   50603 
   50604 
   50605   /* Allocate memory from the gap in between the cell pointer array
   50606   ** and the cell content area.  The btreeInitPage() call has already
   50607   ** validated the freelist.  Given that the freelist is valid, there
   50608   ** is no way that the allocation can extend off the end of the page.
   50609   ** The assert() below verifies the previous sentence.
   50610   */
   50611   top -= nByte;
   50612   put2byte(&data[hdr+5], top);
   50613   assert( top+nByte <= (int)pPage->pBt->usableSize );
   50614   *pIdx = top;
   50615   return SQLITE_OK;
   50616 }
   50617 
   50618 /*
   50619 ** Return a section of the pPage->aData to the freelist.
   50620 ** The first byte of the new free block is pPage->aDisk[start]
   50621 ** and the size of the block is "size" bytes.
   50622 **
   50623 ** Most of the effort here is involved in coalesing adjacent
   50624 ** free blocks into a single big free block.
   50625 */
   50626 static int freeSpace(MemPage *pPage, int start, int size){
   50627   int addr, pbegin, hdr;
   50628   int iLast;                        /* Largest possible freeblock offset */
   50629   unsigned char *data = pPage->aData;
   50630 
   50631   assert( pPage->pBt!=0 );
   50632   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50633   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   50634   assert( (start + size) <= (int)pPage->pBt->usableSize );
   50635   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50636   assert( size>=0 );   /* Minimum cell size is 4 */
   50637 
   50638   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
   50639     /* Overwrite deleted information with zeros when the secure_delete
   50640     ** option is enabled */
   50641     memset(&data[start], 0, size);
   50642   }
   50643 
   50644   /* Add the space back into the linked list of freeblocks.  Note that
   50645   ** even though the freeblock list was checked by btreeInitPage(),
   50646   ** btreeInitPage() did not detect overlapping cells or
   50647   ** freeblocks that overlapped cells.   Nor does it detect when the
   50648   ** cell content area exceeds the value in the page header.  If these
   50649   ** situations arise, then subsequent insert operations might corrupt
   50650   ** the freelist.  So we do need to check for corruption while scanning
   50651   ** the freelist.
   50652   */
   50653   hdr = pPage->hdrOffset;
   50654   addr = hdr + 1;
   50655   iLast = pPage->pBt->usableSize - 4;
   50656   assert( start<=iLast );
   50657   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   50658     if( pbegin<addr+4 ){
   50659       return SQLITE_CORRUPT_BKPT;
   50660     }
   50661     addr = pbegin;
   50662   }
   50663   if( pbegin>iLast ){
   50664     return SQLITE_CORRUPT_BKPT;
   50665   }
   50666   assert( pbegin>addr || pbegin==0 );
   50667   put2byte(&data[addr], start);
   50668   put2byte(&data[start], pbegin);
   50669   put2byte(&data[start+2], size);
   50670   pPage->nFree = pPage->nFree + (u16)size;
   50671 
   50672   /* Coalesce adjacent free blocks */
   50673   addr = hdr + 1;
   50674   while( (pbegin = get2byte(&data[addr]))>0 ){
   50675     int pnext, psize, x;
   50676     assert( pbegin>addr );
   50677     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
   50678     pnext = get2byte(&data[pbegin]);
   50679     psize = get2byte(&data[pbegin+2]);
   50680     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   50681       int frag = pnext - (pbegin+psize);
   50682       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   50683         return SQLITE_CORRUPT_BKPT;
   50684       }
   50685       data[hdr+7] -= (u8)frag;
   50686       x = get2byte(&data[pnext]);
   50687       put2byte(&data[pbegin], x);
   50688       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   50689       put2byte(&data[pbegin+2], x);
   50690     }else{
   50691       addr = pbegin;
   50692     }
   50693   }
   50694 
   50695   /* If the cell content area begins with a freeblock, remove it. */
   50696   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   50697     int top;
   50698     pbegin = get2byte(&data[hdr+1]);
   50699     memcpy(&data[hdr+1], &data[pbegin], 2);
   50700     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   50701     put2byte(&data[hdr+5], top);
   50702   }
   50703   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50704   return SQLITE_OK;
   50705 }
   50706 
   50707 /*
   50708 ** Decode the flags byte (the first byte of the header) for a page
   50709 ** and initialize fields of the MemPage structure accordingly.
   50710 **
   50711 ** Only the following combinations are supported.  Anything different
   50712 ** indicates a corrupt database files:
   50713 **
   50714 **         PTF_ZERODATA
   50715 **         PTF_ZERODATA | PTF_LEAF
   50716 **         PTF_LEAFDATA | PTF_INTKEY
   50717 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   50718 */
   50719 static int decodeFlags(MemPage *pPage, int flagByte){
   50720   BtShared *pBt;     /* A copy of pPage->pBt */
   50721 
   50722   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   50723   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50724   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   50725   flagByte &= ~PTF_LEAF;
   50726   pPage->childPtrSize = 4-4*pPage->leaf;
   50727   pBt = pPage->pBt;
   50728   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   50729     pPage->intKey = 1;
   50730     pPage->hasData = pPage->leaf;
   50731     pPage->maxLocal = pBt->maxLeaf;
   50732     pPage->minLocal = pBt->minLeaf;
   50733   }else if( flagByte==PTF_ZERODATA ){
   50734     pPage->intKey = 0;
   50735     pPage->hasData = 0;
   50736     pPage->maxLocal = pBt->maxLocal;
   50737     pPage->minLocal = pBt->minLocal;
   50738   }else{
   50739     return SQLITE_CORRUPT_BKPT;
   50740   }
   50741   pPage->max1bytePayload = pBt->max1bytePayload;
   50742   return SQLITE_OK;
   50743 }
   50744 
   50745 /*
   50746 ** Initialize the auxiliary information for a disk block.
   50747 **
   50748 ** Return SQLITE_OK on success.  If we see that the page does
   50749 ** not contain a well-formed database page, then return
   50750 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   50751 ** guarantee that the page is well-formed.  It only shows that
   50752 ** we failed to detect any corruption.
   50753 */
   50754 static int btreeInitPage(MemPage *pPage){
   50755 
   50756   assert( pPage->pBt!=0 );
   50757   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50758   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   50759   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   50760   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   50761 
   50762   if( !pPage->isInit ){
   50763     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   50764     u8 hdr;            /* Offset to beginning of page header */
   50765     u8 *data;          /* Equal to pPage->aData */
   50766     BtShared *pBt;        /* The main btree structure */
   50767     int usableSize;    /* Amount of usable space on each page */
   50768     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   50769     int nFree;         /* Number of unused bytes on the page */
   50770     int top;           /* First byte of the cell content area */
   50771     int iCellFirst;    /* First allowable cell or freeblock offset */
   50772     int iCellLast;     /* Last possible cell or freeblock offset */
   50773 
   50774     pBt = pPage->pBt;
   50775 
   50776     hdr = pPage->hdrOffset;
   50777     data = pPage->aData;
   50778     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   50779     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   50780     pPage->maskPage = (u16)(pBt->pageSize - 1);
   50781     pPage->nOverflow = 0;
   50782     usableSize = pBt->usableSize;
   50783     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   50784     pPage->aDataEnd = &data[usableSize];
   50785     pPage->aCellIdx = &data[cellOffset];
   50786     top = get2byteNotZero(&data[hdr+5]);
   50787     pPage->nCell = get2byte(&data[hdr+3]);
   50788     if( pPage->nCell>MX_CELL(pBt) ){
   50789       /* To many cells for a single page.  The page must be corrupt */
   50790       return SQLITE_CORRUPT_BKPT;
   50791     }
   50792     testcase( pPage->nCell==MX_CELL(pBt) );
   50793 
   50794     /* A malformed database page might cause us to read past the end
   50795     ** of page when parsing a cell.
   50796     **
   50797     ** The following block of code checks early to see if a cell extends
   50798     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   50799     ** returned if it does.
   50800     */
   50801     iCellFirst = cellOffset + 2*pPage->nCell;
   50802     iCellLast = usableSize - 4;
   50803 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   50804     {
   50805       int i;            /* Index into the cell pointer array */
   50806       int sz;           /* Size of a cell */
   50807 
   50808       if( !pPage->leaf ) iCellLast--;
   50809       for(i=0; i<pPage->nCell; i++){
   50810         pc = get2byte(&data[cellOffset+i*2]);
   50811         testcase( pc==iCellFirst );
   50812         testcase( pc==iCellLast );
   50813         if( pc<iCellFirst || pc>iCellLast ){
   50814           return SQLITE_CORRUPT_BKPT;
   50815         }
   50816         sz = cellSizePtr(pPage, &data[pc]);
   50817         testcase( pc+sz==usableSize );
   50818         if( pc+sz>usableSize ){
   50819           return SQLITE_CORRUPT_BKPT;
   50820         }
   50821       }
   50822       if( !pPage->leaf ) iCellLast++;
   50823     }
   50824 #endif
   50825 
   50826     /* Compute the total free space on the page */
   50827     pc = get2byte(&data[hdr+1]);
   50828     nFree = data[hdr+7] + top;
   50829     while( pc>0 ){
   50830       u16 next, size;
   50831       if( pc<iCellFirst || pc>iCellLast ){
   50832         /* Start of free block is off the page */
   50833         return SQLITE_CORRUPT_BKPT;
   50834       }
   50835       next = get2byte(&data[pc]);
   50836       size = get2byte(&data[pc+2]);
   50837       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   50838         /* Free blocks must be in ascending order. And the last byte of
   50839 	** the free-block must lie on the database page.  */
   50840         return SQLITE_CORRUPT_BKPT;
   50841       }
   50842       nFree = nFree + size;
   50843       pc = next;
   50844     }
   50845 
   50846     /* At this point, nFree contains the sum of the offset to the start
   50847     ** of the cell-content area plus the number of free bytes within
   50848     ** the cell-content area. If this is greater than the usable-size
   50849     ** of the page, then the page must be corrupted. This check also
   50850     ** serves to verify that the offset to the start of the cell-content
   50851     ** area, according to the page header, lies within the page.
   50852     */
   50853     if( nFree>usableSize ){
   50854       return SQLITE_CORRUPT_BKPT;
   50855     }
   50856     pPage->nFree = (u16)(nFree - iCellFirst);
   50857     pPage->isInit = 1;
   50858   }
   50859   return SQLITE_OK;
   50860 }
   50861 
   50862 /*
   50863 ** Set up a raw page so that it looks like a database page holding
   50864 ** no entries.
   50865 */
   50866 static void zeroPage(MemPage *pPage, int flags){
   50867   unsigned char *data = pPage->aData;
   50868   BtShared *pBt = pPage->pBt;
   50869   u8 hdr = pPage->hdrOffset;
   50870   u16 first;
   50871 
   50872   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   50873   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   50874   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   50875   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50876   assert( sqlite3_mutex_held(pBt->mutex) );
   50877   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   50878     memset(&data[hdr], 0, pBt->usableSize - hdr);
   50879   }
   50880   data[hdr] = (char)flags;
   50881   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
   50882   memset(&data[hdr+1], 0, 4);
   50883   data[hdr+7] = 0;
   50884   put2byte(&data[hdr+5], pBt->usableSize);
   50885   pPage->nFree = (u16)(pBt->usableSize - first);
   50886   decodeFlags(pPage, flags);
   50887   pPage->hdrOffset = hdr;
   50888   pPage->cellOffset = first;
   50889   pPage->aDataEnd = &data[pBt->usableSize];
   50890   pPage->aCellIdx = &data[first];
   50891   pPage->nOverflow = 0;
   50892   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   50893   pPage->maskPage = (u16)(pBt->pageSize - 1);
   50894   pPage->nCell = 0;
   50895   pPage->isInit = 1;
   50896 }
   50897 
   50898 
   50899 /*
   50900 ** Convert a DbPage obtained from the pager into a MemPage used by
   50901 ** the btree layer.
   50902 */
   50903 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   50904   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   50905   pPage->aData = sqlite3PagerGetData(pDbPage);
   50906   pPage->pDbPage = pDbPage;
   50907   pPage->pBt = pBt;
   50908   pPage->pgno = pgno;
   50909   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   50910   return pPage;
   50911 }
   50912 
   50913 /*
   50914 ** Get a page from the pager.  Initialize the MemPage.pBt and
   50915 ** MemPage.aData elements if needed.
   50916 **
   50917 ** If the noContent flag is set, it means that we do not care about
   50918 ** the content of the page at this time.  So do not go to the disk
   50919 ** to fetch the content.  Just fill in the content with zeros for now.
   50920 ** If in the future we call sqlite3PagerWrite() on this page, that
   50921 ** means we have started to be concerned about content and the disk
   50922 ** read should occur at that point.
   50923 */
   50924 static int btreeGetPage(
   50925   BtShared *pBt,       /* The btree */
   50926   Pgno pgno,           /* Number of the page to fetch */
   50927   MemPage **ppPage,    /* Return the page in this parameter */
   50928   int noContent        /* Do not load page content if true */
   50929 ){
   50930   int rc;
   50931   DbPage *pDbPage;
   50932 
   50933   assert( sqlite3_mutex_held(pBt->mutex) );
   50934   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
   50935   if( rc ) return rc;
   50936   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   50937   return SQLITE_OK;
   50938 }
   50939 
   50940 /*
   50941 ** Retrieve a page from the pager cache. If the requested page is not
   50942 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   50943 ** MemPage.aData elements if needed.
   50944 */
   50945 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   50946   DbPage *pDbPage;
   50947   assert( sqlite3_mutex_held(pBt->mutex) );
   50948   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   50949   if( pDbPage ){
   50950     return btreePageFromDbPage(pDbPage, pgno, pBt);
   50951   }
   50952   return 0;
   50953 }
   50954 
   50955 /*
   50956 ** Return the size of the database file in pages. If there is any kind of
   50957 ** error, return ((unsigned int)-1).
   50958 */
   50959 static Pgno btreePagecount(BtShared *pBt){
   50960   return pBt->nPage;
   50961 }
   50962 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   50963   assert( sqlite3BtreeHoldsMutex(p) );
   50964   assert( ((p->pBt->nPage)&0x8000000)==0 );
   50965   return (int)btreePagecount(p->pBt);
   50966 }
   50967 
   50968 /*
   50969 ** Get a page from the pager and initialize it.  This routine is just a
   50970 ** convenience wrapper around separate calls to btreeGetPage() and
   50971 ** btreeInitPage().
   50972 **
   50973 ** If an error occurs, then the value *ppPage is set to is undefined. It
   50974 ** may remain unchanged, or it may be set to an invalid value.
   50975 */
   50976 static int getAndInitPage(
   50977   BtShared *pBt,          /* The database file */
   50978   Pgno pgno,           /* Number of the page to get */
   50979   MemPage **ppPage     /* Write the page pointer here */
   50980 ){
   50981   int rc;
   50982   assert( sqlite3_mutex_held(pBt->mutex) );
   50983 
   50984   if( pgno>btreePagecount(pBt) ){
   50985     rc = SQLITE_CORRUPT_BKPT;
   50986   }else{
   50987     rc = btreeGetPage(pBt, pgno, ppPage, 0);
   50988     if( rc==SQLITE_OK ){
   50989       rc = btreeInitPage(*ppPage);
   50990       if( rc!=SQLITE_OK ){
   50991         releasePage(*ppPage);
   50992       }
   50993     }
   50994   }
   50995 
   50996   testcase( pgno==0 );
   50997   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   50998   return rc;
   50999 }
   51000 
   51001 /*
   51002 ** Release a MemPage.  This should be called once for each prior
   51003 ** call to btreeGetPage.
   51004 */
   51005 static void releasePage(MemPage *pPage){
   51006   if( pPage ){
   51007     assert( pPage->aData );
   51008     assert( pPage->pBt );
   51009     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   51010     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   51011     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   51012     sqlite3PagerUnref(pPage->pDbPage);
   51013   }
   51014 }
   51015 
   51016 /*
   51017 ** During a rollback, when the pager reloads information into the cache
   51018 ** so that the cache is restored to its original state at the start of
   51019 ** the transaction, for each page restored this routine is called.
   51020 **
   51021 ** This routine needs to reset the extra data section at the end of the
   51022 ** page to agree with the restored data.
   51023 */
   51024 static void pageReinit(DbPage *pData){
   51025   MemPage *pPage;
   51026   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   51027   assert( sqlite3PagerPageRefcount(pData)>0 );
   51028   if( pPage->isInit ){
   51029     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   51030     pPage->isInit = 0;
   51031     if( sqlite3PagerPageRefcount(pData)>1 ){
   51032       /* pPage might not be a btree page;  it might be an overflow page
   51033       ** or ptrmap page or a free page.  In those cases, the following
   51034       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   51035       ** But no harm is done by this.  And it is very important that
   51036       ** btreeInitPage() be called on every btree page so we make
   51037       ** the call for every page that comes in for re-initing. */
   51038       btreeInitPage(pPage);
   51039     }
   51040   }
   51041 }
   51042 
   51043 /*
   51044 ** Invoke the busy handler for a btree.
   51045 */
   51046 static int btreeInvokeBusyHandler(void *pArg){
   51047   BtShared *pBt = (BtShared*)pArg;
   51048   assert( pBt->db );
   51049   assert( sqlite3_mutex_held(pBt->db->mutex) );
   51050   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   51051 }
   51052 
   51053 /*
   51054 ** Open a database file.
   51055 **
   51056 ** zFilename is the name of the database file.  If zFilename is NULL
   51057 ** then an ephemeral database is created.  The ephemeral database might
   51058 ** be exclusively in memory, or it might use a disk-based memory cache.
   51059 ** Either way, the ephemeral database will be automatically deleted
   51060 ** when sqlite3BtreeClose() is called.
   51061 **
   51062 ** If zFilename is ":memory:" then an in-memory database is created
   51063 ** that is automatically destroyed when it is closed.
   51064 **
   51065 ** The "flags" parameter is a bitmask that might contain bits like
   51066 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
   51067 **
   51068 ** If the database is already opened in the same database connection
   51069 ** and we are in shared cache mode, then the open will fail with an
   51070 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   51071 ** objects in the same database connection since doing so will lead
   51072 ** to problems with locking.
   51073 */
   51074 SQLITE_PRIVATE int sqlite3BtreeOpen(
   51075   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
   51076   const char *zFilename,  /* Name of the file containing the BTree database */
   51077   sqlite3 *db,            /* Associated database handle */
   51078   Btree **ppBtree,        /* Pointer to new Btree object written here */
   51079   int flags,              /* Options */
   51080   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   51081 ){
   51082   BtShared *pBt = 0;             /* Shared part of btree structure */
   51083   Btree *p;                      /* Handle to return */
   51084   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   51085   int rc = SQLITE_OK;            /* Result code from this function */
   51086   u8 nReserve;                   /* Byte of unused space on each page */
   51087   unsigned char zDbHeader[100];  /* Database header content */
   51088 
   51089   /* True if opening an ephemeral, temporary database */
   51090   const int isTempDb = zFilename==0 || zFilename[0]==0;
   51091 
   51092   /* Set the variable isMemdb to true for an in-memory database, or
   51093   ** false for a file-based database.
   51094   */
   51095 #ifdef SQLITE_OMIT_MEMORYDB
   51096   const int isMemdb = 0;
   51097 #else
   51098   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   51099                        || (isTempDb && sqlite3TempInMemory(db));
   51100 #endif
   51101 
   51102   assert( db!=0 );
   51103   assert( pVfs!=0 );
   51104   assert( sqlite3_mutex_held(db->mutex) );
   51105   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   51106 
   51107   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   51108   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   51109 
   51110   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   51111   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   51112 
   51113   if( isMemdb ){
   51114     flags |= BTREE_MEMORY;
   51115   }
   51116   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   51117     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   51118   }
   51119   p = sqlite3MallocZero(sizeof(Btree));
   51120   if( !p ){
   51121     return SQLITE_NOMEM;
   51122   }
   51123   p->inTrans = TRANS_NONE;
   51124   p->db = db;
   51125 #ifndef SQLITE_OMIT_SHARED_CACHE
   51126   p->lock.pBtree = p;
   51127   p->lock.iTable = 1;
   51128 #endif
   51129 
   51130 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51131   /*
   51132   ** If this Btree is a candidate for shared cache, try to find an
   51133   ** existing BtShared object that we can share with
   51134   */
   51135   if( isMemdb==0 && isTempDb==0 ){
   51136     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   51137       int nFullPathname = pVfs->mxPathname+1;
   51138       char *zFullPathname = sqlite3Malloc(nFullPathname);
   51139       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   51140       p->sharable = 1;
   51141       if( !zFullPathname ){
   51142         sqlite3_free(p);
   51143         return SQLITE_NOMEM;
   51144       }
   51145       rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
   51146       if( rc ){
   51147         sqlite3_free(zFullPathname);
   51148         sqlite3_free(p);
   51149         return rc;
   51150       }
   51151 #if SQLITE_THREADSAFE
   51152       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   51153       sqlite3_mutex_enter(mutexOpen);
   51154       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   51155       sqlite3_mutex_enter(mutexShared);
   51156 #endif
   51157       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   51158         assert( pBt->nRef>0 );
   51159         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
   51160                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   51161           int iDb;
   51162           for(iDb=db->nDb-1; iDb>=0; iDb--){
   51163             Btree *pExisting = db->aDb[iDb].pBt;
   51164             if( pExisting && pExisting->pBt==pBt ){
   51165               sqlite3_mutex_leave(mutexShared);
   51166               sqlite3_mutex_leave(mutexOpen);
   51167               sqlite3_free(zFullPathname);
   51168               sqlite3_free(p);
   51169               return SQLITE_CONSTRAINT;
   51170             }
   51171           }
   51172           p->pBt = pBt;
   51173           pBt->nRef++;
   51174           break;
   51175         }
   51176       }
   51177       sqlite3_mutex_leave(mutexShared);
   51178       sqlite3_free(zFullPathname);
   51179     }
   51180 #ifdef SQLITE_DEBUG
   51181     else{
   51182       /* In debug mode, we mark all persistent databases as sharable
   51183       ** even when they are not.  This exercises the locking code and
   51184       ** gives more opportunity for asserts(sqlite3_mutex_held())
   51185       ** statements to find locking problems.
   51186       */
   51187       p->sharable = 1;
   51188     }
   51189 #endif
   51190   }
   51191 #endif
   51192   if( pBt==0 ){
   51193     /*
   51194     ** The following asserts make sure that structures used by the btree are
   51195     ** the right size.  This is to guard against size changes that result
   51196     ** when compiling on a different architecture.
   51197     */
   51198     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   51199     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   51200     assert( sizeof(u32)==4 );
   51201     assert( sizeof(u16)==2 );
   51202     assert( sizeof(Pgno)==4 );
   51203 
   51204     pBt = sqlite3MallocZero( sizeof(*pBt) );
   51205     if( pBt==0 ){
   51206       rc = SQLITE_NOMEM;
   51207       goto btree_open_out;
   51208     }
   51209     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   51210                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   51211     if( rc==SQLITE_OK ){
   51212       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   51213     }
   51214     if( rc!=SQLITE_OK ){
   51215       goto btree_open_out;
   51216     }
   51217     pBt->openFlags = (u8)flags;
   51218     pBt->db = db;
   51219     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   51220     p->pBt = pBt;
   51221 
   51222     pBt->pCursor = 0;
   51223     pBt->pPage1 = 0;
   51224     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
   51225 #ifdef SQLITE_SECURE_DELETE
   51226     pBt->btsFlags |= BTS_SECURE_DELETE;
   51227 #endif
   51228     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   51229     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   51230          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   51231       pBt->pageSize = 0;
   51232 #ifndef SQLITE_OMIT_AUTOVACUUM
   51233       /* If the magic name ":memory:" will create an in-memory database, then
   51234       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   51235       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   51236       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   51237       ** regular file-name. In this case the auto-vacuum applies as per normal.
   51238       */
   51239       if( zFilename && !isMemdb ){
   51240         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   51241         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   51242       }
   51243 #endif
   51244       nReserve = 0;
   51245     }else{
   51246       nReserve = zDbHeader[20];
   51247       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51248 #ifndef SQLITE_OMIT_AUTOVACUUM
   51249       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   51250       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   51251 #endif
   51252     }
   51253     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   51254     if( rc ) goto btree_open_out;
   51255     pBt->usableSize = pBt->pageSize - nReserve;
   51256     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   51257 
   51258 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51259     /* Add the new BtShared object to the linked list sharable BtShareds.
   51260     */
   51261     if( p->sharable ){
   51262       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
   51263       pBt->nRef = 1;
   51264       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
   51265       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   51266         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   51267         if( pBt->mutex==0 ){
   51268           rc = SQLITE_NOMEM;
   51269           db->mallocFailed = 0;
   51270           goto btree_open_out;
   51271         }
   51272       }
   51273       sqlite3_mutex_enter(mutexShared);
   51274       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   51275       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   51276       sqlite3_mutex_leave(mutexShared);
   51277     }
   51278 #endif
   51279   }
   51280 
   51281 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   51282   /* If the new Btree uses a sharable pBtShared, then link the new
   51283   ** Btree into the list of all sharable Btrees for the same connection.
   51284   ** The list is kept in ascending order by pBt address.
   51285   */
   51286   if( p->sharable ){
   51287     int i;
   51288     Btree *pSib;
   51289     for(i=0; i<db->nDb; i++){
   51290       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   51291         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   51292         if( p->pBt<pSib->pBt ){
   51293           p->pNext = pSib;
   51294           p->pPrev = 0;
   51295           pSib->pPrev = p;
   51296         }else{
   51297           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   51298             pSib = pSib->pNext;
   51299           }
   51300           p->pNext = pSib->pNext;
   51301           p->pPrev = pSib;
   51302           if( p->pNext ){
   51303             p->pNext->pPrev = p;
   51304           }
   51305           pSib->pNext = p;
   51306         }
   51307         break;
   51308       }
   51309     }
   51310   }
   51311 #endif
   51312   *ppBtree = p;
   51313 
   51314 btree_open_out:
   51315   if( rc!=SQLITE_OK ){
   51316     if( pBt && pBt->pPager ){
   51317       sqlite3PagerClose(pBt->pPager);
   51318     }
   51319     sqlite3_free(pBt);
   51320     sqlite3_free(p);
   51321     *ppBtree = 0;
   51322   }else{
   51323     /* If the B-Tree was successfully opened, set the pager-cache size to the
   51324     ** default value. Except, when opening on an existing shared pager-cache,
   51325     ** do not change the pager-cache size.
   51326     */
   51327     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   51328       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   51329     }
   51330   }
   51331   if( mutexOpen ){
   51332     assert( sqlite3_mutex_held(mutexOpen) );
   51333     sqlite3_mutex_leave(mutexOpen);
   51334   }
   51335   return rc;
   51336 }
   51337 
   51338 /*
   51339 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   51340 ** remove the BtShared structure from the sharing list.  Return
   51341 ** true if the BtShared.nRef counter reaches zero and return
   51342 ** false if it is still positive.
   51343 */
   51344 static int removeFromSharingList(BtShared *pBt){
   51345 #ifndef SQLITE_OMIT_SHARED_CACHE
   51346   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
   51347   BtShared *pList;
   51348   int removed = 0;
   51349 
   51350   assert( sqlite3_mutex_notheld(pBt->mutex) );
   51351   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   51352   sqlite3_mutex_enter(pMaster);
   51353   pBt->nRef--;
   51354   if( pBt->nRef<=0 ){
   51355     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   51356       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   51357     }else{
   51358       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   51359       while( ALWAYS(pList) && pList->pNext!=pBt ){
   51360         pList=pList->pNext;
   51361       }
   51362       if( ALWAYS(pList) ){
   51363         pList->pNext = pBt->pNext;
   51364       }
   51365     }
   51366     if( SQLITE_THREADSAFE ){
   51367       sqlite3_mutex_free(pBt->mutex);
   51368     }
   51369     removed = 1;
   51370   }
   51371   sqlite3_mutex_leave(pMaster);
   51372   return removed;
   51373 #else
   51374   return 1;
   51375 #endif
   51376 }
   51377 
   51378 /*
   51379 ** Make sure pBt->pTmpSpace points to an allocation of
   51380 ** MX_CELL_SIZE(pBt) bytes.
   51381 */
   51382 static void allocateTempSpace(BtShared *pBt){
   51383   if( !pBt->pTmpSpace ){
   51384     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   51385   }
   51386 }
   51387 
   51388 /*
   51389 ** Free the pBt->pTmpSpace allocation
   51390 */
   51391 static void freeTempSpace(BtShared *pBt){
   51392   sqlite3PageFree( pBt->pTmpSpace);
   51393   pBt->pTmpSpace = 0;
   51394 }
   51395 
   51396 /*
   51397 ** Close an open database and invalidate all cursors.
   51398 */
   51399 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   51400   BtShared *pBt = p->pBt;
   51401   BtCursor *pCur;
   51402 
   51403   /* Close all cursors opened via this handle.  */
   51404   assert( sqlite3_mutex_held(p->db->mutex) );
   51405   sqlite3BtreeEnter(p);
   51406   pCur = pBt->pCursor;
   51407   while( pCur ){
   51408     BtCursor *pTmp = pCur;
   51409     pCur = pCur->pNext;
   51410     if( pTmp->pBtree==p ){
   51411       sqlite3BtreeCloseCursor(pTmp);
   51412     }
   51413   }
   51414 
   51415   /* Rollback any active transaction and free the handle structure.
   51416   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   51417   ** this handle.
   51418   */
   51419   sqlite3BtreeRollback(p, SQLITE_OK);
   51420   sqlite3BtreeLeave(p);
   51421 
   51422   /* If there are still other outstanding references to the shared-btree
   51423   ** structure, return now. The remainder of this procedure cleans
   51424   ** up the shared-btree.
   51425   */
   51426   assert( p->wantToLock==0 && p->locked==0 );
   51427   if( !p->sharable || removeFromSharingList(pBt) ){
   51428     /* The pBt is no longer on the sharing list, so we can access
   51429     ** it without having to hold the mutex.
   51430     **
   51431     ** Clean out and delete the BtShared object.
   51432     */
   51433     assert( !pBt->pCursor );
   51434     sqlite3PagerClose(pBt->pPager);
   51435     if( pBt->xFreeSchema && pBt->pSchema ){
   51436       pBt->xFreeSchema(pBt->pSchema);
   51437     }
   51438     sqlite3DbFree(0, pBt->pSchema);
   51439     freeTempSpace(pBt);
   51440     sqlite3_free(pBt);
   51441   }
   51442 
   51443 #ifndef SQLITE_OMIT_SHARED_CACHE
   51444   assert( p->wantToLock==0 );
   51445   assert( p->locked==0 );
   51446   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   51447   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   51448 #endif
   51449 
   51450   sqlite3_free(p);
   51451   return SQLITE_OK;
   51452 }
   51453 
   51454 /*
   51455 ** Change the limit on the number of pages allowed in the cache.
   51456 **
   51457 ** The maximum number of cache pages is set to the absolute
   51458 ** value of mxPage.  If mxPage is negative, the pager will
   51459 ** operate asynchronously - it will not stop to do fsync()s
   51460 ** to insure data is written to the disk surface before
   51461 ** continuing.  Transactions still work if synchronous is off,
   51462 ** and the database cannot be corrupted if this program
   51463 ** crashes.  But if the operating system crashes or there is
   51464 ** an abrupt power failure when synchronous is off, the database
   51465 ** could be left in an inconsistent and unrecoverable state.
   51466 ** Synchronous is on by default so database corruption is not
   51467 ** normally a worry.
   51468 */
   51469 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   51470   BtShared *pBt = p->pBt;
   51471   assert( sqlite3_mutex_held(p->db->mutex) );
   51472   sqlite3BtreeEnter(p);
   51473   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   51474   sqlite3BtreeLeave(p);
   51475   return SQLITE_OK;
   51476 }
   51477 
   51478 /*
   51479 ** Change the way data is synced to disk in order to increase or decrease
   51480 ** how well the database resists damage due to OS crashes and power
   51481 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   51482 ** there is a high probability of damage)  Level 2 is the default.  There
   51483 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   51484 ** probability of damage to near zero but with a write performance reduction.
   51485 */
   51486 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   51487 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
   51488   Btree *p,              /* The btree to set the safety level on */
   51489   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   51490   int fullSync,          /* PRAGMA fullfsync. */
   51491   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
   51492 ){
   51493   BtShared *pBt = p->pBt;
   51494   assert( sqlite3_mutex_held(p->db->mutex) );
   51495   assert( level>=1 && level<=3 );
   51496   sqlite3BtreeEnter(p);
   51497   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
   51498   sqlite3BtreeLeave(p);
   51499   return SQLITE_OK;
   51500 }
   51501 #endif
   51502 
   51503 /*
   51504 ** Return TRUE if the given btree is set to safety level 1.  In other
   51505 ** words, return TRUE if no sync() occurs on the disk files.
   51506 */
   51507 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   51508   BtShared *pBt = p->pBt;
   51509   int rc;
   51510   assert( sqlite3_mutex_held(p->db->mutex) );
   51511   sqlite3BtreeEnter(p);
   51512   assert( pBt && pBt->pPager );
   51513   rc = sqlite3PagerNosync(pBt->pPager);
   51514   sqlite3BtreeLeave(p);
   51515   return rc;
   51516 }
   51517 
   51518 /*
   51519 ** Change the default pages size and the number of reserved bytes per page.
   51520 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   51521 ** without changing anything.
   51522 **
   51523 ** The page size must be a power of 2 between 512 and 65536.  If the page
   51524 ** size supplied does not meet this constraint then the page size is not
   51525 ** changed.
   51526 **
   51527 ** Page sizes are constrained to be a power of two so that the region
   51528 ** of the database file used for locking (beginning at PENDING_BYTE,
   51529 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   51530 ** at the beginning of a page.
   51531 **
   51532 ** If parameter nReserve is less than zero, then the number of reserved
   51533 ** bytes per page is left unchanged.
   51534 **
   51535 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
   51536 ** and autovacuum mode can no longer be changed.
   51537 */
   51538 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   51539   int rc = SQLITE_OK;
   51540   BtShared *pBt = p->pBt;
   51541   assert( nReserve>=-1 && nReserve<=255 );
   51542   sqlite3BtreeEnter(p);
   51543   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
   51544     sqlite3BtreeLeave(p);
   51545     return SQLITE_READONLY;
   51546   }
   51547   if( nReserve<0 ){
   51548     nReserve = pBt->pageSize - pBt->usableSize;
   51549   }
   51550   assert( nReserve>=0 && nReserve<=255 );
   51551   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   51552         ((pageSize-1)&pageSize)==0 ){
   51553     assert( (pageSize & 7)==0 );
   51554     assert( !pBt->pPage1 && !pBt->pCursor );
   51555     pBt->pageSize = (u32)pageSize;
   51556     freeTempSpace(pBt);
   51557   }
   51558   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   51559   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   51560   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51561   sqlite3BtreeLeave(p);
   51562   return rc;
   51563 }
   51564 
   51565 /*
   51566 ** Return the currently defined page size
   51567 */
   51568 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   51569   return p->pBt->pageSize;
   51570 }
   51571 
   51572 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   51573 /*
   51574 ** Return the number of bytes of space at the end of every page that
   51575 ** are intentually left unused.  This is the "reserved" space that is
   51576 ** sometimes used by extensions.
   51577 */
   51578 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   51579   int n;
   51580   sqlite3BtreeEnter(p);
   51581   n = p->pBt->pageSize - p->pBt->usableSize;
   51582   sqlite3BtreeLeave(p);
   51583   return n;
   51584 }
   51585 
   51586 /*
   51587 ** Set the maximum page count for a database if mxPage is positive.
   51588 ** No changes are made if mxPage is 0 or negative.
   51589 ** Regardless of the value of mxPage, return the maximum page count.
   51590 */
   51591 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   51592   int n;
   51593   sqlite3BtreeEnter(p);
   51594   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   51595   sqlite3BtreeLeave(p);
   51596   return n;
   51597 }
   51598 
   51599 /*
   51600 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
   51601 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
   51602 ** setting after the change.
   51603 */
   51604 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   51605   int b;
   51606   if( p==0 ) return 0;
   51607   sqlite3BtreeEnter(p);
   51608   if( newFlag>=0 ){
   51609     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
   51610     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
   51611   }
   51612   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
   51613   sqlite3BtreeLeave(p);
   51614   return b;
   51615 }
   51616 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   51617 
   51618 /*
   51619 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   51620 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   51621 ** is disabled. The default value for the auto-vacuum property is
   51622 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   51623 */
   51624 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   51625 #ifdef SQLITE_OMIT_AUTOVACUUM
   51626   return SQLITE_READONLY;
   51627 #else
   51628   BtShared *pBt = p->pBt;
   51629   int rc = SQLITE_OK;
   51630   u8 av = (u8)autoVacuum;
   51631 
   51632   sqlite3BtreeEnter(p);
   51633   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
   51634     rc = SQLITE_READONLY;
   51635   }else{
   51636     pBt->autoVacuum = av ?1:0;
   51637     pBt->incrVacuum = av==2 ?1:0;
   51638   }
   51639   sqlite3BtreeLeave(p);
   51640   return rc;
   51641 #endif
   51642 }
   51643 
   51644 /*
   51645 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   51646 ** enabled 1 is returned. Otherwise 0.
   51647 */
   51648 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   51649 #ifdef SQLITE_OMIT_AUTOVACUUM
   51650   return BTREE_AUTOVACUUM_NONE;
   51651 #else
   51652   int rc;
   51653   sqlite3BtreeEnter(p);
   51654   rc = (
   51655     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   51656     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   51657     BTREE_AUTOVACUUM_INCR
   51658   );
   51659   sqlite3BtreeLeave(p);
   51660   return rc;
   51661 #endif
   51662 }
   51663 
   51664 
   51665 /*
   51666 ** Get a reference to pPage1 of the database file.  This will
   51667 ** also acquire a readlock on that file.
   51668 **
   51669 ** SQLITE_OK is returned on success.  If the file is not a
   51670 ** well-formed database file, then SQLITE_CORRUPT is returned.
   51671 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   51672 ** is returned if we run out of memory.
   51673 */
   51674 static int lockBtree(BtShared *pBt){
   51675   int rc;              /* Result code from subfunctions */
   51676   MemPage *pPage1;     /* Page 1 of the database file */
   51677   int nPage;           /* Number of pages in the database */
   51678   int nPageFile = 0;   /* Number of pages in the database file */
   51679   int nPageHeader;     /* Number of pages in the database according to hdr */
   51680 
   51681   assert( sqlite3_mutex_held(pBt->mutex) );
   51682   assert( pBt->pPage1==0 );
   51683   rc = sqlite3PagerSharedLock(pBt->pPager);
   51684   if( rc!=SQLITE_OK ) return rc;
   51685   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   51686   if( rc!=SQLITE_OK ) return rc;
   51687 
   51688   /* Do some checking to help insure the file we opened really is
   51689   ** a valid database file.
   51690   */
   51691   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   51692   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   51693   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   51694     nPage = nPageFile;
   51695   }
   51696   if( nPage>0 ){
   51697     u32 pageSize;
   51698     u32 usableSize;
   51699     u8 *page1 = pPage1->aData;
   51700     rc = SQLITE_NOTADB;
   51701     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   51702       goto page1_init_failed;
   51703     }
   51704 
   51705 #ifdef SQLITE_OMIT_WAL
   51706     if( page1[18]>1 ){
   51707       pBt->btsFlags |= BTS_READ_ONLY;
   51708     }
   51709     if( page1[19]>1 ){
   51710       goto page1_init_failed;
   51711     }
   51712 #else
   51713     if( page1[18]>2 ){
   51714       pBt->btsFlags |= BTS_READ_ONLY;
   51715     }
   51716     if( page1[19]>2 ){
   51717       goto page1_init_failed;
   51718     }
   51719 
   51720     /* If the write version is set to 2, this database should be accessed
   51721     ** in WAL mode. If the log is not already open, open it now. Then
   51722     ** return SQLITE_OK and return without populating BtShared.pPage1.
   51723     ** The caller detects this and calls this function again. This is
   51724     ** required as the version of page 1 currently in the page1 buffer
   51725     ** may not be the latest version - there may be a newer one in the log
   51726     ** file.
   51727     */
   51728     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
   51729       int isOpen = 0;
   51730       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   51731       if( rc!=SQLITE_OK ){
   51732         goto page1_init_failed;
   51733       }else if( isOpen==0 ){
   51734         releasePage(pPage1);
   51735         return SQLITE_OK;
   51736       }
   51737       rc = SQLITE_NOTADB;
   51738     }
   51739 #endif
   51740 
   51741     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   51742     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   51743     ** The original design allowed these amounts to vary, but as of
   51744     ** version 3.6.0, we require them to be fixed.
   51745     */
   51746     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   51747       goto page1_init_failed;
   51748     }
   51749     pageSize = (page1[16]<<8) | (page1[17]<<16);
   51750     if( ((pageSize-1)&pageSize)!=0
   51751      || pageSize>SQLITE_MAX_PAGE_SIZE
   51752      || pageSize<=256
   51753     ){
   51754       goto page1_init_failed;
   51755     }
   51756     assert( (pageSize & 7)==0 );
   51757     usableSize = pageSize - page1[20];
   51758     if( (u32)pageSize!=pBt->pageSize ){
   51759       /* After reading the first page of the database assuming a page size
   51760       ** of BtShared.pageSize, we have discovered that the page-size is
   51761       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   51762       ** zero and return SQLITE_OK. The caller will call this function
   51763       ** again with the correct page-size.
   51764       */
   51765       releasePage(pPage1);
   51766       pBt->usableSize = usableSize;
   51767       pBt->pageSize = pageSize;
   51768       freeTempSpace(pBt);
   51769       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   51770                                    pageSize-usableSize);
   51771       return rc;
   51772     }
   51773     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
   51774       rc = SQLITE_CORRUPT_BKPT;
   51775       goto page1_init_failed;
   51776     }
   51777     if( usableSize<480 ){
   51778       goto page1_init_failed;
   51779     }
   51780     pBt->pageSize = pageSize;
   51781     pBt->usableSize = usableSize;
   51782 #ifndef SQLITE_OMIT_AUTOVACUUM
   51783     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   51784     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   51785 #endif
   51786   }
   51787 
   51788   /* maxLocal is the maximum amount of payload to store locally for
   51789   ** a cell.  Make sure it is small enough so that at least minFanout
   51790   ** cells can will fit on one page.  We assume a 10-byte page header.
   51791   ** Besides the payload, the cell must store:
   51792   **     2-byte pointer to the cell
   51793   **     4-byte child pointer
   51794   **     9-byte nKey value
   51795   **     4-byte nData value
   51796   **     4-byte overflow page pointer
   51797   ** So a cell consists of a 2-byte pointer, a header which is as much as
   51798   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   51799   ** page pointer.
   51800   */
   51801   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   51802   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   51803   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   51804   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   51805   if( pBt->maxLocal>127 ){
   51806     pBt->max1bytePayload = 127;
   51807   }else{
   51808     pBt->max1bytePayload = (u8)pBt->maxLocal;
   51809   }
   51810   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   51811   pBt->pPage1 = pPage1;
   51812   pBt->nPage = nPage;
   51813   return SQLITE_OK;
   51814 
   51815 page1_init_failed:
   51816   releasePage(pPage1);
   51817   pBt->pPage1 = 0;
   51818   return rc;
   51819 }
   51820 
   51821 /*
   51822 ** If there are no outstanding cursors and we are not in the middle
   51823 ** of a transaction but there is a read lock on the database, then
   51824 ** this routine unrefs the first page of the database file which
   51825 ** has the effect of releasing the read lock.
   51826 **
   51827 ** If there is a transaction in progress, this routine is a no-op.
   51828 */
   51829 static void unlockBtreeIfUnused(BtShared *pBt){
   51830   assert( sqlite3_mutex_held(pBt->mutex) );
   51831   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
   51832   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   51833     assert( pBt->pPage1->aData );
   51834     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   51835     assert( pBt->pPage1->aData );
   51836     releasePage(pBt->pPage1);
   51837     pBt->pPage1 = 0;
   51838   }
   51839 }
   51840 
   51841 /*
   51842 ** If pBt points to an empty file then convert that empty file
   51843 ** into a new empty database by initializing the first page of
   51844 ** the database.
   51845 */
   51846 static int newDatabase(BtShared *pBt){
   51847   MemPage *pP1;
   51848   unsigned char *data;
   51849   int rc;
   51850 
   51851   assert( sqlite3_mutex_held(pBt->mutex) );
   51852   if( pBt->nPage>0 ){
   51853     return SQLITE_OK;
   51854   }
   51855   pP1 = pBt->pPage1;
   51856   assert( pP1!=0 );
   51857   data = pP1->aData;
   51858   rc = sqlite3PagerWrite(pP1->pDbPage);
   51859   if( rc ) return rc;
   51860   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   51861   assert( sizeof(zMagicHeader)==16 );
   51862   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   51863   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   51864   data[18] = 1;
   51865   data[19] = 1;
   51866   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   51867   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   51868   data[21] = 64;
   51869   data[22] = 32;
   51870   data[23] = 32;
   51871   memset(&data[24], 0, 100-24);
   51872   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   51873   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
   51874 #ifndef SQLITE_OMIT_AUTOVACUUM
   51875   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   51876   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   51877   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   51878   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   51879 #endif
   51880   pBt->nPage = 1;
   51881   data[31] = 1;
   51882   return SQLITE_OK;
   51883 }
   51884 
   51885 /*
   51886 ** Attempt to start a new transaction. A write-transaction
   51887 ** is started if the second argument is nonzero, otherwise a read-
   51888 ** transaction.  If the second argument is 2 or more and exclusive
   51889 ** transaction is started, meaning that no other process is allowed
   51890 ** to access the database.  A preexisting transaction may not be
   51891 ** upgraded to exclusive by calling this routine a second time - the
   51892 ** exclusivity flag only works for a new transaction.
   51893 **
   51894 ** A write-transaction must be started before attempting any
   51895 ** changes to the database.  None of the following routines
   51896 ** will work unless a transaction is started first:
   51897 **
   51898 **      sqlite3BtreeCreateTable()
   51899 **      sqlite3BtreeCreateIndex()
   51900 **      sqlite3BtreeClearTable()
   51901 **      sqlite3BtreeDropTable()
   51902 **      sqlite3BtreeInsert()
   51903 **      sqlite3BtreeDelete()
   51904 **      sqlite3BtreeUpdateMeta()
   51905 **
   51906 ** If an initial attempt to acquire the lock fails because of lock contention
   51907 ** and the database was previously unlocked, then invoke the busy handler
   51908 ** if there is one.  But if there was previously a read-lock, do not
   51909 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   51910 ** returned when there is already a read-lock in order to avoid a deadlock.
   51911 **
   51912 ** Suppose there are two processes A and B.  A has a read lock and B has
   51913 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   51914 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   51915 ** One or the other of the two processes must give way or there can be
   51916 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   51917 ** when A already has a read lock, we encourage A to give up and let B
   51918 ** proceed.
   51919 */
   51920 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   51921   sqlite3 *pBlock = 0;
   51922   BtShared *pBt = p->pBt;
   51923   int rc = SQLITE_OK;
   51924 
   51925   sqlite3BtreeEnter(p);
   51926   btreeIntegrity(p);
   51927 
   51928   /* If the btree is already in a write-transaction, or it
   51929   ** is already in a read-transaction and a read-transaction
   51930   ** is requested, this is a no-op.
   51931   */
   51932   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   51933     goto trans_begun;
   51934   }
   51935 
   51936   /* Write transactions are not possible on a read-only database */
   51937   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
   51938     rc = SQLITE_READONLY;
   51939     goto trans_begun;
   51940   }
   51941 
   51942 #ifndef SQLITE_OMIT_SHARED_CACHE
   51943   /* If another database handle has already opened a write transaction
   51944   ** on this shared-btree structure and a second write transaction is
   51945   ** requested, return SQLITE_LOCKED.
   51946   */
   51947   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
   51948    || (pBt->btsFlags & BTS_PENDING)!=0
   51949   ){
   51950     pBlock = pBt->pWriter->db;
   51951   }else if( wrflag>1 ){
   51952     BtLock *pIter;
   51953     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   51954       if( pIter->pBtree!=p ){
   51955         pBlock = pIter->pBtree->db;
   51956         break;
   51957       }
   51958     }
   51959   }
   51960   if( pBlock ){
   51961     sqlite3ConnectionBlocked(p->db, pBlock);
   51962     rc = SQLITE_LOCKED_SHAREDCACHE;
   51963     goto trans_begun;
   51964   }
   51965 #endif
   51966 
   51967   /* Any read-only or read-write transaction implies a read-lock on
   51968   ** page 1. So if some other shared-cache client already has a write-lock
   51969   ** on page 1, the transaction cannot be opened. */
   51970   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   51971   if( SQLITE_OK!=rc ) goto trans_begun;
   51972 
   51973   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   51974   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   51975   do {
   51976     /* Call lockBtree() until either pBt->pPage1 is populated or
   51977     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   51978     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   51979     ** reading page 1 it discovers that the page-size of the database
   51980     ** file is not pBt->pageSize. In this case lockBtree() will update
   51981     ** pBt->pageSize to the page-size of the file on disk.
   51982     */
   51983     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   51984 
   51985     if( rc==SQLITE_OK && wrflag ){
   51986       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
   51987         rc = SQLITE_READONLY;
   51988       }else{
   51989         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   51990         if( rc==SQLITE_OK ){
   51991           rc = newDatabase(pBt);
   51992         }
   51993       }
   51994     }
   51995 
   51996     if( rc!=SQLITE_OK ){
   51997       unlockBtreeIfUnused(pBt);
   51998     }
   51999   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   52000           btreeInvokeBusyHandler(pBt) );
   52001 
   52002   if( rc==SQLITE_OK ){
   52003     if( p->inTrans==TRANS_NONE ){
   52004       pBt->nTransaction++;
   52005 #ifndef SQLITE_OMIT_SHARED_CACHE
   52006       if( p->sharable ){
   52007 	assert( p->lock.pBtree==p && p->lock.iTable==1 );
   52008         p->lock.eLock = READ_LOCK;
   52009         p->lock.pNext = pBt->pLock;
   52010         pBt->pLock = &p->lock;
   52011       }
   52012 #endif
   52013     }
   52014     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   52015     if( p->inTrans>pBt->inTransaction ){
   52016       pBt->inTransaction = p->inTrans;
   52017     }
   52018     if( wrflag ){
   52019       MemPage *pPage1 = pBt->pPage1;
   52020 #ifndef SQLITE_OMIT_SHARED_CACHE
   52021       assert( !pBt->pWriter );
   52022       pBt->pWriter = p;
   52023       pBt->btsFlags &= ~BTS_EXCLUSIVE;
   52024       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
   52025 #endif
   52026 
   52027       /* If the db-size header field is incorrect (as it may be if an old
   52028       ** client has been writing the database file), update it now. Doing
   52029       ** this sooner rather than later means the database size can safely
   52030       ** re-read the database size from page 1 if a savepoint or transaction
   52031       ** rollback occurs within the transaction.
   52032       */
   52033       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   52034         rc = sqlite3PagerWrite(pPage1->pDbPage);
   52035         if( rc==SQLITE_OK ){
   52036           put4byte(&pPage1->aData[28], pBt->nPage);
   52037         }
   52038       }
   52039     }
   52040   }
   52041 
   52042 
   52043 trans_begun:
   52044   if( rc==SQLITE_OK && wrflag ){
   52045     /* This call makes sure that the pager has the correct number of
   52046     ** open savepoints. If the second parameter is greater than 0 and
   52047     ** the sub-journal is not already open, then it will be opened here.
   52048     */
   52049     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   52050   }
   52051 
   52052   btreeIntegrity(p);
   52053   sqlite3BtreeLeave(p);
   52054   return rc;
   52055 }
   52056 
   52057 #ifndef SQLITE_OMIT_AUTOVACUUM
   52058 
   52059 /*
   52060 ** Set the pointer-map entries for all children of page pPage. Also, if
   52061 ** pPage contains cells that point to overflow pages, set the pointer
   52062 ** map entries for the overflow pages as well.
   52063 */
   52064 static int setChildPtrmaps(MemPage *pPage){
   52065   int i;                             /* Counter variable */
   52066   int nCell;                         /* Number of cells in page pPage */
   52067   int rc;                            /* Return code */
   52068   BtShared *pBt = pPage->pBt;
   52069   u8 isInitOrig = pPage->isInit;
   52070   Pgno pgno = pPage->pgno;
   52071 
   52072   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52073   rc = btreeInitPage(pPage);
   52074   if( rc!=SQLITE_OK ){
   52075     goto set_child_ptrmaps_out;
   52076   }
   52077   nCell = pPage->nCell;
   52078 
   52079   for(i=0; i<nCell; i++){
   52080     u8 *pCell = findCell(pPage, i);
   52081 
   52082     ptrmapPutOvflPtr(pPage, pCell, &rc);
   52083 
   52084     if( !pPage->leaf ){
   52085       Pgno childPgno = get4byte(pCell);
   52086       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   52087     }
   52088   }
   52089 
   52090   if( !pPage->leaf ){
   52091     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   52092     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   52093   }
   52094 
   52095 set_child_ptrmaps_out:
   52096   pPage->isInit = isInitOrig;
   52097   return rc;
   52098 }
   52099 
   52100 /*
   52101 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   52102 ** that it points to iTo. Parameter eType describes the type of pointer to
   52103 ** be modified, as  follows:
   52104 **
   52105 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   52106 **                   page of pPage.
   52107 **
   52108 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   52109 **                   page pointed to by one of the cells on pPage.
   52110 **
   52111 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   52112 **                   overflow page in the list.
   52113 */
   52114 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   52115   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   52116   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   52117   if( eType==PTRMAP_OVERFLOW2 ){
   52118     /* The pointer is always the first 4 bytes of the page in this case.  */
   52119     if( get4byte(pPage->aData)!=iFrom ){
   52120       return SQLITE_CORRUPT_BKPT;
   52121     }
   52122     put4byte(pPage->aData, iTo);
   52123   }else{
   52124     u8 isInitOrig = pPage->isInit;
   52125     int i;
   52126     int nCell;
   52127 
   52128     btreeInitPage(pPage);
   52129     nCell = pPage->nCell;
   52130 
   52131     for(i=0; i<nCell; i++){
   52132       u8 *pCell = findCell(pPage, i);
   52133       if( eType==PTRMAP_OVERFLOW1 ){
   52134         CellInfo info;
   52135         btreeParseCellPtr(pPage, pCell, &info);
   52136         if( info.iOverflow
   52137          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
   52138          && iFrom==get4byte(&pCell[info.iOverflow])
   52139         ){
   52140           put4byte(&pCell[info.iOverflow], iTo);
   52141           break;
   52142         }
   52143       }else{
   52144         if( get4byte(pCell)==iFrom ){
   52145           put4byte(pCell, iTo);
   52146           break;
   52147         }
   52148       }
   52149     }
   52150 
   52151     if( i==nCell ){
   52152       if( eType!=PTRMAP_BTREE ||
   52153           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   52154         return SQLITE_CORRUPT_BKPT;
   52155       }
   52156       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   52157     }
   52158 
   52159     pPage->isInit = isInitOrig;
   52160   }
   52161   return SQLITE_OK;
   52162 }
   52163 
   52164 
   52165 /*
   52166 ** Move the open database page pDbPage to location iFreePage in the
   52167 ** database. The pDbPage reference remains valid.
   52168 **
   52169 ** The isCommit flag indicates that there is no need to remember that
   52170 ** the journal needs to be sync()ed before database page pDbPage->pgno
   52171 ** can be written to. The caller has already promised not to write to that
   52172 ** page.
   52173 */
   52174 static int relocatePage(
   52175   BtShared *pBt,           /* Btree */
   52176   MemPage *pDbPage,        /* Open page to move */
   52177   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   52178   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   52179   Pgno iFreePage,          /* The location to move pDbPage to */
   52180   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   52181 ){
   52182   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   52183   Pgno iDbPage = pDbPage->pgno;
   52184   Pager *pPager = pBt->pPager;
   52185   int rc;
   52186 
   52187   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   52188       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   52189   assert( sqlite3_mutex_held(pBt->mutex) );
   52190   assert( pDbPage->pBt==pBt );
   52191 
   52192   /* Move page iDbPage from its current location to page number iFreePage */
   52193   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   52194       iDbPage, iFreePage, iPtrPage, eType));
   52195   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   52196   if( rc!=SQLITE_OK ){
   52197     return rc;
   52198   }
   52199   pDbPage->pgno = iFreePage;
   52200 
   52201   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   52202   ** that point to overflow pages. The pointer map entries for all these
   52203   ** pages need to be changed.
   52204   **
   52205   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   52206   ** pointer to a subsequent overflow page. If this is the case, then
   52207   ** the pointer map needs to be updated for the subsequent overflow page.
   52208   */
   52209   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   52210     rc = setChildPtrmaps(pDbPage);
   52211     if( rc!=SQLITE_OK ){
   52212       return rc;
   52213     }
   52214   }else{
   52215     Pgno nextOvfl = get4byte(pDbPage->aData);
   52216     if( nextOvfl!=0 ){
   52217       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   52218       if( rc!=SQLITE_OK ){
   52219         return rc;
   52220       }
   52221     }
   52222   }
   52223 
   52224   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   52225   ** that it points at iFreePage. Also fix the pointer map entry for
   52226   ** iPtrPage.
   52227   */
   52228   if( eType!=PTRMAP_ROOTPAGE ){
   52229     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   52230     if( rc!=SQLITE_OK ){
   52231       return rc;
   52232     }
   52233     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   52234     if( rc!=SQLITE_OK ){
   52235       releasePage(pPtrPage);
   52236       return rc;
   52237     }
   52238     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   52239     releasePage(pPtrPage);
   52240     if( rc==SQLITE_OK ){
   52241       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   52242     }
   52243   }
   52244   return rc;
   52245 }
   52246 
   52247 /* Forward declaration required by incrVacuumStep(). */
   52248 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   52249 
   52250 /*
   52251 ** Perform a single step of an incremental-vacuum. If successful,
   52252 ** return SQLITE_OK. If there is no work to do (and therefore no
   52253 ** point in calling this function again), return SQLITE_DONE.
   52254 **
   52255 ** More specificly, this function attempts to re-organize the
   52256 ** database so that the last page of the file currently in use
   52257 ** is no longer in use.
   52258 **
   52259 ** If the nFin parameter is non-zero, this function assumes
   52260 ** that the caller will keep calling incrVacuumStep() until
   52261 ** it returns SQLITE_DONE or an error, and that nFin is the
   52262 ** number of pages the database file will contain after this
   52263 ** process is complete.  If nFin is zero, it is assumed that
   52264 ** incrVacuumStep() will be called a finite amount of times
   52265 ** which may or may not empty the freelist.  A full autovacuum
   52266 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
   52267 */
   52268 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
   52269   Pgno nFreeList;           /* Number of pages still on the free-list */
   52270   int rc;
   52271 
   52272   assert( sqlite3_mutex_held(pBt->mutex) );
   52273   assert( iLastPg>nFin );
   52274 
   52275   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   52276     u8 eType;
   52277     Pgno iPtrPage;
   52278 
   52279     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   52280     if( nFreeList==0 ){
   52281       return SQLITE_DONE;
   52282     }
   52283 
   52284     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   52285     if( rc!=SQLITE_OK ){
   52286       return rc;
   52287     }
   52288     if( eType==PTRMAP_ROOTPAGE ){
   52289       return SQLITE_CORRUPT_BKPT;
   52290     }
   52291 
   52292     if( eType==PTRMAP_FREEPAGE ){
   52293       if( nFin==0 ){
   52294         /* Remove the page from the files free-list. This is not required
   52295         ** if nFin is non-zero. In that case, the free-list will be
   52296         ** truncated to zero after this function returns, so it doesn't
   52297         ** matter if it still contains some garbage entries.
   52298         */
   52299         Pgno iFreePg;
   52300         MemPage *pFreePg;
   52301         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
   52302         if( rc!=SQLITE_OK ){
   52303           return rc;
   52304         }
   52305         assert( iFreePg==iLastPg );
   52306         releasePage(pFreePg);
   52307       }
   52308     } else {
   52309       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   52310       MemPage *pLastPg;
   52311 
   52312       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   52313       if( rc!=SQLITE_OK ){
   52314         return rc;
   52315       }
   52316 
   52317       /* If nFin is zero, this loop runs exactly once and page pLastPg
   52318       ** is swapped with the first free page pulled off the free list.
   52319       **
   52320       ** On the other hand, if nFin is greater than zero, then keep
   52321       ** looping until a free-page located within the first nFin pages
   52322       ** of the file is found.
   52323       */
   52324       do {
   52325         MemPage *pFreePg;
   52326         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
   52327         if( rc!=SQLITE_OK ){
   52328           releasePage(pLastPg);
   52329           return rc;
   52330         }
   52331         releasePage(pFreePg);
   52332       }while( nFin!=0 && iFreePg>nFin );
   52333       assert( iFreePg<iLastPg );
   52334 
   52335       rc = sqlite3PagerWrite(pLastPg->pDbPage);
   52336       if( rc==SQLITE_OK ){
   52337         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
   52338       }
   52339       releasePage(pLastPg);
   52340       if( rc!=SQLITE_OK ){
   52341         return rc;
   52342       }
   52343     }
   52344   }
   52345 
   52346   if( nFin==0 ){
   52347     iLastPg--;
   52348     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
   52349       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
   52350         MemPage *pPg;
   52351         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
   52352         if( rc!=SQLITE_OK ){
   52353           return rc;
   52354         }
   52355         rc = sqlite3PagerWrite(pPg->pDbPage);
   52356         releasePage(pPg);
   52357         if( rc!=SQLITE_OK ){
   52358           return rc;
   52359         }
   52360       }
   52361       iLastPg--;
   52362     }
   52363     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
   52364     pBt->nPage = iLastPg;
   52365   }
   52366   return SQLITE_OK;
   52367 }
   52368 
   52369 /*
   52370 ** A write-transaction must be opened before calling this function.
   52371 ** It performs a single unit of work towards an incremental vacuum.
   52372 **
   52373 ** If the incremental vacuum is finished after this function has run,
   52374 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   52375 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   52376 */
   52377 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   52378   int rc;
   52379   BtShared *pBt = p->pBt;
   52380 
   52381   sqlite3BtreeEnter(p);
   52382   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   52383   if( !pBt->autoVacuum ){
   52384     rc = SQLITE_DONE;
   52385   }else{
   52386     invalidateAllOverflowCache(pBt);
   52387     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
   52388     if( rc==SQLITE_OK ){
   52389       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   52390       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   52391     }
   52392   }
   52393   sqlite3BtreeLeave(p);
   52394   return rc;
   52395 }
   52396 
   52397 /*
   52398 ** This routine is called prior to sqlite3PagerCommit when a transaction
   52399 ** is commited for an auto-vacuum database.
   52400 **
   52401 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   52402 ** the database file should be truncated to during the commit process.
   52403 ** i.e. the database has been reorganized so that only the first *pnTrunc
   52404 ** pages are in use.
   52405 */
   52406 static int autoVacuumCommit(BtShared *pBt){
   52407   int rc = SQLITE_OK;
   52408   Pager *pPager = pBt->pPager;
   52409   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   52410 
   52411   assert( sqlite3_mutex_held(pBt->mutex) );
   52412   invalidateAllOverflowCache(pBt);
   52413   assert(pBt->autoVacuum);
   52414   if( !pBt->incrVacuum ){
   52415     Pgno nFin;         /* Number of pages in database after autovacuuming */
   52416     Pgno nFree;        /* Number of pages on the freelist initially */
   52417     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
   52418     Pgno iFree;        /* The next page to be freed */
   52419     int nEntry;        /* Number of entries on one ptrmap page */
   52420     Pgno nOrig;        /* Database size before freeing */
   52421 
   52422     nOrig = btreePagecount(pBt);
   52423     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   52424       /* It is not possible to create a database for which the final page
   52425       ** is either a pointer-map page or the pending-byte page. If one
   52426       ** is encountered, this indicates corruption.
   52427       */
   52428       return SQLITE_CORRUPT_BKPT;
   52429     }
   52430 
   52431     nFree = get4byte(&pBt->pPage1->aData[36]);
   52432     nEntry = pBt->usableSize/5;
   52433     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   52434     nFin = nOrig - nFree - nPtrmap;
   52435     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   52436       nFin--;
   52437     }
   52438     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   52439       nFin--;
   52440     }
   52441     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   52442 
   52443     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   52444       rc = incrVacuumStep(pBt, nFin, iFree);
   52445     }
   52446     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   52447       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   52448       put4byte(&pBt->pPage1->aData[32], 0);
   52449       put4byte(&pBt->pPage1->aData[36], 0);
   52450       put4byte(&pBt->pPage1->aData[28], nFin);
   52451       sqlite3PagerTruncateImage(pBt->pPager, nFin);
   52452       pBt->nPage = nFin;
   52453     }
   52454     if( rc!=SQLITE_OK ){
   52455       sqlite3PagerRollback(pPager);
   52456     }
   52457   }
   52458 
   52459   assert( nRef==sqlite3PagerRefcount(pPager) );
   52460   return rc;
   52461 }
   52462 
   52463 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   52464 # define setChildPtrmaps(x) SQLITE_OK
   52465 #endif
   52466 
   52467 /*
   52468 ** This routine does the first phase of a two-phase commit.  This routine
   52469 ** causes a rollback journal to be created (if it does not already exist)
   52470 ** and populated with enough information so that if a power loss occurs
   52471 ** the database can be restored to its original state by playing back
   52472 ** the journal.  Then the contents of the journal are flushed out to
   52473 ** the disk.  After the journal is safely on oxide, the changes to the
   52474 ** database are written into the database file and flushed to oxide.
   52475 ** At the end of this call, the rollback journal still exists on the
   52476 ** disk and we are still holding all locks, so the transaction has not
   52477 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   52478 ** commit process.
   52479 **
   52480 ** This call is a no-op if no write-transaction is currently active on pBt.
   52481 **
   52482 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   52483 ** the name of a master journal file that should be written into the
   52484 ** individual journal file, or is NULL, indicating no master journal file
   52485 ** (single database transaction).
   52486 **
   52487 ** When this is called, the master journal should already have been
   52488 ** created, populated with this journal pointer and synced to disk.
   52489 **
   52490 ** Once this is routine has returned, the only thing required to commit
   52491 ** the write-transaction for this database file is to delete the journal.
   52492 */
   52493 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   52494   int rc = SQLITE_OK;
   52495   if( p->inTrans==TRANS_WRITE ){
   52496     BtShared *pBt = p->pBt;
   52497     sqlite3BtreeEnter(p);
   52498 #ifndef SQLITE_OMIT_AUTOVACUUM
   52499     if( pBt->autoVacuum ){
   52500       rc = autoVacuumCommit(pBt);
   52501       if( rc!=SQLITE_OK ){
   52502         sqlite3BtreeLeave(p);
   52503         return rc;
   52504       }
   52505     }
   52506 #endif
   52507     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   52508     sqlite3BtreeLeave(p);
   52509   }
   52510   return rc;
   52511 }
   52512 
   52513 /*
   52514 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   52515 ** at the conclusion of a transaction.
   52516 */
   52517 static void btreeEndTransaction(Btree *p){
   52518   BtShared *pBt = p->pBt;
   52519   assert( sqlite3BtreeHoldsMutex(p) );
   52520 
   52521   btreeClearHasContent(pBt);
   52522   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
   52523     /* If there are other active statements that belong to this database
   52524     ** handle, downgrade to a read-only transaction. The other statements
   52525     ** may still be reading from the database.  */
   52526     downgradeAllSharedCacheTableLocks(p);
   52527     p->inTrans = TRANS_READ;
   52528   }else{
   52529     /* If the handle had any kind of transaction open, decrement the
   52530     ** transaction count of the shared btree. If the transaction count
   52531     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   52532     ** call below will unlock the pager.  */
   52533     if( p->inTrans!=TRANS_NONE ){
   52534       clearAllSharedCacheTableLocks(p);
   52535       pBt->nTransaction--;
   52536       if( 0==pBt->nTransaction ){
   52537         pBt->inTransaction = TRANS_NONE;
   52538       }
   52539     }
   52540 
   52541     /* Set the current transaction state to TRANS_NONE and unlock the
   52542     ** pager if this call closed the only read or write transaction.  */
   52543     p->inTrans = TRANS_NONE;
   52544     unlockBtreeIfUnused(pBt);
   52545   }
   52546 
   52547   btreeIntegrity(p);
   52548 }
   52549 
   52550 /*
   52551 ** Commit the transaction currently in progress.
   52552 **
   52553 ** This routine implements the second phase of a 2-phase commit.  The
   52554 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   52555 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   52556 ** routine did all the work of writing information out to disk and flushing the
   52557 ** contents so that they are written onto the disk platter.  All this
   52558 ** routine has to do is delete or truncate or zero the header in the
   52559 ** the rollback journal (which causes the transaction to commit) and
   52560 ** drop locks.
   52561 **
   52562 ** Normally, if an error occurs while the pager layer is attempting to
   52563 ** finalize the underlying journal file, this function returns an error and
   52564 ** the upper layer will attempt a rollback. However, if the second argument
   52565 ** is non-zero then this b-tree transaction is part of a multi-file
   52566 ** transaction. In this case, the transaction has already been committed
   52567 ** (by deleting a master journal file) and the caller will ignore this
   52568 ** functions return code. So, even if an error occurs in the pager layer,
   52569 ** reset the b-tree objects internal state to indicate that the write
   52570 ** transaction has been closed. This is quite safe, as the pager will have
   52571 ** transitioned to the error state.
   52572 **
   52573 ** This will release the write lock on the database file.  If there
   52574 ** are no active cursors, it also releases the read lock.
   52575 */
   52576 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   52577 
   52578   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   52579   sqlite3BtreeEnter(p);
   52580   btreeIntegrity(p);
   52581 
   52582   /* If the handle has a write-transaction open, commit the shared-btrees
   52583   ** transaction and set the shared state to TRANS_READ.
   52584   */
   52585   if( p->inTrans==TRANS_WRITE ){
   52586     int rc;
   52587     BtShared *pBt = p->pBt;
   52588     assert( pBt->inTransaction==TRANS_WRITE );
   52589     assert( pBt->nTransaction>0 );
   52590     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   52591     if( rc!=SQLITE_OK && bCleanup==0 ){
   52592       sqlite3BtreeLeave(p);
   52593       return rc;
   52594     }
   52595     pBt->inTransaction = TRANS_READ;
   52596   }
   52597 
   52598   btreeEndTransaction(p);
   52599   sqlite3BtreeLeave(p);
   52600   return SQLITE_OK;
   52601 }
   52602 
   52603 /*
   52604 ** Do both phases of a commit.
   52605 */
   52606 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   52607   int rc;
   52608   sqlite3BtreeEnter(p);
   52609   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   52610   if( rc==SQLITE_OK ){
   52611     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
   52612   }
   52613   sqlite3BtreeLeave(p);
   52614   return rc;
   52615 }
   52616 
   52617 #ifndef NDEBUG
   52618 /*
   52619 ** Return the number of write-cursors open on this handle. This is for use
   52620 ** in assert() expressions, so it is only compiled if NDEBUG is not
   52621 ** defined.
   52622 **
   52623 ** For the purposes of this routine, a write-cursor is any cursor that
   52624 ** is capable of writing to the databse.  That means the cursor was
   52625 ** originally opened for writing and the cursor has not be disabled
   52626 ** by having its state changed to CURSOR_FAULT.
   52627 */
   52628 static int countWriteCursors(BtShared *pBt){
   52629   BtCursor *pCur;
   52630   int r = 0;
   52631   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   52632     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
   52633   }
   52634   return r;
   52635 }
   52636 #endif
   52637 
   52638 /*
   52639 ** This routine sets the state to CURSOR_FAULT and the error
   52640 ** code to errCode for every cursor on BtShared that pBtree
   52641 ** references.
   52642 **
   52643 ** Every cursor is tripped, including cursors that belong
   52644 ** to other database connections that happen to be sharing
   52645 ** the cache with pBtree.
   52646 **
   52647 ** This routine gets called when a rollback occurs.
   52648 ** All cursors using the same cache must be tripped
   52649 ** to prevent them from trying to use the btree after
   52650 ** the rollback.  The rollback may have deleted tables
   52651 ** or moved root pages, so it is not sufficient to
   52652 ** save the state of the cursor.  The cursor must be
   52653 ** invalidated.
   52654 */
   52655 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   52656   BtCursor *p;
   52657   if( pBtree==0 ) return;
   52658   sqlite3BtreeEnter(pBtree);
   52659   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   52660     int i;
   52661     sqlite3BtreeClearCursor(p);
   52662     p->eState = CURSOR_FAULT;
   52663     p->skipNext = errCode;
   52664     for(i=0; i<=p->iPage; i++){
   52665       releasePage(p->apPage[i]);
   52666       p->apPage[i] = 0;
   52667     }
   52668   }
   52669   sqlite3BtreeLeave(pBtree);
   52670 }
   52671 
   52672 /*
   52673 ** Rollback the transaction in progress.  All cursors will be
   52674 ** invalided by this operation.  Any attempt to use a cursor
   52675 ** that was open at the beginning of this operation will result
   52676 ** in an error.
   52677 **
   52678 ** This will release the write lock on the database file.  If there
   52679 ** are no active cursors, it also releases the read lock.
   52680 */
   52681 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
   52682   int rc;
   52683   BtShared *pBt = p->pBt;
   52684   MemPage *pPage1;
   52685 
   52686   sqlite3BtreeEnter(p);
   52687   if( tripCode==SQLITE_OK ){
   52688     rc = tripCode = saveAllCursors(pBt, 0, 0);
   52689   }else{
   52690     rc = SQLITE_OK;
   52691   }
   52692   if( tripCode ){
   52693     sqlite3BtreeTripAllCursors(p, tripCode);
   52694   }
   52695   btreeIntegrity(p);
   52696 
   52697   if( p->inTrans==TRANS_WRITE ){
   52698     int rc2;
   52699 
   52700     assert( TRANS_WRITE==pBt->inTransaction );
   52701     rc2 = sqlite3PagerRollback(pBt->pPager);
   52702     if( rc2!=SQLITE_OK ){
   52703       rc = rc2;
   52704     }
   52705 
   52706     /* The rollback may have destroyed the pPage1->aData value.  So
   52707     ** call btreeGetPage() on page 1 again to make
   52708     ** sure pPage1->aData is set correctly. */
   52709     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   52710       int nPage = get4byte(28+(u8*)pPage1->aData);
   52711       testcase( nPage==0 );
   52712       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   52713       testcase( pBt->nPage!=nPage );
   52714       pBt->nPage = nPage;
   52715       releasePage(pPage1);
   52716     }
   52717     assert( countWriteCursors(pBt)==0 );
   52718     pBt->inTransaction = TRANS_READ;
   52719   }
   52720 
   52721   btreeEndTransaction(p);
   52722   sqlite3BtreeLeave(p);
   52723   return rc;
   52724 }
   52725 
   52726 /*
   52727 ** Start a statement subtransaction. The subtransaction can can be rolled
   52728 ** back independently of the main transaction. You must start a transaction
   52729 ** before starting a subtransaction. The subtransaction is ended automatically
   52730 ** if the main transaction commits or rolls back.
   52731 **
   52732 ** Statement subtransactions are used around individual SQL statements
   52733 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   52734 ** error occurs within the statement, the effect of that one statement
   52735 ** can be rolled back without having to rollback the entire transaction.
   52736 **
   52737 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   52738 ** value passed as the second parameter is the total number of savepoints,
   52739 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   52740 ** are no active savepoints and no other statement-transactions open,
   52741 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   52742 ** using the sqlite3BtreeSavepoint() function.
   52743 */
   52744 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   52745   int rc;
   52746   BtShared *pBt = p->pBt;
   52747   sqlite3BtreeEnter(p);
   52748   assert( p->inTrans==TRANS_WRITE );
   52749   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   52750   assert( iStatement>0 );
   52751   assert( iStatement>p->db->nSavepoint );
   52752   assert( pBt->inTransaction==TRANS_WRITE );
   52753   /* At the pager level, a statement transaction is a savepoint with
   52754   ** an index greater than all savepoints created explicitly using
   52755   ** SQL statements. It is illegal to open, release or rollback any
   52756   ** such savepoints while the statement transaction savepoint is active.
   52757   */
   52758   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   52759   sqlite3BtreeLeave(p);
   52760   return rc;
   52761 }
   52762 
   52763 /*
   52764 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   52765 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   52766 ** savepoint identified by parameter iSavepoint, depending on the value
   52767 ** of op.
   52768 **
   52769 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   52770 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   52771 ** contents of the entire transaction are rolled back. This is different
   52772 ** from a normal transaction rollback, as no locks are released and the
   52773 ** transaction remains open.
   52774 */
   52775 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   52776   int rc = SQLITE_OK;
   52777   if( p && p->inTrans==TRANS_WRITE ){
   52778     BtShared *pBt = p->pBt;
   52779     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   52780     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   52781     sqlite3BtreeEnter(p);
   52782     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   52783     if( rc==SQLITE_OK ){
   52784       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
   52785         pBt->nPage = 0;
   52786       }
   52787       rc = newDatabase(pBt);
   52788       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   52789 
   52790       /* The database size was written into the offset 28 of the header
   52791       ** when the transaction started, so we know that the value at offset
   52792       ** 28 is nonzero. */
   52793       assert( pBt->nPage>0 );
   52794     }
   52795     sqlite3BtreeLeave(p);
   52796   }
   52797   return rc;
   52798 }
   52799 
   52800 /*
   52801 ** Create a new cursor for the BTree whose root is on the page
   52802 ** iTable. If a read-only cursor is requested, it is assumed that
   52803 ** the caller already has at least a read-only transaction open
   52804 ** on the database already. If a write-cursor is requested, then
   52805 ** the caller is assumed to have an open write transaction.
   52806 **
   52807 ** If wrFlag==0, then the cursor can only be used for reading.
   52808 ** If wrFlag==1, then the cursor can be used for reading or for
   52809 ** writing if other conditions for writing are also met.  These
   52810 ** are the conditions that must be met in order for writing to
   52811 ** be allowed:
   52812 **
   52813 ** 1:  The cursor must have been opened with wrFlag==1
   52814 **
   52815 ** 2:  Other database connections that share the same pager cache
   52816 **     but which are not in the READ_UNCOMMITTED state may not have
   52817 **     cursors open with wrFlag==0 on the same table.  Otherwise
   52818 **     the changes made by this write cursor would be visible to
   52819 **     the read cursors in the other database connection.
   52820 **
   52821 ** 3:  The database must be writable (not on read-only media)
   52822 **
   52823 ** 4:  There must be an active transaction.
   52824 **
   52825 ** No checking is done to make sure that page iTable really is the
   52826 ** root page of a b-tree.  If it is not, then the cursor acquired
   52827 ** will not work correctly.
   52828 **
   52829 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   52830 ** on pCur to initialize the memory space prior to invoking this routine.
   52831 */
   52832 static int btreeCursor(
   52833   Btree *p,                              /* The btree */
   52834   int iTable,                            /* Root page of table to open */
   52835   int wrFlag,                            /* 1 to write. 0 read-only */
   52836   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   52837   BtCursor *pCur                         /* Space for new cursor */
   52838 ){
   52839   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   52840 
   52841   assert( sqlite3BtreeHoldsMutex(p) );
   52842   assert( wrFlag==0 || wrFlag==1 );
   52843 
   52844   /* The following assert statements verify that if this is a sharable
   52845   ** b-tree database, the connection is holding the required table locks,
   52846   ** and that no other connection has any open cursor that conflicts with
   52847   ** this lock.  */
   52848   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   52849   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   52850 
   52851   /* Assert that the caller has opened the required transaction. */
   52852   assert( p->inTrans>TRANS_NONE );
   52853   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   52854   assert( pBt->pPage1 && pBt->pPage1->aData );
   52855 
   52856   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
   52857     return SQLITE_READONLY;
   52858   }
   52859   if( iTable==1 && btreePagecount(pBt)==0 ){
   52860     assert( wrFlag==0 );
   52861     iTable = 0;
   52862   }
   52863 
   52864   /* Now that no other errors can occur, finish filling in the BtCursor
   52865   ** variables and link the cursor into the BtShared list.  */
   52866   pCur->pgnoRoot = (Pgno)iTable;
   52867   pCur->iPage = -1;
   52868   pCur->pKeyInfo = pKeyInfo;
   52869   pCur->pBtree = p;
   52870   pCur->pBt = pBt;
   52871   pCur->wrFlag = (u8)wrFlag;
   52872   pCur->pNext = pBt->pCursor;
   52873   if( pCur->pNext ){
   52874     pCur->pNext->pPrev = pCur;
   52875   }
   52876   pBt->pCursor = pCur;
   52877   pCur->eState = CURSOR_INVALID;
   52878   pCur->cachedRowid = 0;
   52879   return SQLITE_OK;
   52880 }
   52881 SQLITE_PRIVATE int sqlite3BtreeCursor(
   52882   Btree *p,                                   /* The btree */
   52883   int iTable,                                 /* Root page of table to open */
   52884   int wrFlag,                                 /* 1 to write. 0 read-only */
   52885   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   52886   BtCursor *pCur                              /* Write new cursor here */
   52887 ){
   52888   int rc;
   52889   sqlite3BtreeEnter(p);
   52890   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   52891   sqlite3BtreeLeave(p);
   52892   return rc;
   52893 }
   52894 
   52895 /*
   52896 ** Return the size of a BtCursor object in bytes.
   52897 **
   52898 ** This interfaces is needed so that users of cursors can preallocate
   52899 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   52900 ** to users so they cannot do the sizeof() themselves - they must call
   52901 ** this routine.
   52902 */
   52903 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   52904   return ROUND8(sizeof(BtCursor));
   52905 }
   52906 
   52907 /*
   52908 ** Initialize memory that will be converted into a BtCursor object.
   52909 **
   52910 ** The simple approach here would be to memset() the entire object
   52911 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   52912 ** do not need to be zeroed and they are large, so we can save a lot
   52913 ** of run-time by skipping the initialization of those elements.
   52914 */
   52915 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   52916   memset(p, 0, offsetof(BtCursor, iPage));
   52917 }
   52918 
   52919 /*
   52920 ** Set the cached rowid value of every cursor in the same database file
   52921 ** as pCur and having the same root page number as pCur.  The value is
   52922 ** set to iRowid.
   52923 **
   52924 ** Only positive rowid values are considered valid for this cache.
   52925 ** The cache is initialized to zero, indicating an invalid cache.
   52926 ** A btree will work fine with zero or negative rowids.  We just cannot
   52927 ** cache zero or negative rowids, which means tables that use zero or
   52928 ** negative rowids might run a little slower.  But in practice, zero
   52929 ** or negative rowids are very uncommon so this should not be a problem.
   52930 */
   52931 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
   52932   BtCursor *p;
   52933   for(p=pCur->pBt->pCursor; p; p=p->pNext){
   52934     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
   52935   }
   52936   assert( pCur->cachedRowid==iRowid );
   52937 }
   52938 
   52939 /*
   52940 ** Return the cached rowid for the given cursor.  A negative or zero
   52941 ** return value indicates that the rowid cache is invalid and should be
   52942 ** ignored.  If the rowid cache has never before been set, then a
   52943 ** zero is returned.
   52944 */
   52945 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
   52946   return pCur->cachedRowid;
   52947 }
   52948 
   52949 /*
   52950 ** Close a cursor.  The read lock on the database file is released
   52951 ** when the last cursor is closed.
   52952 */
   52953 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   52954   Btree *pBtree = pCur->pBtree;
   52955   if( pBtree ){
   52956     int i;
   52957     BtShared *pBt = pCur->pBt;
   52958     sqlite3BtreeEnter(pBtree);
   52959     sqlite3BtreeClearCursor(pCur);
   52960     if( pCur->pPrev ){
   52961       pCur->pPrev->pNext = pCur->pNext;
   52962     }else{
   52963       pBt->pCursor = pCur->pNext;
   52964     }
   52965     if( pCur->pNext ){
   52966       pCur->pNext->pPrev = pCur->pPrev;
   52967     }
   52968     for(i=0; i<=pCur->iPage; i++){
   52969       releasePage(pCur->apPage[i]);
   52970     }
   52971     unlockBtreeIfUnused(pBt);
   52972     invalidateOverflowCache(pCur);
   52973     /* sqlite3_free(pCur); */
   52974     sqlite3BtreeLeave(pBtree);
   52975   }
   52976   return SQLITE_OK;
   52977 }
   52978 
   52979 /*
   52980 ** Make sure the BtCursor* given in the argument has a valid
   52981 ** BtCursor.info structure.  If it is not already valid, call
   52982 ** btreeParseCell() to fill it in.
   52983 **
   52984 ** BtCursor.info is a cache of the information in the current cell.
   52985 ** Using this cache reduces the number of calls to btreeParseCell().
   52986 **
   52987 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   52988 ** compiler to crash when getCellInfo() is implemented as a macro.
   52989 ** But there is a measureable speed advantage to using the macro on gcc
   52990 ** (when less compiler optimizations like -Os or -O0 are used and the
   52991 ** compiler is not doing agressive inlining.)  So we use a real function
   52992 ** for MSVC and a macro for everything else.  Ticket #2457.
   52993 */
   52994 #ifndef NDEBUG
   52995   static void assertCellInfo(BtCursor *pCur){
   52996     CellInfo info;
   52997     int iPage = pCur->iPage;
   52998     memset(&info, 0, sizeof(info));
   52999     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   53000     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
   53001   }
   53002 #else
   53003   #define assertCellInfo(x)
   53004 #endif
   53005 #ifdef _MSC_VER
   53006   /* Use a real function in MSVC to work around bugs in that compiler. */
   53007   static void getCellInfo(BtCursor *pCur){
   53008     if( pCur->info.nSize==0 ){
   53009       int iPage = pCur->iPage;
   53010       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   53011       pCur->validNKey = 1;
   53012     }else{
   53013       assertCellInfo(pCur);
   53014     }
   53015   }
   53016 #else /* if not _MSC_VER */
   53017   /* Use a macro in all other compilers so that the function is inlined */
   53018 #define getCellInfo(pCur)                                                      \
   53019   if( pCur->info.nSize==0 ){                                                   \
   53020     int iPage = pCur->iPage;                                                   \
   53021     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
   53022     pCur->validNKey = 1;                                                       \
   53023   }else{                                                                       \
   53024     assertCellInfo(pCur);                                                      \
   53025   }
   53026 #endif /* _MSC_VER */
   53027 
   53028 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   53029 /*
   53030 ** Return true if the given BtCursor is valid.  A valid cursor is one
   53031 ** that is currently pointing to a row in a (non-empty) table.
   53032 ** This is a verification routine is used only within assert() statements.
   53033 */
   53034 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   53035   return pCur && pCur->eState==CURSOR_VALID;
   53036 }
   53037 #endif /* NDEBUG */
   53038 
   53039 /*
   53040 ** Set *pSize to the size of the buffer needed to hold the value of
   53041 ** the key for the current entry.  If the cursor is not pointing
   53042 ** to a valid entry, *pSize is set to 0.
   53043 **
   53044 ** For a table with the INTKEY flag set, this routine returns the key
   53045 ** itself, not the number of bytes in the key.
   53046 **
   53047 ** The caller must position the cursor prior to invoking this routine.
   53048 **
   53049 ** This routine cannot fail.  It always returns SQLITE_OK.
   53050 */
   53051 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   53052   assert( cursorHoldsMutex(pCur) );
   53053   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   53054   if( pCur->eState!=CURSOR_VALID ){
   53055     *pSize = 0;
   53056   }else{
   53057     getCellInfo(pCur);
   53058     *pSize = pCur->info.nKey;
   53059   }
   53060   return SQLITE_OK;
   53061 }
   53062 
   53063 /*
   53064 ** Set *pSize to the number of bytes of data in the entry the
   53065 ** cursor currently points to.
   53066 **
   53067 ** The caller must guarantee that the cursor is pointing to a non-NULL
   53068 ** valid entry.  In other words, the calling procedure must guarantee
   53069 ** that the cursor has Cursor.eState==CURSOR_VALID.
   53070 **
   53071 ** Failure is not possible.  This function always returns SQLITE_OK.
   53072 ** It might just as well be a procedure (returning void) but we continue
   53073 ** to return an integer result code for historical reasons.
   53074 */
   53075 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   53076   assert( cursorHoldsMutex(pCur) );
   53077   assert( pCur->eState==CURSOR_VALID );
   53078   getCellInfo(pCur);
   53079   *pSize = pCur->info.nData;
   53080   return SQLITE_OK;
   53081 }
   53082 
   53083 /*
   53084 ** Given the page number of an overflow page in the database (parameter
   53085 ** ovfl), this function finds the page number of the next page in the
   53086 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   53087 ** pointer-map data instead of reading the content of page ovfl to do so.
   53088 **
   53089 ** If an error occurs an SQLite error code is returned. Otherwise:
   53090 **
   53091 ** The page number of the next overflow page in the linked list is
   53092 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   53093 ** list, *pPgnoNext is set to zero.
   53094 **
   53095 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   53096 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   53097 ** reference. It is the responsibility of the caller to call releasePage()
   53098 ** on *ppPage to free the reference. In no reference was obtained (because
   53099 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   53100 ** *ppPage is set to zero.
   53101 */
   53102 static int getOverflowPage(
   53103   BtShared *pBt,               /* The database file */
   53104   Pgno ovfl,                   /* Current overflow page number */
   53105   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   53106   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   53107 ){
   53108   Pgno next = 0;
   53109   MemPage *pPage = 0;
   53110   int rc = SQLITE_OK;
   53111 
   53112   assert( sqlite3_mutex_held(pBt->mutex) );
   53113   assert(pPgnoNext);
   53114 
   53115 #ifndef SQLITE_OMIT_AUTOVACUUM
   53116   /* Try to find the next page in the overflow list using the
   53117   ** autovacuum pointer-map pages. Guess that the next page in
   53118   ** the overflow list is page number (ovfl+1). If that guess turns
   53119   ** out to be wrong, fall back to loading the data of page
   53120   ** number ovfl to determine the next page number.
   53121   */
   53122   if( pBt->autoVacuum ){
   53123     Pgno pgno;
   53124     Pgno iGuess = ovfl+1;
   53125     u8 eType;
   53126 
   53127     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   53128       iGuess++;
   53129     }
   53130 
   53131     if( iGuess<=btreePagecount(pBt) ){
   53132       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   53133       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   53134         next = iGuess;
   53135         rc = SQLITE_DONE;
   53136       }
   53137     }
   53138   }
   53139 #endif
   53140 
   53141   assert( next==0 || rc==SQLITE_DONE );
   53142   if( rc==SQLITE_OK ){
   53143     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
   53144     assert( rc==SQLITE_OK || pPage==0 );
   53145     if( rc==SQLITE_OK ){
   53146       next = get4byte(pPage->aData);
   53147     }
   53148   }
   53149 
   53150   *pPgnoNext = next;
   53151   if( ppPage ){
   53152     *ppPage = pPage;
   53153   }else{
   53154     releasePage(pPage);
   53155   }
   53156   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   53157 }
   53158 
   53159 /*
   53160 ** Copy data from a buffer to a page, or from a page to a buffer.
   53161 **
   53162 ** pPayload is a pointer to data stored on database page pDbPage.
   53163 ** If argument eOp is false, then nByte bytes of data are copied
   53164 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   53165 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   53166 ** of data are copied from the buffer pBuf to pPayload.
   53167 **
   53168 ** SQLITE_OK is returned on success, otherwise an error code.
   53169 */
   53170 static int copyPayload(
   53171   void *pPayload,           /* Pointer to page data */
   53172   void *pBuf,               /* Pointer to buffer */
   53173   int nByte,                /* Number of bytes to copy */
   53174   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   53175   DbPage *pDbPage           /* Page containing pPayload */
   53176 ){
   53177   if( eOp ){
   53178     /* Copy data from buffer to page (a write operation) */
   53179     int rc = sqlite3PagerWrite(pDbPage);
   53180     if( rc!=SQLITE_OK ){
   53181       return rc;
   53182     }
   53183     memcpy(pPayload, pBuf, nByte);
   53184   }else{
   53185     /* Copy data from page to buffer (a read operation) */
   53186     memcpy(pBuf, pPayload, nByte);
   53187   }
   53188   return SQLITE_OK;
   53189 }
   53190 
   53191 /*
   53192 ** This function is used to read or overwrite payload information
   53193 ** for the entry that the pCur cursor is pointing to. If the eOp
   53194 ** parameter is 0, this is a read operation (data copied into
   53195 ** buffer pBuf). If it is non-zero, a write (data copied from
   53196 ** buffer pBuf).
   53197 **
   53198 ** A total of "amt" bytes are read or written beginning at "offset".
   53199 ** Data is read to or from the buffer pBuf.
   53200 **
   53201 ** The content being read or written might appear on the main page
   53202 ** or be scattered out on multiple overflow pages.
   53203 **
   53204 ** If the BtCursor.isIncrblobHandle flag is set, and the current
   53205 ** cursor entry uses one or more overflow pages, this function
   53206 ** allocates space for and lazily popluates the overflow page-list
   53207 ** cache array (BtCursor.aOverflow). Subsequent calls use this
   53208 ** cache to make seeking to the supplied offset more efficient.
   53209 **
   53210 ** Once an overflow page-list cache has been allocated, it may be
   53211 ** invalidated if some other cursor writes to the same table, or if
   53212 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   53213 ** mode, the following events may invalidate an overflow page-list cache.
   53214 **
   53215 **   * An incremental vacuum,
   53216 **   * A commit in auto_vacuum="full" mode,
   53217 **   * Creating a table (may require moving an overflow page).
   53218 */
   53219 static int accessPayload(
   53220   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   53221   u32 offset,          /* Begin reading this far into payload */
   53222   u32 amt,             /* Read this many bytes */
   53223   unsigned char *pBuf, /* Write the bytes into this buffer */
   53224   int eOp              /* zero to read. non-zero to write. */
   53225 ){
   53226   unsigned char *aPayload;
   53227   int rc = SQLITE_OK;
   53228   u32 nKey;
   53229   int iIdx = 0;
   53230   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   53231   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   53232 
   53233   assert( pPage );
   53234   assert( pCur->eState==CURSOR_VALID );
   53235   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53236   assert( cursorHoldsMutex(pCur) );
   53237 
   53238   getCellInfo(pCur);
   53239   aPayload = pCur->info.pCell + pCur->info.nHeader;
   53240   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   53241 
   53242   if( NEVER(offset+amt > nKey+pCur->info.nData)
   53243    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   53244   ){
   53245     /* Trying to read or write past the end of the data is an error */
   53246     return SQLITE_CORRUPT_BKPT;
   53247   }
   53248 
   53249   /* Check if data must be read/written to/from the btree page itself. */
   53250   if( offset<pCur->info.nLocal ){
   53251     int a = amt;
   53252     if( a+offset>pCur->info.nLocal ){
   53253       a = pCur->info.nLocal - offset;
   53254     }
   53255     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
   53256     offset = 0;
   53257     pBuf += a;
   53258     amt -= a;
   53259   }else{
   53260     offset -= pCur->info.nLocal;
   53261   }
   53262 
   53263   if( rc==SQLITE_OK && amt>0 ){
   53264     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   53265     Pgno nextPage;
   53266 
   53267     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   53268 
   53269 #ifndef SQLITE_OMIT_INCRBLOB
   53270     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
   53271     ** has not been allocated, allocate it now. The array is sized at
   53272     ** one entry for each overflow page in the overflow chain. The
   53273     ** page number of the first overflow page is stored in aOverflow[0],
   53274     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
   53275     ** (the cache is lazily populated).
   53276     */
   53277     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
   53278       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   53279       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
   53280       /* nOvfl is always positive.  If it were zero, fetchPayload would have
   53281       ** been used instead of this routine. */
   53282       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
   53283         rc = SQLITE_NOMEM;
   53284       }
   53285     }
   53286 
   53287     /* If the overflow page-list cache has been allocated and the
   53288     ** entry for the first required overflow page is valid, skip
   53289     ** directly to it.
   53290     */
   53291     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
   53292       iIdx = (offset/ovflSize);
   53293       nextPage = pCur->aOverflow[iIdx];
   53294       offset = (offset%ovflSize);
   53295     }
   53296 #endif
   53297 
   53298     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   53299 
   53300 #ifndef SQLITE_OMIT_INCRBLOB
   53301       /* If required, populate the overflow page-list cache. */
   53302       if( pCur->aOverflow ){
   53303         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   53304         pCur->aOverflow[iIdx] = nextPage;
   53305       }
   53306 #endif
   53307 
   53308       if( offset>=ovflSize ){
   53309         /* The only reason to read this page is to obtain the page
   53310         ** number for the next page in the overflow chain. The page
   53311         ** data is not required. So first try to lookup the overflow
   53312         ** page-list cache, if any, then fall back to the getOverflowPage()
   53313         ** function.
   53314         */
   53315 #ifndef SQLITE_OMIT_INCRBLOB
   53316         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
   53317           nextPage = pCur->aOverflow[iIdx+1];
   53318         } else
   53319 #endif
   53320           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   53321         offset -= ovflSize;
   53322       }else{
   53323         /* Need to read this page properly. It contains some of the
   53324         ** range of data that is being read (eOp==0) or written (eOp!=0).
   53325         */
   53326 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   53327         sqlite3_file *fd;
   53328 #endif
   53329         int a = amt;
   53330         if( a + offset > ovflSize ){
   53331           a = ovflSize - offset;
   53332         }
   53333 
   53334 #ifdef SQLITE_DIRECT_OVERFLOW_READ
   53335         /* If all the following are true:
   53336         **
   53337         **   1) this is a read operation, and
   53338         **   2) data is required from the start of this overflow page, and
   53339         **   3) the database is file-backed, and
   53340         **   4) there is no open write-transaction, and
   53341         **   5) the database is not a WAL database,
   53342         **
   53343         ** then data can be read directly from the database file into the
   53344         ** output buffer, bypassing the page-cache altogether. This speeds
   53345         ** up loading large records that span many overflow pages.
   53346         */
   53347         if( eOp==0                                             /* (1) */
   53348          && offset==0                                          /* (2) */
   53349          && pBt->inTransaction==TRANS_READ                     /* (4) */
   53350          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
   53351          && pBt->pPage1->aData[19]==0x01                       /* (5) */
   53352         ){
   53353           u8 aSave[4];
   53354           u8 *aWrite = &pBuf[-4];
   53355           memcpy(aSave, aWrite, 4);
   53356           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
   53357           nextPage = get4byte(aWrite);
   53358           memcpy(aWrite, aSave, 4);
   53359         }else
   53360 #endif
   53361 
   53362         {
   53363           DbPage *pDbPage;
   53364           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
   53365           if( rc==SQLITE_OK ){
   53366             aPayload = sqlite3PagerGetData(pDbPage);
   53367             nextPage = get4byte(aPayload);
   53368             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
   53369             sqlite3PagerUnref(pDbPage);
   53370             offset = 0;
   53371           }
   53372         }
   53373         amt -= a;
   53374         pBuf += a;
   53375       }
   53376     }
   53377   }
   53378 
   53379   if( rc==SQLITE_OK && amt>0 ){
   53380     return SQLITE_CORRUPT_BKPT;
   53381   }
   53382   return rc;
   53383 }
   53384 
   53385 /*
   53386 ** Read part of the key associated with cursor pCur.  Exactly
   53387 ** "amt" bytes will be transfered into pBuf[].  The transfer
   53388 ** begins at "offset".
   53389 **
   53390 ** The caller must ensure that pCur is pointing to a valid row
   53391 ** in the table.
   53392 **
   53393 ** Return SQLITE_OK on success or an error code if anything goes
   53394 ** wrong.  An error is returned if "offset+amt" is larger than
   53395 ** the available payload.
   53396 */
   53397 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   53398   assert( cursorHoldsMutex(pCur) );
   53399   assert( pCur->eState==CURSOR_VALID );
   53400   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   53401   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   53402   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   53403 }
   53404 
   53405 /*
   53406 ** Read part of the data associated with cursor pCur.  Exactly
   53407 ** "amt" bytes will be transfered into pBuf[].  The transfer
   53408 ** begins at "offset".
   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 sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   53415   int rc;
   53416 
   53417 #ifndef SQLITE_OMIT_INCRBLOB
   53418   if ( pCur->eState==CURSOR_INVALID ){
   53419     return SQLITE_ABORT;
   53420   }
   53421 #endif
   53422 
   53423   assert( cursorHoldsMutex(pCur) );
   53424   rc = restoreCursorPosition(pCur);
   53425   if( rc==SQLITE_OK ){
   53426     assert( pCur->eState==CURSOR_VALID );
   53427     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   53428     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   53429     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   53430   }
   53431   return rc;
   53432 }
   53433 
   53434 /*
   53435 ** Return a pointer to payload information from the entry that the
   53436 ** pCur cursor is pointing to.  The pointer is to the beginning of
   53437 ** the key if skipKey==0 and it points to the beginning of data if
   53438 ** skipKey==1.  The number of bytes of available key/data is written
   53439 ** into *pAmt.  If *pAmt==0, then the value returned will not be
   53440 ** a valid pointer.
   53441 **
   53442 ** This routine is an optimization.  It is common for the entire key
   53443 ** and data to fit on the local page and for there to be no overflow
   53444 ** pages.  When that is so, this routine can be used to access the
   53445 ** key and data without making a copy.  If the key and/or data spills
   53446 ** onto overflow pages, then accessPayload() must be used to reassemble
   53447 ** the key/data and copy it into a preallocated buffer.
   53448 **
   53449 ** The pointer returned by this routine looks directly into the cached
   53450 ** page of the database.  The data might change or move the next time
   53451 ** any btree routine is called.
   53452 */
   53453 static const unsigned char *fetchPayload(
   53454   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   53455   int *pAmt,           /* Write the number of available bytes here */
   53456   int skipKey          /* read beginning at data if this is true */
   53457 ){
   53458   unsigned char *aPayload;
   53459   MemPage *pPage;
   53460   u32 nKey;
   53461   u32 nLocal;
   53462 
   53463   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   53464   assert( pCur->eState==CURSOR_VALID );
   53465   assert( cursorHoldsMutex(pCur) );
   53466   pPage = pCur->apPage[pCur->iPage];
   53467   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53468   if( NEVER(pCur->info.nSize==0) ){
   53469     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
   53470                    &pCur->info);
   53471   }
   53472   aPayload = pCur->info.pCell;
   53473   aPayload += pCur->info.nHeader;
   53474   if( pPage->intKey ){
   53475     nKey = 0;
   53476   }else{
   53477     nKey = (int)pCur->info.nKey;
   53478   }
   53479   if( skipKey ){
   53480     aPayload += nKey;
   53481     nLocal = pCur->info.nLocal - nKey;
   53482   }else{
   53483     nLocal = pCur->info.nLocal;
   53484     assert( nLocal<=nKey );
   53485   }
   53486   *pAmt = nLocal;
   53487   return aPayload;
   53488 }
   53489 
   53490 
   53491 /*
   53492 ** For the entry that cursor pCur is point to, return as
   53493 ** many bytes of the key or data as are available on the local
   53494 ** b-tree page.  Write the number of available bytes into *pAmt.
   53495 **
   53496 ** The pointer returned is ephemeral.  The key/data may move
   53497 ** or be destroyed on the next call to any Btree routine,
   53498 ** including calls from other threads against the same cache.
   53499 ** Hence, a mutex on the BtShared should be held prior to calling
   53500 ** this routine.
   53501 **
   53502 ** These routines is used to get quick access to key and data
   53503 ** in the common case where no overflow pages are used.
   53504 */
   53505 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
   53506   const void *p = 0;
   53507   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53508   assert( cursorHoldsMutex(pCur) );
   53509   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   53510     p = (const void*)fetchPayload(pCur, pAmt, 0);
   53511   }
   53512   return p;
   53513 }
   53514 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
   53515   const void *p = 0;
   53516   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53517   assert( cursorHoldsMutex(pCur) );
   53518   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   53519     p = (const void*)fetchPayload(pCur, pAmt, 1);
   53520   }
   53521   return p;
   53522 }
   53523 
   53524 
   53525 /*
   53526 ** Move the cursor down to a new child page.  The newPgno argument is the
   53527 ** page number of the child page to move to.
   53528 **
   53529 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   53530 ** the new child page does not match the flags field of the parent (i.e.
   53531 ** if an intkey page appears to be the parent of a non-intkey page, or
   53532 ** vice-versa).
   53533 */
   53534 static int moveToChild(BtCursor *pCur, u32 newPgno){
   53535   int rc;
   53536   int i = pCur->iPage;
   53537   MemPage *pNewPage;
   53538   BtShared *pBt = pCur->pBt;
   53539 
   53540   assert( cursorHoldsMutex(pCur) );
   53541   assert( pCur->eState==CURSOR_VALID );
   53542   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   53543   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   53544     return SQLITE_CORRUPT_BKPT;
   53545   }
   53546   rc = getAndInitPage(pBt, newPgno, &pNewPage);
   53547   if( rc ) return rc;
   53548   pCur->apPage[i+1] = pNewPage;
   53549   pCur->aiIdx[i+1] = 0;
   53550   pCur->iPage++;
   53551 
   53552   pCur->info.nSize = 0;
   53553   pCur->validNKey = 0;
   53554   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   53555     return SQLITE_CORRUPT_BKPT;
   53556   }
   53557   return SQLITE_OK;
   53558 }
   53559 
   53560 #if 0
   53561 /*
   53562 ** Page pParent is an internal (non-leaf) tree page. This function
   53563 ** asserts that page number iChild is the left-child if the iIdx'th
   53564 ** cell in page pParent. Or, if iIdx is equal to the total number of
   53565 ** cells in pParent, that page number iChild is the right-child of
   53566 ** the page.
   53567 */
   53568 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   53569   assert( iIdx<=pParent->nCell );
   53570   if( iIdx==pParent->nCell ){
   53571     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   53572   }else{
   53573     assert( get4byte(findCell(pParent, iIdx))==iChild );
   53574   }
   53575 }
   53576 #else
   53577 #  define assertParentIndex(x,y,z)
   53578 #endif
   53579 
   53580 /*
   53581 ** Move the cursor up to the parent page.
   53582 **
   53583 ** pCur->idx is set to the cell index that contains the pointer
   53584 ** to the page we are coming from.  If we are coming from the
   53585 ** right-most child page then pCur->idx is set to one more than
   53586 ** the largest cell index.
   53587 */
   53588 static void moveToParent(BtCursor *pCur){
   53589   assert( cursorHoldsMutex(pCur) );
   53590   assert( pCur->eState==CURSOR_VALID );
   53591   assert( pCur->iPage>0 );
   53592   assert( pCur->apPage[pCur->iPage] );
   53593 
   53594   /* UPDATE: It is actually possible for the condition tested by the assert
   53595   ** below to be untrue if the database file is corrupt. This can occur if
   53596   ** one cursor has modified page pParent while a reference to it is held
   53597   ** by a second cursor. Which can only happen if a single page is linked
   53598   ** into more than one b-tree structure in a corrupt database.  */
   53599 #if 0
   53600   assertParentIndex(
   53601     pCur->apPage[pCur->iPage-1],
   53602     pCur->aiIdx[pCur->iPage-1],
   53603     pCur->apPage[pCur->iPage]->pgno
   53604   );
   53605 #endif
   53606   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
   53607 
   53608   releasePage(pCur->apPage[pCur->iPage]);
   53609   pCur->iPage--;
   53610   pCur->info.nSize = 0;
   53611   pCur->validNKey = 0;
   53612 }
   53613 
   53614 /*
   53615 ** Move the cursor to point to the root page of its b-tree structure.
   53616 **
   53617 ** If the table has a virtual root page, then the cursor is moved to point
   53618 ** to the virtual root page instead of the actual root page. A table has a
   53619 ** virtual root page when the actual root page contains no cells and a
   53620 ** single child page. This can only happen with the table rooted at page 1.
   53621 **
   53622 ** If the b-tree structure is empty, the cursor state is set to
   53623 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   53624 ** cell located on the root (or virtual root) page and the cursor state
   53625 ** is set to CURSOR_VALID.
   53626 **
   53627 ** If this function returns successfully, it may be assumed that the
   53628 ** page-header flags indicate that the [virtual] root-page is the expected
   53629 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   53630 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   53631 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   53632 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   53633 ** b-tree).
   53634 */
   53635 static int moveToRoot(BtCursor *pCur){
   53636   MemPage *pRoot;
   53637   int rc = SQLITE_OK;
   53638   Btree *p = pCur->pBtree;
   53639   BtShared *pBt = p->pBt;
   53640 
   53641   assert( cursorHoldsMutex(pCur) );
   53642   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   53643   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   53644   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   53645   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   53646     if( pCur->eState==CURSOR_FAULT ){
   53647       assert( pCur->skipNext!=SQLITE_OK );
   53648       return pCur->skipNext;
   53649     }
   53650     sqlite3BtreeClearCursor(pCur);
   53651   }
   53652 
   53653   if( pCur->iPage>=0 ){
   53654     int i;
   53655     for(i=1; i<=pCur->iPage; i++){
   53656       releasePage(pCur->apPage[i]);
   53657     }
   53658     pCur->iPage = 0;
   53659   }else if( pCur->pgnoRoot==0 ){
   53660     pCur->eState = CURSOR_INVALID;
   53661     return SQLITE_OK;
   53662   }else{
   53663     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
   53664     if( rc!=SQLITE_OK ){
   53665       pCur->eState = CURSOR_INVALID;
   53666       return rc;
   53667     }
   53668     pCur->iPage = 0;
   53669 
   53670     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   53671     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   53672     ** NULL, the caller expects a table b-tree. If this is not the case,
   53673     ** return an SQLITE_CORRUPT error.  */
   53674     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
   53675     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
   53676       return SQLITE_CORRUPT_BKPT;
   53677     }
   53678   }
   53679 
   53680   /* Assert that the root page is of the correct type. This must be the
   53681   ** case as the call to this function that loaded the root-page (either
   53682   ** this call or a previous invocation) would have detected corruption
   53683   ** if the assumption were not true, and it is not possible for the flags
   53684   ** byte to have been modified while this cursor is holding a reference
   53685   ** to the page.  */
   53686   pRoot = pCur->apPage[0];
   53687   assert( pRoot->pgno==pCur->pgnoRoot );
   53688   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
   53689 
   53690   pCur->aiIdx[0] = 0;
   53691   pCur->info.nSize = 0;
   53692   pCur->atLast = 0;
   53693   pCur->validNKey = 0;
   53694 
   53695   if( pRoot->nCell==0 && !pRoot->leaf ){
   53696     Pgno subpage;
   53697     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   53698     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   53699     pCur->eState = CURSOR_VALID;
   53700     rc = moveToChild(pCur, subpage);
   53701   }else{
   53702     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
   53703   }
   53704   return rc;
   53705 }
   53706 
   53707 /*
   53708 ** Move the cursor down to the left-most leaf entry beneath the
   53709 ** entry to which it is currently pointing.
   53710 **
   53711 ** The left-most leaf is the one with the smallest key - the first
   53712 ** in ascending order.
   53713 */
   53714 static int moveToLeftmost(BtCursor *pCur){
   53715   Pgno pgno;
   53716   int rc = SQLITE_OK;
   53717   MemPage *pPage;
   53718 
   53719   assert( cursorHoldsMutex(pCur) );
   53720   assert( pCur->eState==CURSOR_VALID );
   53721   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   53722     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   53723     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   53724     rc = moveToChild(pCur, pgno);
   53725   }
   53726   return rc;
   53727 }
   53728 
   53729 /*
   53730 ** Move the cursor down to the right-most leaf entry beneath the
   53731 ** page to which it is currently pointing.  Notice the difference
   53732 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   53733 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   53734 ** finds the right-most entry beneath the *page*.
   53735 **
   53736 ** The right-most entry is the one with the largest key - the last
   53737 ** key in ascending order.
   53738 */
   53739 static int moveToRightmost(BtCursor *pCur){
   53740   Pgno pgno;
   53741   int rc = SQLITE_OK;
   53742   MemPage *pPage = 0;
   53743 
   53744   assert( cursorHoldsMutex(pCur) );
   53745   assert( pCur->eState==CURSOR_VALID );
   53746   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   53747     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   53748     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   53749     rc = moveToChild(pCur, pgno);
   53750   }
   53751   if( rc==SQLITE_OK ){
   53752     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   53753     pCur->info.nSize = 0;
   53754     pCur->validNKey = 0;
   53755   }
   53756   return rc;
   53757 }
   53758 
   53759 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   53760 ** on success.  Set *pRes to 0 if the cursor actually points to something
   53761 ** or set *pRes to 1 if the table is empty.
   53762 */
   53763 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   53764   int rc;
   53765 
   53766   assert( cursorHoldsMutex(pCur) );
   53767   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53768   rc = moveToRoot(pCur);
   53769   if( rc==SQLITE_OK ){
   53770     if( pCur->eState==CURSOR_INVALID ){
   53771       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53772       *pRes = 1;
   53773     }else{
   53774       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   53775       *pRes = 0;
   53776       rc = moveToLeftmost(pCur);
   53777     }
   53778   }
   53779   return rc;
   53780 }
   53781 
   53782 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   53783 ** on success.  Set *pRes to 0 if the cursor actually points to something
   53784 ** or set *pRes to 1 if the table is empty.
   53785 */
   53786 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   53787   int rc;
   53788 
   53789   assert( cursorHoldsMutex(pCur) );
   53790   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53791 
   53792   /* If the cursor already points to the last entry, this is a no-op. */
   53793   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
   53794 #ifdef SQLITE_DEBUG
   53795     /* This block serves to assert() that the cursor really does point
   53796     ** to the last entry in the b-tree. */
   53797     int ii;
   53798     for(ii=0; ii<pCur->iPage; ii++){
   53799       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   53800     }
   53801     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   53802     assert( pCur->apPage[pCur->iPage]->leaf );
   53803 #endif
   53804     return SQLITE_OK;
   53805   }
   53806 
   53807   rc = moveToRoot(pCur);
   53808   if( rc==SQLITE_OK ){
   53809     if( CURSOR_INVALID==pCur->eState ){
   53810       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53811       *pRes = 1;
   53812     }else{
   53813       assert( pCur->eState==CURSOR_VALID );
   53814       *pRes = 0;
   53815       rc = moveToRightmost(pCur);
   53816       pCur->atLast = rc==SQLITE_OK ?1:0;
   53817     }
   53818   }
   53819   return rc;
   53820 }
   53821 
   53822 /* Move the cursor so that it points to an entry near the key
   53823 ** specified by pIdxKey or intKey.   Return a success code.
   53824 **
   53825 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   53826 ** must be NULL.  For index tables, pIdxKey is used and intKey
   53827 ** is ignored.
   53828 **
   53829 ** If an exact match is not found, then the cursor is always
   53830 ** left pointing at a leaf page which would hold the entry if it
   53831 ** were present.  The cursor might point to an entry that comes
   53832 ** before or after the key.
   53833 **
   53834 ** An integer is written into *pRes which is the result of
   53835 ** comparing the key with the entry to which the cursor is
   53836 ** pointing.  The meaning of the integer written into
   53837 ** *pRes is as follows:
   53838 **
   53839 **     *pRes<0      The cursor is left pointing at an entry that
   53840 **                  is smaller than intKey/pIdxKey or if the table is empty
   53841 **                  and the cursor is therefore left point to nothing.
   53842 **
   53843 **     *pRes==0     The cursor is left pointing at an entry that
   53844 **                  exactly matches intKey/pIdxKey.
   53845 **
   53846 **     *pRes>0      The cursor is left pointing at an entry that
   53847 **                  is larger than intKey/pIdxKey.
   53848 **
   53849 */
   53850 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   53851   BtCursor *pCur,          /* The cursor to be moved */
   53852   UnpackedRecord *pIdxKey, /* Unpacked index key */
   53853   i64 intKey,              /* The table key */
   53854   int biasRight,           /* If true, bias the search to the high end */
   53855   int *pRes                /* Write search results here */
   53856 ){
   53857   int rc;
   53858 
   53859   assert( cursorHoldsMutex(pCur) );
   53860   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53861   assert( pRes );
   53862   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   53863 
   53864   /* If the cursor is already positioned at the point we are trying
   53865   ** to move to, then just return without doing any work */
   53866   if( pCur->eState==CURSOR_VALID && pCur->validNKey
   53867    && pCur->apPage[0]->intKey
   53868   ){
   53869     if( pCur->info.nKey==intKey ){
   53870       *pRes = 0;
   53871       return SQLITE_OK;
   53872     }
   53873     if( pCur->atLast && pCur->info.nKey<intKey ){
   53874       *pRes = -1;
   53875       return SQLITE_OK;
   53876     }
   53877   }
   53878 
   53879   rc = moveToRoot(pCur);
   53880   if( rc ){
   53881     return rc;
   53882   }
   53883   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
   53884   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
   53885   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
   53886   if( pCur->eState==CURSOR_INVALID ){
   53887     *pRes = -1;
   53888     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
   53889     return SQLITE_OK;
   53890   }
   53891   assert( pCur->apPage[0]->intKey || pIdxKey );
   53892   for(;;){
   53893     int lwr, upr, idx;
   53894     Pgno chldPg;
   53895     MemPage *pPage = pCur->apPage[pCur->iPage];
   53896     int c;
   53897 
   53898     /* pPage->nCell must be greater than zero. If this is the root-page
   53899     ** the cursor would have been INVALID above and this for(;;) loop
   53900     ** not run. If this is not the root-page, then the moveToChild() routine
   53901     ** would have already detected db corruption. Similarly, pPage must
   53902     ** be the right kind (index or table) of b-tree page. Otherwise
   53903     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   53904     assert( pPage->nCell>0 );
   53905     assert( pPage->intKey==(pIdxKey==0) );
   53906     lwr = 0;
   53907     upr = pPage->nCell-1;
   53908     if( biasRight ){
   53909       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
   53910     }else{
   53911       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
   53912     }
   53913     for(;;){
   53914       u8 *pCell;                          /* Pointer to current cell in pPage */
   53915 
   53916       assert( idx==pCur->aiIdx[pCur->iPage] );
   53917       pCur->info.nSize = 0;
   53918       pCell = findCell(pPage, idx) + pPage->childPtrSize;
   53919       if( pPage->intKey ){
   53920         i64 nCellKey;
   53921         if( pPage->hasData ){
   53922           u32 dummy;
   53923           pCell += getVarint32(pCell, dummy);
   53924         }
   53925         getVarint(pCell, (u64*)&nCellKey);
   53926         if( nCellKey==intKey ){
   53927           c = 0;
   53928         }else if( nCellKey<intKey ){
   53929           c = -1;
   53930         }else{
   53931           assert( nCellKey>intKey );
   53932           c = +1;
   53933         }
   53934         pCur->validNKey = 1;
   53935         pCur->info.nKey = nCellKey;
   53936       }else{
   53937         /* The maximum supported page-size is 65536 bytes. This means that
   53938         ** the maximum number of record bytes stored on an index B-Tree
   53939         ** page is less than 16384 bytes and may be stored as a 2-byte
   53940         ** varint. This information is used to attempt to avoid parsing
   53941         ** the entire cell by checking for the cases where the record is
   53942         ** stored entirely within the b-tree page by inspecting the first
   53943         ** 2 bytes of the cell.
   53944         */
   53945         int nCell = pCell[0];
   53946         if( nCell<=pPage->max1bytePayload
   53947          /* && (pCell+nCell)<pPage->aDataEnd */
   53948         ){
   53949           /* This branch runs if the record-size field of the cell is a
   53950           ** single byte varint and the record fits entirely on the main
   53951           ** b-tree page.  */
   53952           testcase( pCell+nCell+1==pPage->aDataEnd );
   53953           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
   53954         }else if( !(pCell[1] & 0x80)
   53955           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   53956           /* && (pCell+nCell+2)<=pPage->aDataEnd */
   53957         ){
   53958           /* The record-size field is a 2 byte varint and the record
   53959           ** fits entirely on the main b-tree page.  */
   53960           testcase( pCell+nCell+2==pPage->aDataEnd );
   53961           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
   53962         }else{
   53963           /* The record flows over onto one or more overflow pages. In
   53964           ** this case the whole cell needs to be parsed, a buffer allocated
   53965           ** and accessPayload() used to retrieve the record into the
   53966           ** buffer before VdbeRecordCompare() can be called. */
   53967           void *pCellKey;
   53968           u8 * const pCellBody = pCell - pPage->childPtrSize;
   53969           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   53970           nCell = (int)pCur->info.nKey;
   53971           pCellKey = sqlite3Malloc( nCell );
   53972           if( pCellKey==0 ){
   53973             rc = SQLITE_NOMEM;
   53974             goto moveto_finish;
   53975           }
   53976           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
   53977           if( rc ){
   53978             sqlite3_free(pCellKey);
   53979             goto moveto_finish;
   53980           }
   53981           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
   53982           sqlite3_free(pCellKey);
   53983         }
   53984       }
   53985       if( c==0 ){
   53986         if( pPage->intKey && !pPage->leaf ){
   53987           lwr = idx;
   53988           break;
   53989         }else{
   53990           *pRes = 0;
   53991           rc = SQLITE_OK;
   53992           goto moveto_finish;
   53993         }
   53994       }
   53995       if( c<0 ){
   53996         lwr = idx+1;
   53997       }else{
   53998         upr = idx-1;
   53999       }
   54000       if( lwr>upr ){
   54001         break;
   54002       }
   54003       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
   54004     }
   54005     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
   54006     assert( pPage->isInit );
   54007     if( pPage->leaf ){
   54008       chldPg = 0;
   54009     }else if( lwr>=pPage->nCell ){
   54010       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   54011     }else{
   54012       chldPg = get4byte(findCell(pPage, lwr));
   54013     }
   54014     if( chldPg==0 ){
   54015       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   54016       *pRes = c;
   54017       rc = SQLITE_OK;
   54018       goto moveto_finish;
   54019     }
   54020     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   54021     pCur->info.nSize = 0;
   54022     pCur->validNKey = 0;
   54023     rc = moveToChild(pCur, chldPg);
   54024     if( rc ) goto moveto_finish;
   54025   }
   54026 moveto_finish:
   54027   return rc;
   54028 }
   54029 
   54030 
   54031 /*
   54032 ** Return TRUE if the cursor is not pointing at an entry of the table.
   54033 **
   54034 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   54035 ** past the last entry in the table or sqlite3BtreePrev() moves past
   54036 ** the first entry.  TRUE is also returned if the table is empty.
   54037 */
   54038 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   54039   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   54040   ** have been deleted? This API will need to change to return an error code
   54041   ** as well as the boolean result value.
   54042   */
   54043   return (CURSOR_VALID!=pCur->eState);
   54044 }
   54045 
   54046 /*
   54047 ** Advance the cursor to the next entry in the database.  If
   54048 ** successful then set *pRes=0.  If the cursor
   54049 ** was already pointing to the last entry in the database before
   54050 ** this routine was called, then set *pRes=1.
   54051 */
   54052 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   54053   int rc;
   54054   int idx;
   54055   MemPage *pPage;
   54056 
   54057   assert( cursorHoldsMutex(pCur) );
   54058   rc = restoreCursorPosition(pCur);
   54059   if( rc!=SQLITE_OK ){
   54060     return rc;
   54061   }
   54062   assert( pRes!=0 );
   54063   if( CURSOR_INVALID==pCur->eState ){
   54064     *pRes = 1;
   54065     return SQLITE_OK;
   54066   }
   54067   if( pCur->skipNext>0 ){
   54068     pCur->skipNext = 0;
   54069     *pRes = 0;
   54070     return SQLITE_OK;
   54071   }
   54072   pCur->skipNext = 0;
   54073 
   54074   pPage = pCur->apPage[pCur->iPage];
   54075   idx = ++pCur->aiIdx[pCur->iPage];
   54076   assert( pPage->isInit );
   54077 
   54078   /* If the database file is corrupt, it is possible for the value of idx
   54079   ** to be invalid here. This can only occur if a second cursor modifies
   54080   ** the page while cursor pCur is holding a reference to it. Which can
   54081   ** only happen if the database is corrupt in such a way as to link the
   54082   ** page into more than one b-tree structure. */
   54083   testcase( idx>pPage->nCell );
   54084 
   54085   pCur->info.nSize = 0;
   54086   pCur->validNKey = 0;
   54087   if( idx>=pPage->nCell ){
   54088     if( !pPage->leaf ){
   54089       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   54090       if( rc ) return rc;
   54091       rc = moveToLeftmost(pCur);
   54092       *pRes = 0;
   54093       return rc;
   54094     }
   54095     do{
   54096       if( pCur->iPage==0 ){
   54097         *pRes = 1;
   54098         pCur->eState = CURSOR_INVALID;
   54099         return SQLITE_OK;
   54100       }
   54101       moveToParent(pCur);
   54102       pPage = pCur->apPage[pCur->iPage];
   54103     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   54104     *pRes = 0;
   54105     if( pPage->intKey ){
   54106       rc = sqlite3BtreeNext(pCur, pRes);
   54107     }else{
   54108       rc = SQLITE_OK;
   54109     }
   54110     return rc;
   54111   }
   54112   *pRes = 0;
   54113   if( pPage->leaf ){
   54114     return SQLITE_OK;
   54115   }
   54116   rc = moveToLeftmost(pCur);
   54117   return rc;
   54118 }
   54119 
   54120 
   54121 /*
   54122 ** Step the cursor to the back to the previous entry in the database.  If
   54123 ** successful then set *pRes=0.  If the cursor
   54124 ** was already pointing to the first entry in the database before
   54125 ** this routine was called, then set *pRes=1.
   54126 */
   54127 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   54128   int rc;
   54129   MemPage *pPage;
   54130 
   54131   assert( cursorHoldsMutex(pCur) );
   54132   rc = restoreCursorPosition(pCur);
   54133   if( rc!=SQLITE_OK ){
   54134     return rc;
   54135   }
   54136   pCur->atLast = 0;
   54137   if( CURSOR_INVALID==pCur->eState ){
   54138     *pRes = 1;
   54139     return SQLITE_OK;
   54140   }
   54141   if( pCur->skipNext<0 ){
   54142     pCur->skipNext = 0;
   54143     *pRes = 0;
   54144     return SQLITE_OK;
   54145   }
   54146   pCur->skipNext = 0;
   54147 
   54148   pPage = pCur->apPage[pCur->iPage];
   54149   assert( pPage->isInit );
   54150   if( !pPage->leaf ){
   54151     int idx = pCur->aiIdx[pCur->iPage];
   54152     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   54153     if( rc ){
   54154       return rc;
   54155     }
   54156     rc = moveToRightmost(pCur);
   54157   }else{
   54158     while( pCur->aiIdx[pCur->iPage]==0 ){
   54159       if( pCur->iPage==0 ){
   54160         pCur->eState = CURSOR_INVALID;
   54161         *pRes = 1;
   54162         return SQLITE_OK;
   54163       }
   54164       moveToParent(pCur);
   54165     }
   54166     pCur->info.nSize = 0;
   54167     pCur->validNKey = 0;
   54168 
   54169     pCur->aiIdx[pCur->iPage]--;
   54170     pPage = pCur->apPage[pCur->iPage];
   54171     if( pPage->intKey && !pPage->leaf ){
   54172       rc = sqlite3BtreePrevious(pCur, pRes);
   54173     }else{
   54174       rc = SQLITE_OK;
   54175     }
   54176   }
   54177   *pRes = 0;
   54178   return rc;
   54179 }
   54180 
   54181 /*
   54182 ** Allocate a new page from the database file.
   54183 **
   54184 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   54185 ** has already been called on the new page.)  The new page has also
   54186 ** been referenced and the calling routine is responsible for calling
   54187 ** sqlite3PagerUnref() on the new page when it is done.
   54188 **
   54189 ** SQLITE_OK is returned on success.  Any other return value indicates
   54190 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   54191 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   54192 **
   54193 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
   54194 ** locate a page close to the page number "nearby".  This can be used in an
   54195 ** attempt to keep related pages close to each other in the database file,
   54196 ** which in turn can make database access faster.
   54197 **
   54198 ** If the "exact" parameter is not 0, and the page-number nearby exists
   54199 ** anywhere on the free-list, then it is guarenteed to be returned. This
   54200 ** is only used by auto-vacuum databases when allocating a new table.
   54201 */
   54202 static int allocateBtreePage(
   54203   BtShared *pBt,
   54204   MemPage **ppPage,
   54205   Pgno *pPgno,
   54206   Pgno nearby,
   54207   u8 exact
   54208 ){
   54209   MemPage *pPage1;
   54210   int rc;
   54211   u32 n;     /* Number of pages on the freelist */
   54212   u32 k;     /* Number of leaves on the trunk of the freelist */
   54213   MemPage *pTrunk = 0;
   54214   MemPage *pPrevTrunk = 0;
   54215   Pgno mxPage;     /* Total size of the database file */
   54216 
   54217   assert( sqlite3_mutex_held(pBt->mutex) );
   54218   pPage1 = pBt->pPage1;
   54219   mxPage = btreePagecount(pBt);
   54220   n = get4byte(&pPage1->aData[36]);
   54221   testcase( n==mxPage-1 );
   54222   if( n>=mxPage ){
   54223     return SQLITE_CORRUPT_BKPT;
   54224   }
   54225   if( n>0 ){
   54226     /* There are pages on the freelist.  Reuse one of those pages. */
   54227     Pgno iTrunk;
   54228     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   54229 
   54230     /* If the 'exact' parameter was true and a query of the pointer-map
   54231     ** shows that the page 'nearby' is somewhere on the free-list, then
   54232     ** the entire-list will be searched for that page.
   54233     */
   54234 #ifndef SQLITE_OMIT_AUTOVACUUM
   54235     if( exact && nearby<=mxPage ){
   54236       u8 eType;
   54237       assert( nearby>0 );
   54238       assert( pBt->autoVacuum );
   54239       rc = ptrmapGet(pBt, nearby, &eType, 0);
   54240       if( rc ) return rc;
   54241       if( eType==PTRMAP_FREEPAGE ){
   54242         searchList = 1;
   54243       }
   54244       *pPgno = nearby;
   54245     }
   54246 #endif
   54247 
   54248     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   54249     ** first free-list trunk page. iPrevTrunk is initially 1.
   54250     */
   54251     rc = sqlite3PagerWrite(pPage1->pDbPage);
   54252     if( rc ) return rc;
   54253     put4byte(&pPage1->aData[36], n-1);
   54254 
   54255     /* The code within this loop is run only once if the 'searchList' variable
   54256     ** is not true. Otherwise, it runs once for each trunk-page on the
   54257     ** free-list until the page 'nearby' is located.
   54258     */
   54259     do {
   54260       pPrevTrunk = pTrunk;
   54261       if( pPrevTrunk ){
   54262         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   54263       }else{
   54264         iTrunk = get4byte(&pPage1->aData[32]);
   54265       }
   54266       testcase( iTrunk==mxPage );
   54267       if( iTrunk>mxPage ){
   54268         rc = SQLITE_CORRUPT_BKPT;
   54269       }else{
   54270         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   54271       }
   54272       if( rc ){
   54273         pTrunk = 0;
   54274         goto end_allocate_page;
   54275       }
   54276       assert( pTrunk!=0 );
   54277       assert( pTrunk->aData!=0 );
   54278 
   54279       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
   54280       if( k==0 && !searchList ){
   54281         /* The trunk has no leaves and the list is not being searched.
   54282         ** So extract the trunk page itself and use it as the newly
   54283         ** allocated page */
   54284         assert( pPrevTrunk==0 );
   54285         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54286         if( rc ){
   54287           goto end_allocate_page;
   54288         }
   54289         *pPgno = iTrunk;
   54290         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   54291         *ppPage = pTrunk;
   54292         pTrunk = 0;
   54293         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   54294       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   54295         /* Value of k is out of range.  Database corruption */
   54296         rc = SQLITE_CORRUPT_BKPT;
   54297         goto end_allocate_page;
   54298 #ifndef SQLITE_OMIT_AUTOVACUUM
   54299       }else if( searchList && nearby==iTrunk ){
   54300         /* The list is being searched and this trunk page is the page
   54301         ** to allocate, regardless of whether it has leaves.
   54302         */
   54303         assert( *pPgno==iTrunk );
   54304         *ppPage = pTrunk;
   54305         searchList = 0;
   54306         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54307         if( rc ){
   54308           goto end_allocate_page;
   54309         }
   54310         if( k==0 ){
   54311           if( !pPrevTrunk ){
   54312             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   54313           }else{
   54314             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   54315             if( rc!=SQLITE_OK ){
   54316               goto end_allocate_page;
   54317             }
   54318             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   54319           }
   54320         }else{
   54321           /* The trunk page is required by the caller but it contains
   54322           ** pointers to free-list leaves. The first leaf becomes a trunk
   54323           ** page in this case.
   54324           */
   54325           MemPage *pNewTrunk;
   54326           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   54327           if( iNewTrunk>mxPage ){
   54328             rc = SQLITE_CORRUPT_BKPT;
   54329             goto end_allocate_page;
   54330           }
   54331           testcase( iNewTrunk==mxPage );
   54332           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   54333           if( rc!=SQLITE_OK ){
   54334             goto end_allocate_page;
   54335           }
   54336           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   54337           if( rc!=SQLITE_OK ){
   54338             releasePage(pNewTrunk);
   54339             goto end_allocate_page;
   54340           }
   54341           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   54342           put4byte(&pNewTrunk->aData[4], k-1);
   54343           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   54344           releasePage(pNewTrunk);
   54345           if( !pPrevTrunk ){
   54346             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   54347             put4byte(&pPage1->aData[32], iNewTrunk);
   54348           }else{
   54349             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   54350             if( rc ){
   54351               goto end_allocate_page;
   54352             }
   54353             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   54354           }
   54355         }
   54356         pTrunk = 0;
   54357         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   54358 #endif
   54359       }else if( k>0 ){
   54360         /* Extract a leaf from the trunk */
   54361         u32 closest;
   54362         Pgno iPage;
   54363         unsigned char *aData = pTrunk->aData;
   54364         if( nearby>0 ){
   54365           u32 i;
   54366           int dist;
   54367           closest = 0;
   54368           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
   54369           for(i=1; i<k; i++){
   54370             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
   54371             if( d2<dist ){
   54372               closest = i;
   54373               dist = d2;
   54374             }
   54375           }
   54376         }else{
   54377           closest = 0;
   54378         }
   54379 
   54380         iPage = get4byte(&aData[8+closest*4]);
   54381         testcase( iPage==mxPage );
   54382         if( iPage>mxPage ){
   54383           rc = SQLITE_CORRUPT_BKPT;
   54384           goto end_allocate_page;
   54385         }
   54386         testcase( iPage==mxPage );
   54387         if( !searchList || iPage==nearby ){
   54388           int noContent;
   54389           *pPgno = iPage;
   54390           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   54391                  ": %d more free pages\n",
   54392                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   54393           rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54394           if( rc ) goto end_allocate_page;
   54395           if( closest<k-1 ){
   54396             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   54397           }
   54398           put4byte(&aData[4], k-1);
   54399           noContent = !btreeGetHasContent(pBt, *pPgno);
   54400           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   54401           if( rc==SQLITE_OK ){
   54402             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   54403             if( rc!=SQLITE_OK ){
   54404               releasePage(*ppPage);
   54405             }
   54406           }
   54407           searchList = 0;
   54408         }
   54409       }
   54410       releasePage(pPrevTrunk);
   54411       pPrevTrunk = 0;
   54412     }while( searchList );
   54413   }else{
   54414     /* There are no pages on the freelist, so create a new page at the
   54415     ** end of the file */
   54416     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   54417     if( rc ) return rc;
   54418     pBt->nPage++;
   54419     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   54420 
   54421 #ifndef SQLITE_OMIT_AUTOVACUUM
   54422     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   54423       /* If *pPgno refers to a pointer-map page, allocate two new pages
   54424       ** at the end of the file instead of one. The first allocated page
   54425       ** becomes a new pointer-map page, the second is used by the caller.
   54426       */
   54427       MemPage *pPg = 0;
   54428       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   54429       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   54430       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
   54431       if( rc==SQLITE_OK ){
   54432         rc = sqlite3PagerWrite(pPg->pDbPage);
   54433         releasePage(pPg);
   54434       }
   54435       if( rc ) return rc;
   54436       pBt->nPage++;
   54437       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   54438     }
   54439 #endif
   54440     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   54441     *pPgno = pBt->nPage;
   54442 
   54443     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   54444     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
   54445     if( rc ) return rc;
   54446     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   54447     if( rc!=SQLITE_OK ){
   54448       releasePage(*ppPage);
   54449     }
   54450     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   54451   }
   54452 
   54453   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   54454 
   54455 end_allocate_page:
   54456   releasePage(pTrunk);
   54457   releasePage(pPrevTrunk);
   54458   if( rc==SQLITE_OK ){
   54459     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   54460       releasePage(*ppPage);
   54461       return SQLITE_CORRUPT_BKPT;
   54462     }
   54463     (*ppPage)->isInit = 0;
   54464   }else{
   54465     *ppPage = 0;
   54466   }
   54467   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
   54468   return rc;
   54469 }
   54470 
   54471 /*
   54472 ** This function is used to add page iPage to the database file free-list.
   54473 ** It is assumed that the page is not already a part of the free-list.
   54474 **
   54475 ** The value passed as the second argument to this function is optional.
   54476 ** If the caller happens to have a pointer to the MemPage object
   54477 ** corresponding to page iPage handy, it may pass it as the second value.
   54478 ** Otherwise, it may pass NULL.
   54479 **
   54480 ** If a pointer to a MemPage object is passed as the second argument,
   54481 ** its reference count is not altered by this function.
   54482 */
   54483 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   54484   MemPage *pTrunk = 0;                /* Free-list trunk page */
   54485   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   54486   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   54487   MemPage *pPage;                     /* Page being freed. May be NULL. */
   54488   int rc;                             /* Return Code */
   54489   int nFree;                          /* Initial number of pages on free-list */
   54490 
   54491   assert( sqlite3_mutex_held(pBt->mutex) );
   54492   assert( iPage>1 );
   54493   assert( !pMemPage || pMemPage->pgno==iPage );
   54494 
   54495   if( pMemPage ){
   54496     pPage = pMemPage;
   54497     sqlite3PagerRef(pPage->pDbPage);
   54498   }else{
   54499     pPage = btreePageLookup(pBt, iPage);
   54500   }
   54501 
   54502   /* Increment the free page count on pPage1 */
   54503   rc = sqlite3PagerWrite(pPage1->pDbPage);
   54504   if( rc ) goto freepage_out;
   54505   nFree = get4byte(&pPage1->aData[36]);
   54506   put4byte(&pPage1->aData[36], nFree+1);
   54507 
   54508   if( pBt->btsFlags & BTS_SECURE_DELETE ){
   54509     /* If the secure_delete option is enabled, then
   54510     ** always fully overwrite deleted information with zeros.
   54511     */
   54512     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   54513      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   54514     ){
   54515       goto freepage_out;
   54516     }
   54517     memset(pPage->aData, 0, pPage->pBt->pageSize);
   54518   }
   54519 
   54520   /* If the database supports auto-vacuum, write an entry in the pointer-map
   54521   ** to indicate that the page is free.
   54522   */
   54523   if( ISAUTOVACUUM ){
   54524     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   54525     if( rc ) goto freepage_out;
   54526   }
   54527 
   54528   /* Now manipulate the actual database free-list structure. There are two
   54529   ** possibilities. If the free-list is currently empty, or if the first
   54530   ** trunk page in the free-list is full, then this page will become a
   54531   ** new free-list trunk page. Otherwise, it will become a leaf of the
   54532   ** first trunk page in the current free-list. This block tests if it
   54533   ** is possible to add the page as a new free-list leaf.
   54534   */
   54535   if( nFree!=0 ){
   54536     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   54537 
   54538     iTrunk = get4byte(&pPage1->aData[32]);
   54539     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   54540     if( rc!=SQLITE_OK ){
   54541       goto freepage_out;
   54542     }
   54543 
   54544     nLeaf = get4byte(&pTrunk->aData[4]);
   54545     assert( pBt->usableSize>32 );
   54546     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   54547       rc = SQLITE_CORRUPT_BKPT;
   54548       goto freepage_out;
   54549     }
   54550     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   54551       /* In this case there is room on the trunk page to insert the page
   54552       ** being freed as a new leaf.
   54553       **
   54554       ** Note that the trunk page is not really full until it contains
   54555       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   54556       ** coded.  But due to a coding error in versions of SQLite prior to
   54557       ** 3.6.0, databases with freelist trunk pages holding more than
   54558       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   54559       ** to maintain backwards compatibility with older versions of SQLite,
   54560       ** we will continue to restrict the number of entries to usableSize/4 - 8
   54561       ** for now.  At some point in the future (once everyone has upgraded
   54562       ** to 3.6.0 or later) we should consider fixing the conditional above
   54563       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   54564       */
   54565       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   54566       if( rc==SQLITE_OK ){
   54567         put4byte(&pTrunk->aData[4], nLeaf+1);
   54568         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   54569         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
   54570           sqlite3PagerDontWrite(pPage->pDbPage);
   54571         }
   54572         rc = btreeSetHasContent(pBt, iPage);
   54573       }
   54574       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   54575       goto freepage_out;
   54576     }
   54577   }
   54578 
   54579   /* If control flows to this point, then it was not possible to add the
   54580   ** the page being freed as a leaf page of the first trunk in the free-list.
   54581   ** Possibly because the free-list is empty, or possibly because the
   54582   ** first trunk in the free-list is full. Either way, the page being freed
   54583   ** will become the new first trunk page in the free-list.
   54584   */
   54585   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   54586     goto freepage_out;
   54587   }
   54588   rc = sqlite3PagerWrite(pPage->pDbPage);
   54589   if( rc!=SQLITE_OK ){
   54590     goto freepage_out;
   54591   }
   54592   put4byte(pPage->aData, iTrunk);
   54593   put4byte(&pPage->aData[4], 0);
   54594   put4byte(&pPage1->aData[32], iPage);
   54595   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   54596 
   54597 freepage_out:
   54598   if( pPage ){
   54599     pPage->isInit = 0;
   54600   }
   54601   releasePage(pPage);
   54602   releasePage(pTrunk);
   54603   return rc;
   54604 }
   54605 static void freePage(MemPage *pPage, int *pRC){
   54606   if( (*pRC)==SQLITE_OK ){
   54607     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   54608   }
   54609 }
   54610 
   54611 /*
   54612 ** Free any overflow pages associated with the given Cell.
   54613 */
   54614 static int clearCell(MemPage *pPage, unsigned char *pCell){
   54615   BtShared *pBt = pPage->pBt;
   54616   CellInfo info;
   54617   Pgno ovflPgno;
   54618   int rc;
   54619   int nOvfl;
   54620   u32 ovflPageSize;
   54621 
   54622   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54623   btreeParseCellPtr(pPage, pCell, &info);
   54624   if( info.iOverflow==0 ){
   54625     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   54626   }
   54627   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
   54628     return SQLITE_CORRUPT;  /* Cell extends past end of page */
   54629   }
   54630   ovflPgno = get4byte(&pCell[info.iOverflow]);
   54631   assert( pBt->usableSize > 4 );
   54632   ovflPageSize = pBt->usableSize - 4;
   54633   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   54634   assert( ovflPgno==0 || nOvfl>0 );
   54635   while( nOvfl-- ){
   54636     Pgno iNext = 0;
   54637     MemPage *pOvfl = 0;
   54638     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   54639       /* 0 is not a legal page number and page 1 cannot be an
   54640       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   54641       ** file the database must be corrupt. */
   54642       return SQLITE_CORRUPT_BKPT;
   54643     }
   54644     if( nOvfl ){
   54645       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   54646       if( rc ) return rc;
   54647     }
   54648 
   54649     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   54650      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   54651     ){
   54652       /* There is no reason any cursor should have an outstanding reference
   54653       ** to an overflow page belonging to a cell that is being deleted/updated.
   54654       ** So if there exists more than one reference to this page, then it
   54655       ** must not really be an overflow page and the database must be corrupt.
   54656       ** It is helpful to detect this before calling freePage2(), as
   54657       ** freePage2() may zero the page contents if secure-delete mode is
   54658       ** enabled. If this 'overflow' page happens to be a page that the
   54659       ** caller is iterating through or using in some other way, this
   54660       ** can be problematic.
   54661       */
   54662       rc = SQLITE_CORRUPT_BKPT;
   54663     }else{
   54664       rc = freePage2(pBt, pOvfl, ovflPgno);
   54665     }
   54666 
   54667     if( pOvfl ){
   54668       sqlite3PagerUnref(pOvfl->pDbPage);
   54669     }
   54670     if( rc ) return rc;
   54671     ovflPgno = iNext;
   54672   }
   54673   return SQLITE_OK;
   54674 }
   54675 
   54676 /*
   54677 ** Create the byte sequence used to represent a cell on page pPage
   54678 ** and write that byte sequence into pCell[].  Overflow pages are
   54679 ** allocated and filled in as necessary.  The calling procedure
   54680 ** is responsible for making sure sufficient space has been allocated
   54681 ** for pCell[].
   54682 **
   54683 ** Note that pCell does not necessary need to point to the pPage->aData
   54684 ** area.  pCell might point to some temporary storage.  The cell will
   54685 ** be constructed in this temporary area then copied into pPage->aData
   54686 ** later.
   54687 */
   54688 static int fillInCell(
   54689   MemPage *pPage,                /* The page that contains the cell */
   54690   unsigned char *pCell,          /* Complete text of the cell */
   54691   const void *pKey, i64 nKey,    /* The key */
   54692   const void *pData,int nData,   /* The data */
   54693   int nZero,                     /* Extra zero bytes to append to pData */
   54694   int *pnSize                    /* Write cell size here */
   54695 ){
   54696   int nPayload;
   54697   const u8 *pSrc;
   54698   int nSrc, n, rc;
   54699   int spaceLeft;
   54700   MemPage *pOvfl = 0;
   54701   MemPage *pToRelease = 0;
   54702   unsigned char *pPrior;
   54703   unsigned char *pPayload;
   54704   BtShared *pBt = pPage->pBt;
   54705   Pgno pgnoOvfl = 0;
   54706   int nHeader;
   54707   CellInfo info;
   54708 
   54709   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54710 
   54711   /* pPage is not necessarily writeable since pCell might be auxiliary
   54712   ** buffer space that is separate from the pPage buffer area */
   54713   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   54714             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54715 
   54716   /* Fill in the header. */
   54717   nHeader = 0;
   54718   if( !pPage->leaf ){
   54719     nHeader += 4;
   54720   }
   54721   if( pPage->hasData ){
   54722     nHeader += putVarint(&pCell[nHeader], nData+nZero);
   54723   }else{
   54724     nData = nZero = 0;
   54725   }
   54726   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   54727   btreeParseCellPtr(pPage, pCell, &info);
   54728   assert( info.nHeader==nHeader );
   54729   assert( info.nKey==nKey );
   54730   assert( info.nData==(u32)(nData+nZero) );
   54731 
   54732   /* Fill in the payload */
   54733   nPayload = nData + nZero;
   54734   if( pPage->intKey ){
   54735     pSrc = pData;
   54736     nSrc = nData;
   54737     nData = 0;
   54738   }else{
   54739     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   54740       return SQLITE_CORRUPT_BKPT;
   54741     }
   54742     nPayload += (int)nKey;
   54743     pSrc = pKey;
   54744     nSrc = (int)nKey;
   54745   }
   54746   *pnSize = info.nSize;
   54747   spaceLeft = info.nLocal;
   54748   pPayload = &pCell[nHeader];
   54749   pPrior = &pCell[info.iOverflow];
   54750 
   54751   while( nPayload>0 ){
   54752     if( spaceLeft==0 ){
   54753 #ifndef SQLITE_OMIT_AUTOVACUUM
   54754       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   54755       if( pBt->autoVacuum ){
   54756         do{
   54757           pgnoOvfl++;
   54758         } while(
   54759           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   54760         );
   54761       }
   54762 #endif
   54763       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   54764 #ifndef SQLITE_OMIT_AUTOVACUUM
   54765       /* If the database supports auto-vacuum, and the second or subsequent
   54766       ** overflow page is being allocated, add an entry to the pointer-map
   54767       ** for that page now.
   54768       **
   54769       ** If this is the first overflow page, then write a partial entry
   54770       ** to the pointer-map. If we write nothing to this pointer-map slot,
   54771       ** then the optimistic overflow chain processing in clearCell()
   54772       ** may misinterpret the uninitialised values and delete the
   54773       ** wrong pages from the database.
   54774       */
   54775       if( pBt->autoVacuum && rc==SQLITE_OK ){
   54776         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   54777         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   54778         if( rc ){
   54779           releasePage(pOvfl);
   54780         }
   54781       }
   54782 #endif
   54783       if( rc ){
   54784         releasePage(pToRelease);
   54785         return rc;
   54786       }
   54787 
   54788       /* If pToRelease is not zero than pPrior points into the data area
   54789       ** of pToRelease.  Make sure pToRelease is still writeable. */
   54790       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   54791 
   54792       /* If pPrior is part of the data area of pPage, then make sure pPage
   54793       ** is still writeable */
   54794       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   54795             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54796 
   54797       put4byte(pPrior, pgnoOvfl);
   54798       releasePage(pToRelease);
   54799       pToRelease = pOvfl;
   54800       pPrior = pOvfl->aData;
   54801       put4byte(pPrior, 0);
   54802       pPayload = &pOvfl->aData[4];
   54803       spaceLeft = pBt->usableSize - 4;
   54804     }
   54805     n = nPayload;
   54806     if( n>spaceLeft ) n = spaceLeft;
   54807 
   54808     /* If pToRelease is not zero than pPayload points into the data area
   54809     ** of pToRelease.  Make sure pToRelease is still writeable. */
   54810     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   54811 
   54812     /* If pPayload is part of the data area of pPage, then make sure pPage
   54813     ** is still writeable */
   54814     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   54815             || sqlite3PagerIswriteable(pPage->pDbPage) );
   54816 
   54817     if( nSrc>0 ){
   54818       if( n>nSrc ) n = nSrc;
   54819       assert( pSrc );
   54820       memcpy(pPayload, pSrc, n);
   54821     }else{
   54822       memset(pPayload, 0, n);
   54823     }
   54824     nPayload -= n;
   54825     pPayload += n;
   54826     pSrc += n;
   54827     nSrc -= n;
   54828     spaceLeft -= n;
   54829     if( nSrc==0 ){
   54830       nSrc = nData;
   54831       pSrc = pData;
   54832     }
   54833   }
   54834   releasePage(pToRelease);
   54835   return SQLITE_OK;
   54836 }
   54837 
   54838 /*
   54839 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   54840 ** The cell content is not freed or deallocated.  It is assumed that
   54841 ** the cell content has been copied someplace else.  This routine just
   54842 ** removes the reference to the cell from pPage.
   54843 **
   54844 ** "sz" must be the number of bytes in the cell.
   54845 */
   54846 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   54847   u32 pc;         /* Offset to cell content of cell being deleted */
   54848   u8 *data;       /* pPage->aData */
   54849   u8 *ptr;        /* Used to move bytes around within data[] */
   54850   u8 *endPtr;     /* End of loop */
   54851   int rc;         /* The return code */
   54852   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   54853 
   54854   if( *pRC ) return;
   54855 
   54856   assert( idx>=0 && idx<pPage->nCell );
   54857   assert( sz==cellSize(pPage, idx) );
   54858   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54859   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54860   data = pPage->aData;
   54861   ptr = &pPage->aCellIdx[2*idx];
   54862   pc = get2byte(ptr);
   54863   hdr = pPage->hdrOffset;
   54864   testcase( pc==get2byte(&data[hdr+5]) );
   54865   testcase( pc+sz==pPage->pBt->usableSize );
   54866   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   54867     *pRC = SQLITE_CORRUPT_BKPT;
   54868     return;
   54869   }
   54870   rc = freeSpace(pPage, pc, sz);
   54871   if( rc ){
   54872     *pRC = rc;
   54873     return;
   54874   }
   54875   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
   54876   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
   54877   while( ptr<endPtr ){
   54878     *(u16*)ptr = *(u16*)&ptr[2];
   54879     ptr += 2;
   54880   }
   54881   pPage->nCell--;
   54882   put2byte(&data[hdr+3], pPage->nCell);
   54883   pPage->nFree += 2;
   54884 }
   54885 
   54886 /*
   54887 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   54888 ** content of the cell.
   54889 **
   54890 ** If the cell content will fit on the page, then put it there.  If it
   54891 ** will not fit, then make a copy of the cell content into pTemp if
   54892 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   54893 ** in pPage->apOvfl[] and make it point to the cell content (either
   54894 ** in pTemp or the original pCell) and also record its index.
   54895 ** Allocating a new entry in pPage->aCell[] implies that
   54896 ** pPage->nOverflow is incremented.
   54897 **
   54898 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   54899 ** cell. The caller will overwrite them after this function returns. If
   54900 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   54901 ** (but pCell+nSkip is always valid).
   54902 */
   54903 static void insertCell(
   54904   MemPage *pPage,   /* Page into which we are copying */
   54905   int i,            /* New cell becomes the i-th cell of the page */
   54906   u8 *pCell,        /* Content of the new cell */
   54907   int sz,           /* Bytes of content in pCell */
   54908   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   54909   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   54910   int *pRC          /* Read and write return code from here */
   54911 ){
   54912   int idx = 0;      /* Where to write new cell content in data[] */
   54913   int j;            /* Loop counter */
   54914   int end;          /* First byte past the last cell pointer in data[] */
   54915   int ins;          /* Index in data[] where new cell pointer is inserted */
   54916   int cellOffset;   /* Address of first cell pointer in data[] */
   54917   u8 *data;         /* The content of the whole page */
   54918   u8 *ptr;          /* Used for moving information around in data[] */
   54919   u8 *endPtr;       /* End of the loop */
   54920 
   54921   int nSkip = (iChild ? 4 : 0);
   54922 
   54923   if( *pRC ) return;
   54924 
   54925   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   54926   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
   54927   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
   54928   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
   54929   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   54930   /* The cell should normally be sized correctly.  However, when moving a
   54931   ** malformed cell from a leaf page to an interior page, if the cell size
   54932   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   54933   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   54934   ** the term after the || in the following assert(). */
   54935   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   54936   if( pPage->nOverflow || sz+2>pPage->nFree ){
   54937     if( pTemp ){
   54938       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   54939       pCell = pTemp;
   54940     }
   54941     if( iChild ){
   54942       put4byte(pCell, iChild);
   54943     }
   54944     j = pPage->nOverflow++;
   54945     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
   54946     pPage->apOvfl[j] = pCell;
   54947     pPage->aiOvfl[j] = (u16)i;
   54948   }else{
   54949     int rc = sqlite3PagerWrite(pPage->pDbPage);
   54950     if( rc!=SQLITE_OK ){
   54951       *pRC = rc;
   54952       return;
   54953     }
   54954     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   54955     data = pPage->aData;
   54956     cellOffset = pPage->cellOffset;
   54957     end = cellOffset + 2*pPage->nCell;
   54958     ins = cellOffset + 2*i;
   54959     rc = allocateSpace(pPage, sz, &idx);
   54960     if( rc ){ *pRC = rc; return; }
   54961     /* The allocateSpace() routine guarantees the following two properties
   54962     ** if it returns success */
   54963     assert( idx >= end+2 );
   54964     assert( idx+sz <= (int)pPage->pBt->usableSize );
   54965     pPage->nCell++;
   54966     pPage->nFree -= (u16)(2 + sz);
   54967     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   54968     if( iChild ){
   54969       put4byte(&data[idx], iChild);
   54970     }
   54971     ptr = &data[end];
   54972     endPtr = &data[ins];
   54973     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
   54974     while( ptr>endPtr ){
   54975       *(u16*)ptr = *(u16*)&ptr[-2];
   54976       ptr -= 2;
   54977     }
   54978     put2byte(&data[ins], idx);
   54979     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   54980 #ifndef SQLITE_OMIT_AUTOVACUUM
   54981     if( pPage->pBt->autoVacuum ){
   54982       /* The cell may contain a pointer to an overflow page. If so, write
   54983       ** the entry for the overflow page into the pointer map.
   54984       */
   54985       ptrmapPutOvflPtr(pPage, pCell, pRC);
   54986     }
   54987 #endif
   54988   }
   54989 }
   54990 
   54991 /*
   54992 ** Add a list of cells to a page.  The page should be initially empty.
   54993 ** The cells are guaranteed to fit on the page.
   54994 */
   54995 static void assemblePage(
   54996   MemPage *pPage,   /* The page to be assemblied */
   54997   int nCell,        /* The number of cells to add to this page */
   54998   u8 **apCell,      /* Pointers to cell bodies */
   54999   u16 *aSize        /* Sizes of the cells */
   55000 ){
   55001   int i;            /* Loop counter */
   55002   u8 *pCellptr;     /* Address of next cell pointer */
   55003   int cellbody;     /* Address of next cell body */
   55004   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   55005   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   55006   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   55007 
   55008   assert( pPage->nOverflow==0 );
   55009   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   55010   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
   55011             && (int)MX_CELL(pPage->pBt)<=10921);
   55012   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   55013 
   55014   /* Check that the page has just been zeroed by zeroPage() */
   55015   assert( pPage->nCell==0 );
   55016   assert( get2byteNotZero(&data[hdr+5])==nUsable );
   55017 
   55018   pCellptr = &pPage->aCellIdx[nCell*2];
   55019   cellbody = nUsable;
   55020   for(i=nCell-1; i>=0; i--){
   55021     u16 sz = aSize[i];
   55022     pCellptr -= 2;
   55023     cellbody -= sz;
   55024     put2byte(pCellptr, cellbody);
   55025     memcpy(&data[cellbody], apCell[i], sz);
   55026   }
   55027   put2byte(&data[hdr+3], nCell);
   55028   put2byte(&data[hdr+5], cellbody);
   55029   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   55030   pPage->nCell = (u16)nCell;
   55031 }
   55032 
   55033 /*
   55034 ** The following parameters determine how many adjacent pages get involved
   55035 ** in a balancing operation.  NN is the number of neighbors on either side
   55036 ** of the page that participate in the balancing operation.  NB is the
   55037 ** total number of pages that participate, including the target page and
   55038 ** NN neighbors on either side.
   55039 **
   55040 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   55041 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   55042 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   55043 ** The value of NN appears to give the best results overall.
   55044 */
   55045 #define NN 1             /* Number of neighbors on either side of pPage */
   55046 #define NB (NN*2+1)      /* Total pages involved in the balance */
   55047 
   55048 
   55049 #ifndef SQLITE_OMIT_QUICKBALANCE
   55050 /*
   55051 ** This version of balance() handles the common special case where
   55052 ** a new entry is being inserted on the extreme right-end of the
   55053 ** tree, in other words, when the new entry will become the largest
   55054 ** entry in the tree.
   55055 **
   55056 ** Instead of trying to balance the 3 right-most leaf pages, just add
   55057 ** a new page to the right-hand side and put the one new entry in
   55058 ** that page.  This leaves the right side of the tree somewhat
   55059 ** unbalanced.  But odds are that we will be inserting new entries
   55060 ** at the end soon afterwards so the nearly empty page will quickly
   55061 ** fill up.  On average.
   55062 **
   55063 ** pPage is the leaf page which is the right-most page in the tree.
   55064 ** pParent is its parent.  pPage must have a single overflow entry
   55065 ** which is also the right-most entry on the page.
   55066 **
   55067 ** The pSpace buffer is used to store a temporary copy of the divider
   55068 ** cell that will be inserted into pParent. Such a cell consists of a 4
   55069 ** byte page number followed by a variable length integer. In other
   55070 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   55071 ** least 13 bytes in size.
   55072 */
   55073 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   55074   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   55075   MemPage *pNew;                       /* Newly allocated page */
   55076   int rc;                              /* Return Code */
   55077   Pgno pgnoNew;                        /* Page number of pNew */
   55078 
   55079   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   55080   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55081   assert( pPage->nOverflow==1 );
   55082 
   55083   /* This error condition is now caught prior to reaching this function */
   55084   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
   55085 
   55086   /* Allocate a new page. This page will become the right-sibling of
   55087   ** pPage. Make the parent page writable, so that the new divider cell
   55088   ** may be inserted. If both these operations are successful, proceed.
   55089   */
   55090   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   55091 
   55092   if( rc==SQLITE_OK ){
   55093 
   55094     u8 *pOut = &pSpace[4];
   55095     u8 *pCell = pPage->apOvfl[0];
   55096     u16 szCell = cellSizePtr(pPage, pCell);
   55097     u8 *pStop;
   55098 
   55099     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   55100     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   55101     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   55102     assemblePage(pNew, 1, &pCell, &szCell);
   55103 
   55104     /* If this is an auto-vacuum database, update the pointer map
   55105     ** with entries for the new page, and any pointer from the
   55106     ** cell on the page to an overflow page. If either of these
   55107     ** operations fails, the return code is set, but the contents
   55108     ** of the parent page are still manipulated by thh code below.
   55109     ** That is Ok, at this point the parent page is guaranteed to
   55110     ** be marked as dirty. Returning an error code will cause a
   55111     ** rollback, undoing any changes made to the parent page.
   55112     */
   55113     if( ISAUTOVACUUM ){
   55114       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   55115       if( szCell>pNew->minLocal ){
   55116         ptrmapPutOvflPtr(pNew, pCell, &rc);
   55117       }
   55118     }
   55119 
   55120     /* Create a divider cell to insert into pParent. The divider cell
   55121     ** consists of a 4-byte page number (the page number of pPage) and
   55122     ** a variable length key value (which must be the same value as the
   55123     ** largest key on pPage).
   55124     **
   55125     ** To find the largest key value on pPage, first find the right-most
   55126     ** cell on pPage. The first two fields of this cell are the
   55127     ** record-length (a variable length integer at most 32-bits in size)
   55128     ** and the key value (a variable length integer, may have any value).
   55129     ** The first of the while(...) loops below skips over the record-length
   55130     ** field. The second while(...) loop copies the key value from the
   55131     ** cell on pPage into the pSpace buffer.
   55132     */
   55133     pCell = findCell(pPage, pPage->nCell-1);
   55134     pStop = &pCell[9];
   55135     while( (*(pCell++)&0x80) && pCell<pStop );
   55136     pStop = &pCell[9];
   55137     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   55138 
   55139     /* Insert the new divider cell into pParent. */
   55140     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   55141                0, pPage->pgno, &rc);
   55142 
   55143     /* Set the right-child pointer of pParent to point to the new page. */
   55144     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   55145 
   55146     /* Release the reference to the new page. */
   55147     releasePage(pNew);
   55148   }
   55149 
   55150   return rc;
   55151 }
   55152 #endif /* SQLITE_OMIT_QUICKBALANCE */
   55153 
   55154 #if 0
   55155 /*
   55156 ** This function does not contribute anything to the operation of SQLite.
   55157 ** it is sometimes activated temporarily while debugging code responsible
   55158 ** for setting pointer-map entries.
   55159 */
   55160 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   55161   int i, j;
   55162   for(i=0; i<nPage; i++){
   55163     Pgno n;
   55164     u8 e;
   55165     MemPage *pPage = apPage[i];
   55166     BtShared *pBt = pPage->pBt;
   55167     assert( pPage->isInit );
   55168 
   55169     for(j=0; j<pPage->nCell; j++){
   55170       CellInfo info;
   55171       u8 *z;
   55172 
   55173       z = findCell(pPage, j);
   55174       btreeParseCellPtr(pPage, z, &info);
   55175       if( info.iOverflow ){
   55176         Pgno ovfl = get4byte(&z[info.iOverflow]);
   55177         ptrmapGet(pBt, ovfl, &e, &n);
   55178         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   55179       }
   55180       if( !pPage->leaf ){
   55181         Pgno child = get4byte(z);
   55182         ptrmapGet(pBt, child, &e, &n);
   55183         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   55184       }
   55185     }
   55186     if( !pPage->leaf ){
   55187       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   55188       ptrmapGet(pBt, child, &e, &n);
   55189       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   55190     }
   55191   }
   55192   return 1;
   55193 }
   55194 #endif
   55195 
   55196 /*
   55197 ** This function is used to copy the contents of the b-tree node stored
   55198 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   55199 ** the pointer-map entries for each child page are updated so that the
   55200 ** parent page stored in the pointer map is page pTo. If pFrom contained
   55201 ** any cells with overflow page pointers, then the corresponding pointer
   55202 ** map entries are also updated so that the parent page is page pTo.
   55203 **
   55204 ** If pFrom is currently carrying any overflow cells (entries in the
   55205 ** MemPage.apOvfl[] array), they are not copied to pTo.
   55206 **
   55207 ** Before returning, page pTo is reinitialized using btreeInitPage().
   55208 **
   55209 ** The performance of this function is not critical. It is only used by
   55210 ** the balance_shallower() and balance_deeper() procedures, neither of
   55211 ** which are called often under normal circumstances.
   55212 */
   55213 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   55214   if( (*pRC)==SQLITE_OK ){
   55215     BtShared * const pBt = pFrom->pBt;
   55216     u8 * const aFrom = pFrom->aData;
   55217     u8 * const aTo = pTo->aData;
   55218     int const iFromHdr = pFrom->hdrOffset;
   55219     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   55220     int rc;
   55221     int iData;
   55222 
   55223 
   55224     assert( pFrom->isInit );
   55225     assert( pFrom->nFree>=iToHdr );
   55226     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
   55227 
   55228     /* Copy the b-tree node content from page pFrom to page pTo. */
   55229     iData = get2byte(&aFrom[iFromHdr+5]);
   55230     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   55231     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   55232 
   55233     /* Reinitialize page pTo so that the contents of the MemPage structure
   55234     ** match the new data. The initialization of pTo can actually fail under
   55235     ** fairly obscure circumstances, even though it is a copy of initialized
   55236     ** page pFrom.
   55237     */
   55238     pTo->isInit = 0;
   55239     rc = btreeInitPage(pTo);
   55240     if( rc!=SQLITE_OK ){
   55241       *pRC = rc;
   55242       return;
   55243     }
   55244 
   55245     /* If this is an auto-vacuum database, update the pointer-map entries
   55246     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   55247     */
   55248     if( ISAUTOVACUUM ){
   55249       *pRC = setChildPtrmaps(pTo);
   55250     }
   55251   }
   55252 }
   55253 
   55254 /*
   55255 ** This routine redistributes cells on the iParentIdx'th child of pParent
   55256 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   55257 ** same amount of free space. Usually a single sibling on either side of the
   55258 ** page are used in the balancing, though both siblings might come from one
   55259 ** side if the page is the first or last child of its parent. If the page
   55260 ** has fewer than 2 siblings (something which can only happen if the page
   55261 ** is a root page or a child of a root page) then all available siblings
   55262 ** participate in the balancing.
   55263 **
   55264 ** The number of siblings of the page might be increased or decreased by
   55265 ** one or two in an effort to keep pages nearly full but not over full.
   55266 **
   55267 ** Note that when this routine is called, some of the cells on the page
   55268 ** might not actually be stored in MemPage.aData[]. This can happen
   55269 ** if the page is overfull. This routine ensures that all cells allocated
   55270 ** to the page and its siblings fit into MemPage.aData[] before returning.
   55271 **
   55272 ** In the course of balancing the page and its siblings, cells may be
   55273 ** inserted into or removed from the parent page (pParent). Doing so
   55274 ** may cause the parent page to become overfull or underfull. If this
   55275 ** happens, it is the responsibility of the caller to invoke the correct
   55276 ** balancing routine to fix this problem (see the balance() routine).
   55277 **
   55278 ** If this routine fails for any reason, it might leave the database
   55279 ** in a corrupted state. So if this routine fails, the database should
   55280 ** be rolled back.
   55281 **
   55282 ** The third argument to this function, aOvflSpace, is a pointer to a
   55283 ** buffer big enough to hold one page. If while inserting cells into the parent
   55284 ** page (pParent) the parent page becomes overfull, this buffer is
   55285 ** used to store the parent's overflow cells. Because this function inserts
   55286 ** a maximum of four divider cells into the parent page, and the maximum
   55287 ** size of a cell stored within an internal node is always less than 1/4
   55288 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   55289 ** enough for all overflow cells.
   55290 **
   55291 ** If aOvflSpace is set to a null pointer, this function returns
   55292 ** SQLITE_NOMEM.
   55293 */
   55294 static int balance_nonroot(
   55295   MemPage *pParent,               /* Parent page of siblings being balanced */
   55296   int iParentIdx,                 /* Index of "the page" in pParent */
   55297   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   55298   int isRoot                      /* True if pParent is a root-page */
   55299 ){
   55300   BtShared *pBt;               /* The whole database */
   55301   int nCell = 0;               /* Number of cells in apCell[] */
   55302   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   55303   int nNew = 0;                /* Number of pages in apNew[] */
   55304   int nOld;                    /* Number of pages in apOld[] */
   55305   int i, j, k;                 /* Loop counters */
   55306   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   55307   int rc = SQLITE_OK;          /* The return code */
   55308   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   55309   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   55310   int usableSpace;             /* Bytes in pPage beyond the header */
   55311   int pageFlags;               /* Value of pPage->aData[0] */
   55312   int subtotal;                /* Subtotal of bytes in cells on one page */
   55313   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   55314   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   55315   int szScratch;               /* Size of scratch memory requested */
   55316   MemPage *apOld[NB];          /* pPage and up to two siblings */
   55317   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   55318   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   55319   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   55320   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   55321   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   55322   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   55323   u8 **apCell = 0;             /* All cells begin balanced */
   55324   u16 *szCell;                 /* Local size of all cells in apCell[] */
   55325   u8 *aSpace1;                 /* Space for copies of dividers cells */
   55326   Pgno pgno;                   /* Temp var to store a page number in */
   55327 
   55328   pBt = pParent->pBt;
   55329   assert( sqlite3_mutex_held(pBt->mutex) );
   55330   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55331 
   55332 #if 0
   55333   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   55334 #endif
   55335 
   55336   /* At this point pParent may have at most one overflow cell. And if
   55337   ** this overflow cell is present, it must be the cell with
   55338   ** index iParentIdx. This scenario comes about when this function
   55339   ** is called (indirectly) from sqlite3BtreeDelete().
   55340   */
   55341   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   55342   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
   55343 
   55344   if( !aOvflSpace ){
   55345     return SQLITE_NOMEM;
   55346   }
   55347 
   55348   /* Find the sibling pages to balance. Also locate the cells in pParent
   55349   ** that divide the siblings. An attempt is made to find NN siblings on
   55350   ** either side of pPage. More siblings are taken from one side, however,
   55351   ** if there are fewer than NN siblings on the other side. If pParent
   55352   ** has NB or fewer children then all children of pParent are taken.
   55353   **
   55354   ** This loop also drops the divider cells from the parent page. This
   55355   ** way, the remainder of the function does not have to deal with any
   55356   ** overflow cells in the parent page, since if any existed they will
   55357   ** have already been removed.
   55358   */
   55359   i = pParent->nOverflow + pParent->nCell;
   55360   if( i<2 ){
   55361     nxDiv = 0;
   55362     nOld = i+1;
   55363   }else{
   55364     nOld = 3;
   55365     if( iParentIdx==0 ){
   55366       nxDiv = 0;
   55367     }else if( iParentIdx==i ){
   55368       nxDiv = i-2;
   55369     }else{
   55370       nxDiv = iParentIdx-1;
   55371     }
   55372     i = 2;
   55373   }
   55374   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   55375     pRight = &pParent->aData[pParent->hdrOffset+8];
   55376   }else{
   55377     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   55378   }
   55379   pgno = get4byte(pRight);
   55380   while( 1 ){
   55381     rc = getAndInitPage(pBt, pgno, &apOld[i]);
   55382     if( rc ){
   55383       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   55384       goto balance_cleanup;
   55385     }
   55386     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   55387     if( (i--)==0 ) break;
   55388 
   55389     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
   55390       apDiv[i] = pParent->apOvfl[0];
   55391       pgno = get4byte(apDiv[i]);
   55392       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   55393       pParent->nOverflow = 0;
   55394     }else{
   55395       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   55396       pgno = get4byte(apDiv[i]);
   55397       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   55398 
   55399       /* Drop the cell from the parent page. apDiv[i] still points to
   55400       ** the cell within the parent, even though it has been dropped.
   55401       ** This is safe because dropping a cell only overwrites the first
   55402       ** four bytes of it, and this function does not need the first
   55403       ** four bytes of the divider cell. So the pointer is safe to use
   55404       ** later on.
   55405       **
   55406       ** But not if we are in secure-delete mode. In secure-delete mode,
   55407       ** the dropCell() routine will overwrite the entire cell with zeroes.
   55408       ** In this case, temporarily copy the cell into the aOvflSpace[]
   55409       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   55410       ** is allocated.  */
   55411       if( pBt->btsFlags & BTS_SECURE_DELETE ){
   55412         int iOff;
   55413 
   55414         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   55415         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   55416           rc = SQLITE_CORRUPT_BKPT;
   55417           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   55418           goto balance_cleanup;
   55419         }else{
   55420           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   55421           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   55422         }
   55423       }
   55424       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   55425     }
   55426   }
   55427 
   55428   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   55429   ** alignment */
   55430   nMaxCells = (nMaxCells + 3)&~3;
   55431 
   55432   /*
   55433   ** Allocate space for memory structures
   55434   */
   55435   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   55436   szScratch =
   55437        nMaxCells*sizeof(u8*)                       /* apCell */
   55438      + nMaxCells*sizeof(u16)                       /* szCell */
   55439      + pBt->pageSize                               /* aSpace1 */
   55440      + k*nOld;                                     /* Page copies (apCopy) */
   55441   apCell = sqlite3ScratchMalloc( szScratch );
   55442   if( apCell==0 ){
   55443     rc = SQLITE_NOMEM;
   55444     goto balance_cleanup;
   55445   }
   55446   szCell = (u16*)&apCell[nMaxCells];
   55447   aSpace1 = (u8*)&szCell[nMaxCells];
   55448   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   55449 
   55450   /*
   55451   ** Load pointers to all cells on sibling pages and the divider cells
   55452   ** into the local apCell[] array.  Make copies of the divider cells
   55453   ** into space obtained from aSpace1[] and remove the the divider Cells
   55454   ** from pParent.
   55455   **
   55456   ** If the siblings are on leaf pages, then the child pointers of the
   55457   ** divider cells are stripped from the cells before they are copied
   55458   ** into aSpace1[].  In this way, all cells in apCell[] are without
   55459   ** child pointers.  If siblings are not leaves, then all cell in
   55460   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   55461   ** are alike.
   55462   **
   55463   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   55464   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   55465   */
   55466   leafCorrection = apOld[0]->leaf*4;
   55467   leafData = apOld[0]->hasData;
   55468   for(i=0; i<nOld; i++){
   55469     int limit;
   55470 
   55471     /* Before doing anything else, take a copy of the i'th original sibling
   55472     ** The rest of this function will use data from the copies rather
   55473     ** that the original pages since the original pages will be in the
   55474     ** process of being overwritten.  */
   55475     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   55476     memcpy(pOld, apOld[i], sizeof(MemPage));
   55477     pOld->aData = (void*)&pOld[1];
   55478     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   55479 
   55480     limit = pOld->nCell+pOld->nOverflow;
   55481     if( pOld->nOverflow>0 ){
   55482       for(j=0; j<limit; j++){
   55483         assert( nCell<nMaxCells );
   55484         apCell[nCell] = findOverflowCell(pOld, j);
   55485         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   55486         nCell++;
   55487       }
   55488     }else{
   55489       u8 *aData = pOld->aData;
   55490       u16 maskPage = pOld->maskPage;
   55491       u16 cellOffset = pOld->cellOffset;
   55492       for(j=0; j<limit; j++){
   55493         assert( nCell<nMaxCells );
   55494         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
   55495         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   55496         nCell++;
   55497       }
   55498     }
   55499     if( i<nOld-1 && !leafData){
   55500       u16 sz = (u16)szNew[i];
   55501       u8 *pTemp;
   55502       assert( nCell<nMaxCells );
   55503       szCell[nCell] = sz;
   55504       pTemp = &aSpace1[iSpace1];
   55505       iSpace1 += sz;
   55506       assert( sz<=pBt->maxLocal+23 );
   55507       assert( iSpace1 <= (int)pBt->pageSize );
   55508       memcpy(pTemp, apDiv[i], sz);
   55509       apCell[nCell] = pTemp+leafCorrection;
   55510       assert( leafCorrection==0 || leafCorrection==4 );
   55511       szCell[nCell] = szCell[nCell] - leafCorrection;
   55512       if( !pOld->leaf ){
   55513         assert( leafCorrection==0 );
   55514         assert( pOld->hdrOffset==0 );
   55515         /* The right pointer of the child page pOld becomes the left
   55516         ** pointer of the divider cell */
   55517         memcpy(apCell[nCell], &pOld->aData[8], 4);
   55518       }else{
   55519         assert( leafCorrection==4 );
   55520         if( szCell[nCell]<4 ){
   55521           /* Do not allow any cells smaller than 4 bytes. */
   55522           szCell[nCell] = 4;
   55523         }
   55524       }
   55525       nCell++;
   55526     }
   55527   }
   55528 
   55529   /*
   55530   ** Figure out the number of pages needed to hold all nCell cells.
   55531   ** Store this number in "k".  Also compute szNew[] which is the total
   55532   ** size of all cells on the i-th page and cntNew[] which is the index
   55533   ** in apCell[] of the cell that divides page i from page i+1.
   55534   ** cntNew[k] should equal nCell.
   55535   **
   55536   ** Values computed by this block:
   55537   **
   55538   **           k: The total number of sibling pages
   55539   **    szNew[i]: Spaced used on the i-th sibling page.
   55540   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   55541   **              the right of the i-th sibling page.
   55542   ** usableSpace: Number of bytes of space available on each sibling.
   55543   **
   55544   */
   55545   usableSpace = pBt->usableSize - 12 + leafCorrection;
   55546   for(subtotal=k=i=0; i<nCell; i++){
   55547     assert( i<nMaxCells );
   55548     subtotal += szCell[i] + 2;
   55549     if( subtotal > usableSpace ){
   55550       szNew[k] = subtotal - szCell[i];
   55551       cntNew[k] = i;
   55552       if( leafData ){ i--; }
   55553       subtotal = 0;
   55554       k++;
   55555       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   55556     }
   55557   }
   55558   szNew[k] = subtotal;
   55559   cntNew[k] = nCell;
   55560   k++;
   55561 
   55562   /*
   55563   ** The packing computed by the previous block is biased toward the siblings
   55564   ** on the left side.  The left siblings are always nearly full, while the
   55565   ** right-most sibling might be nearly empty.  This block of code attempts
   55566   ** to adjust the packing of siblings to get a better balance.
   55567   **
   55568   ** This adjustment is more than an optimization.  The packing above might
   55569   ** be so out of balance as to be illegal.  For example, the right-most
   55570   ** sibling might be completely empty.  This adjustment is not optional.
   55571   */
   55572   for(i=k-1; i>0; i--){
   55573     int szRight = szNew[i];  /* Size of sibling on the right */
   55574     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   55575     int r;              /* Index of right-most cell in left sibling */
   55576     int d;              /* Index of first cell to the left of right sibling */
   55577 
   55578     r = cntNew[i-1] - 1;
   55579     d = r + 1 - leafData;
   55580     assert( d<nMaxCells );
   55581     assert( r<nMaxCells );
   55582     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
   55583       szRight += szCell[d] + 2;
   55584       szLeft -= szCell[r] + 2;
   55585       cntNew[i-1]--;
   55586       r = cntNew[i-1] - 1;
   55587       d = r + 1 - leafData;
   55588     }
   55589     szNew[i] = szRight;
   55590     szNew[i-1] = szLeft;
   55591   }
   55592 
   55593   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   55594   ** a virtual root page.  A virtual root page is when the real root
   55595   ** page is page 1 and we are the only child of that page.
   55596   **
   55597   ** UPDATE:  The assert() below is not necessarily true if the database
   55598   ** file is corrupt.  The corruption will be detected and reported later
   55599   ** in this procedure so there is no need to act upon it now.
   55600   */
   55601 #if 0
   55602   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   55603 #endif
   55604 
   55605   TRACE(("BALANCE: old: %d %d %d  ",
   55606     apOld[0]->pgno,
   55607     nOld>=2 ? apOld[1]->pgno : 0,
   55608     nOld>=3 ? apOld[2]->pgno : 0
   55609   ));
   55610 
   55611   /*
   55612   ** Allocate k new pages.  Reuse old pages where possible.
   55613   */
   55614   if( apOld[0]->pgno<=1 ){
   55615     rc = SQLITE_CORRUPT_BKPT;
   55616     goto balance_cleanup;
   55617   }
   55618   pageFlags = apOld[0]->aData[0];
   55619   for(i=0; i<k; i++){
   55620     MemPage *pNew;
   55621     if( i<nOld ){
   55622       pNew = apNew[i] = apOld[i];
   55623       apOld[i] = 0;
   55624       rc = sqlite3PagerWrite(pNew->pDbPage);
   55625       nNew++;
   55626       if( rc ) goto balance_cleanup;
   55627     }else{
   55628       assert( i>0 );
   55629       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
   55630       if( rc ) goto balance_cleanup;
   55631       apNew[i] = pNew;
   55632       nNew++;
   55633 
   55634       /* Set the pointer-map entry for the new sibling page. */
   55635       if( ISAUTOVACUUM ){
   55636         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   55637         if( rc!=SQLITE_OK ){
   55638           goto balance_cleanup;
   55639         }
   55640       }
   55641     }
   55642   }
   55643 
   55644   /* Free any old pages that were not reused as new pages.
   55645   */
   55646   while( i<nOld ){
   55647     freePage(apOld[i], &rc);
   55648     if( rc ) goto balance_cleanup;
   55649     releasePage(apOld[i]);
   55650     apOld[i] = 0;
   55651     i++;
   55652   }
   55653 
   55654   /*
   55655   ** Put the new pages in accending order.  This helps to
   55656   ** keep entries in the disk file in order so that a scan
   55657   ** of the table is a linear scan through the file.  That
   55658   ** in turn helps the operating system to deliver pages
   55659   ** from the disk more rapidly.
   55660   **
   55661   ** An O(n^2) insertion sort algorithm is used, but since
   55662   ** n is never more than NB (a small constant), that should
   55663   ** not be a problem.
   55664   **
   55665   ** When NB==3, this one optimization makes the database
   55666   ** about 25% faster for large insertions and deletions.
   55667   */
   55668   for(i=0; i<k-1; i++){
   55669     int minV = apNew[i]->pgno;
   55670     int minI = i;
   55671     for(j=i+1; j<k; j++){
   55672       if( apNew[j]->pgno<(unsigned)minV ){
   55673         minI = j;
   55674         minV = apNew[j]->pgno;
   55675       }
   55676     }
   55677     if( minI>i ){
   55678       MemPage *pT;
   55679       pT = apNew[i];
   55680       apNew[i] = apNew[minI];
   55681       apNew[minI] = pT;
   55682     }
   55683   }
   55684   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   55685     apNew[0]->pgno, szNew[0],
   55686     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   55687     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   55688     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   55689     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   55690 
   55691   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55692   put4byte(pRight, apNew[nNew-1]->pgno);
   55693 
   55694   /*
   55695   ** Evenly distribute the data in apCell[] across the new pages.
   55696   ** Insert divider cells into pParent as necessary.
   55697   */
   55698   j = 0;
   55699   for(i=0; i<nNew; i++){
   55700     /* Assemble the new sibling page. */
   55701     MemPage *pNew = apNew[i];
   55702     assert( j<nMaxCells );
   55703     zeroPage(pNew, pageFlags);
   55704     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   55705     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   55706     assert( pNew->nOverflow==0 );
   55707 
   55708     j = cntNew[i];
   55709 
   55710     /* If the sibling page assembled above was not the right-most sibling,
   55711     ** insert a divider cell into the parent page.
   55712     */
   55713     assert( i<nNew-1 || j==nCell );
   55714     if( j<nCell ){
   55715       u8 *pCell;
   55716       u8 *pTemp;
   55717       int sz;
   55718 
   55719       assert( j<nMaxCells );
   55720       pCell = apCell[j];
   55721       sz = szCell[j] + leafCorrection;
   55722       pTemp = &aOvflSpace[iOvflSpace];
   55723       if( !pNew->leaf ){
   55724         memcpy(&pNew->aData[8], pCell, 4);
   55725       }else if( leafData ){
   55726         /* If the tree is a leaf-data tree, and the siblings are leaves,
   55727         ** then there is no divider cell in apCell[]. Instead, the divider
   55728         ** cell consists of the integer key for the right-most cell of
   55729         ** the sibling-page assembled above only.
   55730         */
   55731         CellInfo info;
   55732         j--;
   55733         btreeParseCellPtr(pNew, apCell[j], &info);
   55734         pCell = pTemp;
   55735         sz = 4 + putVarint(&pCell[4], info.nKey);
   55736         pTemp = 0;
   55737       }else{
   55738         pCell -= 4;
   55739         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   55740         ** previously stored on a leaf node, and its reported size was 4
   55741         ** bytes, then it may actually be smaller than this
   55742         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   55743         ** any cell). But it is important to pass the correct size to
   55744         ** insertCell(), so reparse the cell now.
   55745         **
   55746         ** Note that this can never happen in an SQLite data file, as all
   55747         ** cells are at least 4 bytes. It only happens in b-trees used
   55748         ** to evaluate "IN (SELECT ...)" and similar clauses.
   55749         */
   55750         if( szCell[j]==4 ){
   55751           assert(leafCorrection==4);
   55752           sz = cellSizePtr(pParent, pCell);
   55753         }
   55754       }
   55755       iOvflSpace += sz;
   55756       assert( sz<=pBt->maxLocal+23 );
   55757       assert( iOvflSpace <= (int)pBt->pageSize );
   55758       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   55759       if( rc!=SQLITE_OK ) goto balance_cleanup;
   55760       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   55761 
   55762       j++;
   55763       nxDiv++;
   55764     }
   55765   }
   55766   assert( j==nCell );
   55767   assert( nOld>0 );
   55768   assert( nNew>0 );
   55769   if( (pageFlags & PTF_LEAF)==0 ){
   55770     u8 *zChild = &apCopy[nOld-1]->aData[8];
   55771     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   55772   }
   55773 
   55774   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   55775     /* The root page of the b-tree now contains no cells. The only sibling
   55776     ** page is the right-child of the parent. Copy the contents of the
   55777     ** child page into the parent, decreasing the overall height of the
   55778     ** b-tree structure by one. This is described as the "balance-shallower"
   55779     ** sub-algorithm in some documentation.
   55780     **
   55781     ** If this is an auto-vacuum database, the call to copyNodeContent()
   55782     ** sets all pointer-map entries corresponding to database image pages
   55783     ** for which the pointer is stored within the content being copied.
   55784     **
   55785     ** The second assert below verifies that the child page is defragmented
   55786     ** (it must be, as it was just reconstructed using assemblePage()). This
   55787     ** is important if the parent page happens to be page 1 of the database
   55788     ** image.  */
   55789     assert( nNew==1 );
   55790     assert( apNew[0]->nFree ==
   55791         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   55792     );
   55793     copyNodeContent(apNew[0], pParent, &rc);
   55794     freePage(apNew[0], &rc);
   55795   }else if( ISAUTOVACUUM ){
   55796     /* Fix the pointer-map entries for all the cells that were shifted around.
   55797     ** There are several different types of pointer-map entries that need to
   55798     ** be dealt with by this routine. Some of these have been set already, but
   55799     ** many have not. The following is a summary:
   55800     **
   55801     **   1) The entries associated with new sibling pages that were not
   55802     **      siblings when this function was called. These have already
   55803     **      been set. We don't need to worry about old siblings that were
   55804     **      moved to the free-list - the freePage() code has taken care
   55805     **      of those.
   55806     **
   55807     **   2) The pointer-map entries associated with the first overflow
   55808     **      page in any overflow chains used by new divider cells. These
   55809     **      have also already been taken care of by the insertCell() code.
   55810     **
   55811     **   3) If the sibling pages are not leaves, then the child pages of
   55812     **      cells stored on the sibling pages may need to be updated.
   55813     **
   55814     **   4) If the sibling pages are not internal intkey nodes, then any
   55815     **      overflow pages used by these cells may need to be updated
   55816     **      (internal intkey nodes never contain pointers to overflow pages).
   55817     **
   55818     **   5) If the sibling pages are not leaves, then the pointer-map
   55819     **      entries for the right-child pages of each sibling may need
   55820     **      to be updated.
   55821     **
   55822     ** Cases 1 and 2 are dealt with above by other code. The next
   55823     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   55824     ** setting a pointer map entry is a relatively expensive operation, this
   55825     ** code only sets pointer map entries for child or overflow pages that have
   55826     ** actually moved between pages.  */
   55827     MemPage *pNew = apNew[0];
   55828     MemPage *pOld = apCopy[0];
   55829     int nOverflow = pOld->nOverflow;
   55830     int iNextOld = pOld->nCell + nOverflow;
   55831     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
   55832     j = 0;                             /* Current 'old' sibling page */
   55833     k = 0;                             /* Current 'new' sibling page */
   55834     for(i=0; i<nCell; i++){
   55835       int isDivider = 0;
   55836       while( i==iNextOld ){
   55837         /* Cell i is the cell immediately following the last cell on old
   55838         ** sibling page j. If the siblings are not leaf pages of an
   55839         ** intkey b-tree, then cell i was a divider cell. */
   55840         assert( j+1 < ArraySize(apCopy) );
   55841         pOld = apCopy[++j];
   55842         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   55843         if( pOld->nOverflow ){
   55844           nOverflow = pOld->nOverflow;
   55845           iOverflow = i + !leafData + pOld->aiOvfl[0];
   55846         }
   55847         isDivider = !leafData;
   55848       }
   55849 
   55850       assert(nOverflow>0 || iOverflow<i );
   55851       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
   55852       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
   55853       if( i==iOverflow ){
   55854         isDivider = 1;
   55855         if( (--nOverflow)>0 ){
   55856           iOverflow++;
   55857         }
   55858       }
   55859 
   55860       if( i==cntNew[k] ){
   55861         /* Cell i is the cell immediately following the last cell on new
   55862         ** sibling page k. If the siblings are not leaf pages of an
   55863         ** intkey b-tree, then cell i is a divider cell.  */
   55864         pNew = apNew[++k];
   55865         if( !leafData ) continue;
   55866       }
   55867       assert( j<nOld );
   55868       assert( k<nNew );
   55869 
   55870       /* If the cell was originally divider cell (and is not now) or
   55871       ** an overflow cell, or if the cell was located on a different sibling
   55872       ** page before the balancing, then the pointer map entries associated
   55873       ** with any child or overflow pages need to be updated.  */
   55874       if( isDivider || pOld->pgno!=pNew->pgno ){
   55875         if( !leafCorrection ){
   55876           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   55877         }
   55878         if( szCell[i]>pNew->minLocal ){
   55879           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   55880         }
   55881       }
   55882     }
   55883 
   55884     if( !leafCorrection ){
   55885       for(i=0; i<nNew; i++){
   55886         u32 key = get4byte(&apNew[i]->aData[8]);
   55887         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   55888       }
   55889     }
   55890 
   55891 #if 0
   55892     /* The ptrmapCheckPages() contains assert() statements that verify that
   55893     ** all pointer map pages are set correctly. This is helpful while
   55894     ** debugging. This is usually disabled because a corrupt database may
   55895     ** cause an assert() statement to fail.  */
   55896     ptrmapCheckPages(apNew, nNew);
   55897     ptrmapCheckPages(&pParent, 1);
   55898 #endif
   55899   }
   55900 
   55901   assert( pParent->isInit );
   55902   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   55903           nOld, nNew, nCell));
   55904 
   55905   /*
   55906   ** Cleanup before returning.
   55907   */
   55908 balance_cleanup:
   55909   sqlite3ScratchFree(apCell);
   55910   for(i=0; i<nOld; i++){
   55911     releasePage(apOld[i]);
   55912   }
   55913   for(i=0; i<nNew; i++){
   55914     releasePage(apNew[i]);
   55915   }
   55916 
   55917   return rc;
   55918 }
   55919 
   55920 
   55921 /*
   55922 ** This function is called when the root page of a b-tree structure is
   55923 ** overfull (has one or more overflow pages).
   55924 **
   55925 ** A new child page is allocated and the contents of the current root
   55926 ** page, including overflow cells, are copied into the child. The root
   55927 ** page is then overwritten to make it an empty page with the right-child
   55928 ** pointer pointing to the new page.
   55929 **
   55930 ** Before returning, all pointer-map entries corresponding to pages
   55931 ** that the new child-page now contains pointers to are updated. The
   55932 ** entry corresponding to the new right-child pointer of the root
   55933 ** page is also updated.
   55934 **
   55935 ** If successful, *ppChild is set to contain a reference to the child
   55936 ** page and SQLITE_OK is returned. In this case the caller is required
   55937 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   55938 ** an error code is returned and *ppChild is set to 0.
   55939 */
   55940 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   55941   int rc;                        /* Return value from subprocedures */
   55942   MemPage *pChild = 0;           /* Pointer to a new child page */
   55943   Pgno pgnoChild = 0;            /* Page number of the new child page */
   55944   BtShared *pBt = pRoot->pBt;    /* The BTree */
   55945 
   55946   assert( pRoot->nOverflow>0 );
   55947   assert( sqlite3_mutex_held(pBt->mutex) );
   55948 
   55949   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   55950   ** page that will become the new right-child of pPage. Copy the contents
   55951   ** of the node stored on pRoot into the new child page.
   55952   */
   55953   rc = sqlite3PagerWrite(pRoot->pDbPage);
   55954   if( rc==SQLITE_OK ){
   55955     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   55956     copyNodeContent(pRoot, pChild, &rc);
   55957     if( ISAUTOVACUUM ){
   55958       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   55959     }
   55960   }
   55961   if( rc ){
   55962     *ppChild = 0;
   55963     releasePage(pChild);
   55964     return rc;
   55965   }
   55966   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   55967   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   55968   assert( pChild->nCell==pRoot->nCell );
   55969 
   55970   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   55971 
   55972   /* Copy the overflow cells from pRoot to pChild */
   55973   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
   55974          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
   55975   memcpy(pChild->apOvfl, pRoot->apOvfl,
   55976          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
   55977   pChild->nOverflow = pRoot->nOverflow;
   55978 
   55979   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   55980   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   55981   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   55982 
   55983   *ppChild = pChild;
   55984   return SQLITE_OK;
   55985 }
   55986 
   55987 /*
   55988 ** The page that pCur currently points to has just been modified in
   55989 ** some way. This function figures out if this modification means the
   55990 ** tree needs to be balanced, and if so calls the appropriate balancing
   55991 ** routine. Balancing routines are:
   55992 **
   55993 **   balance_quick()
   55994 **   balance_deeper()
   55995 **   balance_nonroot()
   55996 */
   55997 static int balance(BtCursor *pCur){
   55998   int rc = SQLITE_OK;
   55999   const int nMin = pCur->pBt->usableSize * 2 / 3;
   56000   u8 aBalanceQuickSpace[13];
   56001   u8 *pFree = 0;
   56002 
   56003   TESTONLY( int balance_quick_called = 0 );
   56004   TESTONLY( int balance_deeper_called = 0 );
   56005 
   56006   do {
   56007     int iPage = pCur->iPage;
   56008     MemPage *pPage = pCur->apPage[iPage];
   56009 
   56010     if( iPage==0 ){
   56011       if( pPage->nOverflow ){
   56012         /* The root page of the b-tree is overfull. In this case call the
   56013         ** balance_deeper() function to create a new child for the root-page
   56014         ** and copy the current contents of the root-page to it. The
   56015         ** next iteration of the do-loop will balance the child page.
   56016         */
   56017         assert( (balance_deeper_called++)==0 );
   56018         rc = balance_deeper(pPage, &pCur->apPage[1]);
   56019         if( rc==SQLITE_OK ){
   56020           pCur->iPage = 1;
   56021           pCur->aiIdx[0] = 0;
   56022           pCur->aiIdx[1] = 0;
   56023           assert( pCur->apPage[1]->nOverflow );
   56024         }
   56025       }else{
   56026         break;
   56027       }
   56028     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   56029       break;
   56030     }else{
   56031       MemPage * const pParent = pCur->apPage[iPage-1];
   56032       int const iIdx = pCur->aiIdx[iPage-1];
   56033 
   56034       rc = sqlite3PagerWrite(pParent->pDbPage);
   56035       if( rc==SQLITE_OK ){
   56036 #ifndef SQLITE_OMIT_QUICKBALANCE
   56037         if( pPage->hasData
   56038          && pPage->nOverflow==1
   56039          && pPage->aiOvfl[0]==pPage->nCell
   56040          && pParent->pgno!=1
   56041          && pParent->nCell==iIdx
   56042         ){
   56043           /* Call balance_quick() to create a new sibling of pPage on which
   56044           ** to store the overflow cell. balance_quick() inserts a new cell
   56045           ** into pParent, which may cause pParent overflow. If this
   56046           ** happens, the next interation of the do-loop will balance pParent
   56047           ** use either balance_nonroot() or balance_deeper(). Until this
   56048           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   56049           ** buffer.
   56050           **
   56051           ** The purpose of the following assert() is to check that only a
   56052           ** single call to balance_quick() is made for each call to this
   56053           ** function. If this were not verified, a subtle bug involving reuse
   56054           ** of the aBalanceQuickSpace[] might sneak in.
   56055           */
   56056           assert( (balance_quick_called++)==0 );
   56057           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   56058         }else
   56059 #endif
   56060         {
   56061           /* In this case, call balance_nonroot() to redistribute cells
   56062           ** between pPage and up to 2 of its sibling pages. This involves
   56063           ** modifying the contents of pParent, which may cause pParent to
   56064           ** become overfull or underfull. The next iteration of the do-loop
   56065           ** will balance the parent page to correct this.
   56066           **
   56067           ** If the parent page becomes overfull, the overflow cell or cells
   56068           ** are stored in the pSpace buffer allocated immediately below.
   56069           ** A subsequent iteration of the do-loop will deal with this by
   56070           ** calling balance_nonroot() (balance_deeper() may be called first,
   56071           ** but it doesn't deal with overflow cells - just moves them to a
   56072           ** different page). Once this subsequent call to balance_nonroot()
   56073           ** has completed, it is safe to release the pSpace buffer used by
   56074           ** the previous call, as the overflow cell data will have been
   56075           ** copied either into the body of a database page or into the new
   56076           ** pSpace buffer passed to the latter call to balance_nonroot().
   56077           */
   56078           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   56079           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
   56080           if( pFree ){
   56081             /* If pFree is not NULL, it points to the pSpace buffer used
   56082             ** by a previous call to balance_nonroot(). Its contents are
   56083             ** now stored either on real database pages or within the
   56084             ** new pSpace buffer, so it may be safely freed here. */
   56085             sqlite3PageFree(pFree);
   56086           }
   56087 
   56088           /* The pSpace buffer will be freed after the next call to
   56089           ** balance_nonroot(), or just before this function returns, whichever
   56090           ** comes first. */
   56091           pFree = pSpace;
   56092         }
   56093       }
   56094 
   56095       pPage->nOverflow = 0;
   56096 
   56097       /* The next iteration of the do-loop balances the parent page. */
   56098       releasePage(pPage);
   56099       pCur->iPage--;
   56100     }
   56101   }while( rc==SQLITE_OK );
   56102 
   56103   if( pFree ){
   56104     sqlite3PageFree(pFree);
   56105   }
   56106   return rc;
   56107 }
   56108 
   56109 
   56110 /*
   56111 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   56112 ** and the data is given by (pData,nData).  The cursor is used only to
   56113 ** define what table the record should be inserted into.  The cursor
   56114 ** is left pointing at a random location.
   56115 **
   56116 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   56117 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   56118 **
   56119 ** If the seekResult parameter is non-zero, then a successful call to
   56120 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   56121 ** been performed. seekResult is the search result returned (a negative
   56122 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   56123 ** a positive value if pCur points at an etry that is larger than
   56124 ** (pKey, nKey)).
   56125 **
   56126 ** If the seekResult parameter is non-zero, then the caller guarantees that
   56127 ** cursor pCur is pointing at the existing copy of a row that is to be
   56128 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   56129 ** point to any entry or to no entry at all and so this function has to seek
   56130 ** the cursor before the new key can be inserted.
   56131 */
   56132 SQLITE_PRIVATE int sqlite3BtreeInsert(
   56133   BtCursor *pCur,                /* Insert data into the table of this cursor */
   56134   const void *pKey, i64 nKey,    /* The key of the new record */
   56135   const void *pData, int nData,  /* The data of the new record */
   56136   int nZero,                     /* Number of extra 0 bytes to append to data */
   56137   int appendBias,                /* True if this is likely an append */
   56138   int seekResult                 /* Result of prior MovetoUnpacked() call */
   56139 ){
   56140   int rc;
   56141   int loc = seekResult;          /* -1: before desired location  +1: after */
   56142   int szNew = 0;
   56143   int idx;
   56144   MemPage *pPage;
   56145   Btree *p = pCur->pBtree;
   56146   BtShared *pBt = p->pBt;
   56147   unsigned char *oldCell;
   56148   unsigned char *newCell = 0;
   56149 
   56150   if( pCur->eState==CURSOR_FAULT ){
   56151     assert( pCur->skipNext!=SQLITE_OK );
   56152     return pCur->skipNext;
   56153   }
   56154 
   56155   assert( cursorHoldsMutex(pCur) );
   56156   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
   56157               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56158   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   56159 
   56160   /* Assert that the caller has been consistent. If this cursor was opened
   56161   ** expecting an index b-tree, then the caller should be inserting blob
   56162   ** keys with no associated data. If the cursor was opened expecting an
   56163   ** intkey table, the caller should be inserting integer keys with a
   56164   ** blob of associated data.  */
   56165   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   56166 
   56167   /* If this is an insert into a table b-tree, invalidate any incrblob
   56168   ** cursors open on the row being replaced (assuming this is a replace
   56169   ** operation - if it is not, the following is a no-op).  */
   56170   if( pCur->pKeyInfo==0 ){
   56171     invalidateIncrblobCursors(p, nKey, 0);
   56172   }
   56173 
   56174   /* Save the positions of any other cursors open on this table.
   56175   **
   56176   ** In some cases, the call to btreeMoveto() below is a no-op. For
   56177   ** example, when inserting data into a table with auto-generated integer
   56178   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   56179   ** integer key to use. It then calls this function to actually insert the
   56180   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   56181   ** that the cursor is already where it needs to be and returns without
   56182   ** doing any work. To avoid thwarting these optimizations, it is important
   56183   ** not to clear the cursor here.
   56184   */
   56185   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   56186   if( rc ) return rc;
   56187   if( !loc ){
   56188     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   56189     if( rc ) return rc;
   56190   }
   56191   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   56192 
   56193   pPage = pCur->apPage[pCur->iPage];
   56194   assert( pPage->intKey || nKey>=0 );
   56195   assert( pPage->leaf || !pPage->intKey );
   56196 
   56197   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   56198           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   56199           loc==0 ? "overwrite" : "new entry"));
   56200   assert( pPage->isInit );
   56201   allocateTempSpace(pBt);
   56202   newCell = pBt->pTmpSpace;
   56203   if( newCell==0 ) return SQLITE_NOMEM;
   56204   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   56205   if( rc ) goto end_insert;
   56206   assert( szNew==cellSizePtr(pPage, newCell) );
   56207   assert( szNew <= MX_CELL_SIZE(pBt) );
   56208   idx = pCur->aiIdx[pCur->iPage];
   56209   if( loc==0 ){
   56210     u16 szOld;
   56211     assert( idx<pPage->nCell );
   56212     rc = sqlite3PagerWrite(pPage->pDbPage);
   56213     if( rc ){
   56214       goto end_insert;
   56215     }
   56216     oldCell = findCell(pPage, idx);
   56217     if( !pPage->leaf ){
   56218       memcpy(newCell, oldCell, 4);
   56219     }
   56220     szOld = cellSizePtr(pPage, oldCell);
   56221     rc = clearCell(pPage, oldCell);
   56222     dropCell(pPage, idx, szOld, &rc);
   56223     if( rc ) goto end_insert;
   56224   }else if( loc<0 && pPage->nCell>0 ){
   56225     assert( pPage->leaf );
   56226     idx = ++pCur->aiIdx[pCur->iPage];
   56227   }else{
   56228     assert( pPage->leaf );
   56229   }
   56230   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   56231   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   56232 
   56233   /* If no error has occured and pPage has an overflow cell, call balance()
   56234   ** to redistribute the cells within the tree. Since balance() may move
   56235   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
   56236   ** variables.
   56237   **
   56238   ** Previous versions of SQLite called moveToRoot() to move the cursor
   56239   ** back to the root page as balance() used to invalidate the contents
   56240   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   56241   ** set the cursor state to "invalid". This makes common insert operations
   56242   ** slightly faster.
   56243   **
   56244   ** There is a subtle but important optimization here too. When inserting
   56245   ** multiple records into an intkey b-tree using a single cursor (as can
   56246   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   56247   ** is advantageous to leave the cursor pointing to the last entry in
   56248   ** the b-tree if possible. If the cursor is left pointing to the last
   56249   ** entry in the table, and the next row inserted has an integer key
   56250   ** larger than the largest existing key, it is possible to insert the
   56251   ** row without seeking the cursor. This can be a big performance boost.
   56252   */
   56253   pCur->info.nSize = 0;
   56254   pCur->validNKey = 0;
   56255   if( rc==SQLITE_OK && pPage->nOverflow ){
   56256     rc = balance(pCur);
   56257 
   56258     /* Must make sure nOverflow is reset to zero even if the balance()
   56259     ** fails. Internal data structure corruption will result otherwise.
   56260     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   56261     ** from trying to save the current position of the cursor.  */
   56262     pCur->apPage[pCur->iPage]->nOverflow = 0;
   56263     pCur->eState = CURSOR_INVALID;
   56264   }
   56265   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   56266 
   56267 end_insert:
   56268   return rc;
   56269 }
   56270 
   56271 /*
   56272 ** Delete the entry that the cursor is pointing to.  The cursor
   56273 ** is left pointing at a arbitrary location.
   56274 */
   56275 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   56276   Btree *p = pCur->pBtree;
   56277   BtShared *pBt = p->pBt;
   56278   int rc;                              /* Return code */
   56279   MemPage *pPage;                      /* Page to delete cell from */
   56280   unsigned char *pCell;                /* Pointer to cell to delete */
   56281   int iCellIdx;                        /* Index of cell to delete */
   56282   int iCellDepth;                      /* Depth of node containing pCell */
   56283 
   56284   assert( cursorHoldsMutex(pCur) );
   56285   assert( pBt->inTransaction==TRANS_WRITE );
   56286   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56287   assert( pCur->wrFlag );
   56288   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   56289   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   56290 
   56291   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   56292    || NEVER(pCur->eState!=CURSOR_VALID)
   56293   ){
   56294     return SQLITE_ERROR;  /* Something has gone awry. */
   56295   }
   56296 
   56297   /* If this is a delete operation to remove a row from a table b-tree,
   56298   ** invalidate any incrblob cursors open on the row being deleted.  */
   56299   if( pCur->pKeyInfo==0 ){
   56300     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   56301   }
   56302 
   56303   iCellDepth = pCur->iPage;
   56304   iCellIdx = pCur->aiIdx[iCellDepth];
   56305   pPage = pCur->apPage[iCellDepth];
   56306   pCell = findCell(pPage, iCellIdx);
   56307 
   56308   /* If the page containing the entry to delete is not a leaf page, move
   56309   ** the cursor to the largest entry in the tree that is smaller than
   56310   ** the entry being deleted. This cell will replace the cell being deleted
   56311   ** from the internal node. The 'previous' entry is used for this instead
   56312   ** of the 'next' entry, as the previous entry is always a part of the
   56313   ** sub-tree headed by the child page of the cell being deleted. This makes
   56314   ** balancing the tree following the delete operation easier.  */
   56315   if( !pPage->leaf ){
   56316     int notUsed;
   56317     rc = sqlite3BtreePrevious(pCur, &notUsed);
   56318     if( rc ) return rc;
   56319   }
   56320 
   56321   /* Save the positions of any other cursors open on this table before
   56322   ** making any modifications. Make the page containing the entry to be
   56323   ** deleted writable. Then free any overflow pages associated with the
   56324   ** entry and finally remove the cell itself from within the page.
   56325   */
   56326   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   56327   if( rc ) return rc;
   56328   rc = sqlite3PagerWrite(pPage->pDbPage);
   56329   if( rc ) return rc;
   56330   rc = clearCell(pPage, pCell);
   56331   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   56332   if( rc ) return rc;
   56333 
   56334   /* If the cell deleted was not located on a leaf page, then the cursor
   56335   ** is currently pointing to the largest entry in the sub-tree headed
   56336   ** by the child-page of the cell that was just deleted from an internal
   56337   ** node. The cell from the leaf node needs to be moved to the internal
   56338   ** node to replace the deleted cell.  */
   56339   if( !pPage->leaf ){
   56340     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   56341     int nCell;
   56342     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   56343     unsigned char *pTmp;
   56344 
   56345     pCell = findCell(pLeaf, pLeaf->nCell-1);
   56346     nCell = cellSizePtr(pLeaf, pCell);
   56347     assert( MX_CELL_SIZE(pBt) >= nCell );
   56348 
   56349     allocateTempSpace(pBt);
   56350     pTmp = pBt->pTmpSpace;
   56351 
   56352     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   56353     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   56354     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   56355     if( rc ) return rc;
   56356   }
   56357 
   56358   /* Balance the tree. If the entry deleted was located on a leaf page,
   56359   ** then the cursor still points to that page. In this case the first
   56360   ** call to balance() repairs the tree, and the if(...) condition is
   56361   ** never true.
   56362   **
   56363   ** Otherwise, if the entry deleted was on an internal node page, then
   56364   ** pCur is pointing to the leaf page from which a cell was removed to
   56365   ** replace the cell deleted from the internal node. This is slightly
   56366   ** tricky as the leaf node may be underfull, and the internal node may
   56367   ** be either under or overfull. In this case run the balancing algorithm
   56368   ** on the leaf node first. If the balance proceeds far enough up the
   56369   ** tree that we can be sure that any problem in the internal node has
   56370   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   56371   ** walk the cursor up the tree to the internal node and balance it as
   56372   ** well.  */
   56373   rc = balance(pCur);
   56374   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   56375     while( pCur->iPage>iCellDepth ){
   56376       releasePage(pCur->apPage[pCur->iPage--]);
   56377     }
   56378     rc = balance(pCur);
   56379   }
   56380 
   56381   if( rc==SQLITE_OK ){
   56382     moveToRoot(pCur);
   56383   }
   56384   return rc;
   56385 }
   56386 
   56387 /*
   56388 ** Create a new BTree table.  Write into *piTable the page
   56389 ** number for the root page of the new table.
   56390 **
   56391 ** The type of type is determined by the flags parameter.  Only the
   56392 ** following values of flags are currently in use.  Other values for
   56393 ** flags might not work:
   56394 **
   56395 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   56396 **     BTREE_ZERODATA                  Used for SQL indices
   56397 */
   56398 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   56399   BtShared *pBt = p->pBt;
   56400   MemPage *pRoot;
   56401   Pgno pgnoRoot;
   56402   int rc;
   56403   int ptfFlags;          /* Page-type flage for the root page of new table */
   56404 
   56405   assert( sqlite3BtreeHoldsMutex(p) );
   56406   assert( pBt->inTransaction==TRANS_WRITE );
   56407   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
   56408 
   56409 #ifdef SQLITE_OMIT_AUTOVACUUM
   56410   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   56411   if( rc ){
   56412     return rc;
   56413   }
   56414 #else
   56415   if( pBt->autoVacuum ){
   56416     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   56417     MemPage *pPageMove; /* The page to move to. */
   56418 
   56419     /* Creating a new table may probably require moving an existing database
   56420     ** to make room for the new tables root page. In case this page turns
   56421     ** out to be an overflow page, delete all overflow page-map caches
   56422     ** held by open cursors.
   56423     */
   56424     invalidateAllOverflowCache(pBt);
   56425 
   56426     /* Read the value of meta[3] from the database to determine where the
   56427     ** root page of the new table should go. meta[3] is the largest root-page
   56428     ** created so far, so the new root-page is (meta[3]+1).
   56429     */
   56430     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   56431     pgnoRoot++;
   56432 
   56433     /* The new root-page may not be allocated on a pointer-map page, or the
   56434     ** PENDING_BYTE page.
   56435     */
   56436     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   56437         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   56438       pgnoRoot++;
   56439     }
   56440     assert( pgnoRoot>=3 );
   56441 
   56442     /* Allocate a page. The page that currently resides at pgnoRoot will
   56443     ** be moved to the allocated page (unless the allocated page happens
   56444     ** to reside at pgnoRoot).
   56445     */
   56446     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
   56447     if( rc!=SQLITE_OK ){
   56448       return rc;
   56449     }
   56450 
   56451     if( pgnoMove!=pgnoRoot ){
   56452       /* pgnoRoot is the page that will be used for the root-page of
   56453       ** the new table (assuming an error did not occur). But we were
   56454       ** allocated pgnoMove. If required (i.e. if it was not allocated
   56455       ** by extending the file), the current page at position pgnoMove
   56456       ** is already journaled.
   56457       */
   56458       u8 eType = 0;
   56459       Pgno iPtrPage = 0;
   56460 
   56461       releasePage(pPageMove);
   56462 
   56463       /* Move the page currently at pgnoRoot to pgnoMove. */
   56464       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   56465       if( rc!=SQLITE_OK ){
   56466         return rc;
   56467       }
   56468       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   56469       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   56470         rc = SQLITE_CORRUPT_BKPT;
   56471       }
   56472       if( rc!=SQLITE_OK ){
   56473         releasePage(pRoot);
   56474         return rc;
   56475       }
   56476       assert( eType!=PTRMAP_ROOTPAGE );
   56477       assert( eType!=PTRMAP_FREEPAGE );
   56478       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   56479       releasePage(pRoot);
   56480 
   56481       /* Obtain the page at pgnoRoot */
   56482       if( rc!=SQLITE_OK ){
   56483         return rc;
   56484       }
   56485       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   56486       if( rc!=SQLITE_OK ){
   56487         return rc;
   56488       }
   56489       rc = sqlite3PagerWrite(pRoot->pDbPage);
   56490       if( rc!=SQLITE_OK ){
   56491         releasePage(pRoot);
   56492         return rc;
   56493       }
   56494     }else{
   56495       pRoot = pPageMove;
   56496     }
   56497 
   56498     /* Update the pointer-map and meta-data with the new root-page number. */
   56499     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   56500     if( rc ){
   56501       releasePage(pRoot);
   56502       return rc;
   56503     }
   56504 
   56505     /* When the new root page was allocated, page 1 was made writable in
   56506     ** order either to increase the database filesize, or to decrement the
   56507     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   56508     */
   56509     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   56510     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   56511     if( NEVER(rc) ){
   56512       releasePage(pRoot);
   56513       return rc;
   56514     }
   56515 
   56516   }else{
   56517     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   56518     if( rc ) return rc;
   56519   }
   56520 #endif
   56521   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   56522   if( createTabFlags & BTREE_INTKEY ){
   56523     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   56524   }else{
   56525     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   56526   }
   56527   zeroPage(pRoot, ptfFlags);
   56528   sqlite3PagerUnref(pRoot->pDbPage);
   56529   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   56530   *piTable = (int)pgnoRoot;
   56531   return SQLITE_OK;
   56532 }
   56533 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   56534   int rc;
   56535   sqlite3BtreeEnter(p);
   56536   rc = btreeCreateTable(p, piTable, flags);
   56537   sqlite3BtreeLeave(p);
   56538   return rc;
   56539 }
   56540 
   56541 /*
   56542 ** Erase the given database page and all its children.  Return
   56543 ** the page to the freelist.
   56544 */
   56545 static int clearDatabasePage(
   56546   BtShared *pBt,           /* The BTree that contains the table */
   56547   Pgno pgno,               /* Page number to clear */
   56548   int freePageFlag,        /* Deallocate page if true */
   56549   int *pnChange            /* Add number of Cells freed to this counter */
   56550 ){
   56551   MemPage *pPage;
   56552   int rc;
   56553   unsigned char *pCell;
   56554   int i;
   56555 
   56556   assert( sqlite3_mutex_held(pBt->mutex) );
   56557   if( pgno>btreePagecount(pBt) ){
   56558     return SQLITE_CORRUPT_BKPT;
   56559   }
   56560 
   56561   rc = getAndInitPage(pBt, pgno, &pPage);
   56562   if( rc ) return rc;
   56563   for(i=0; i<pPage->nCell; i++){
   56564     pCell = findCell(pPage, i);
   56565     if( !pPage->leaf ){
   56566       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   56567       if( rc ) goto cleardatabasepage_out;
   56568     }
   56569     rc = clearCell(pPage, pCell);
   56570     if( rc ) goto cleardatabasepage_out;
   56571   }
   56572   if( !pPage->leaf ){
   56573     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
   56574     if( rc ) goto cleardatabasepage_out;
   56575   }else if( pnChange ){
   56576     assert( pPage->intKey );
   56577     *pnChange += pPage->nCell;
   56578   }
   56579   if( freePageFlag ){
   56580     freePage(pPage, &rc);
   56581   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   56582     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
   56583   }
   56584 
   56585 cleardatabasepage_out:
   56586   releasePage(pPage);
   56587   return rc;
   56588 }
   56589 
   56590 /*
   56591 ** Delete all information from a single table in the database.  iTable is
   56592 ** the page number of the root of the table.  After this routine returns,
   56593 ** the root page is empty, but still exists.
   56594 **
   56595 ** This routine will fail with SQLITE_LOCKED if there are any open
   56596 ** read cursors on the table.  Open write cursors are moved to the
   56597 ** root of the table.
   56598 **
   56599 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   56600 ** integer value pointed to by pnChange is incremented by the number of
   56601 ** entries in the table.
   56602 */
   56603 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   56604   int rc;
   56605   BtShared *pBt = p->pBt;
   56606   sqlite3BtreeEnter(p);
   56607   assert( p->inTrans==TRANS_WRITE );
   56608 
   56609   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   56610   ** is the root of a table b-tree - if it is not, the following call is
   56611   ** a no-op).  */
   56612   invalidateIncrblobCursors(p, 0, 1);
   56613 
   56614   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   56615   if( SQLITE_OK==rc ){
   56616     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   56617   }
   56618   sqlite3BtreeLeave(p);
   56619   return rc;
   56620 }
   56621 
   56622 /*
   56623 ** Erase all information in a table and add the root of the table to
   56624 ** the freelist.  Except, the root of the principle table (the one on
   56625 ** page 1) is never added to the freelist.
   56626 **
   56627 ** This routine will fail with SQLITE_LOCKED if there are any open
   56628 ** cursors on the table.
   56629 **
   56630 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   56631 ** root page in the database file, then the last root page
   56632 ** in the database file is moved into the slot formerly occupied by
   56633 ** iTable and that last slot formerly occupied by the last root page
   56634 ** is added to the freelist instead of iTable.  In this say, all
   56635 ** root pages are kept at the beginning of the database file, which
   56636 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   56637 ** page number that used to be the last root page in the file before
   56638 ** the move.  If no page gets moved, *piMoved is set to 0.
   56639 ** The last root page is recorded in meta[3] and the value of
   56640 ** meta[3] is updated by this procedure.
   56641 */
   56642 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   56643   int rc;
   56644   MemPage *pPage = 0;
   56645   BtShared *pBt = p->pBt;
   56646 
   56647   assert( sqlite3BtreeHoldsMutex(p) );
   56648   assert( p->inTrans==TRANS_WRITE );
   56649 
   56650   /* It is illegal to drop a table if any cursors are open on the
   56651   ** database. This is because in auto-vacuum mode the backend may
   56652   ** need to move another root-page to fill a gap left by the deleted
   56653   ** root page. If an open cursor was using this page a problem would
   56654   ** occur.
   56655   **
   56656   ** This error is caught long before control reaches this point.
   56657   */
   56658   if( NEVER(pBt->pCursor) ){
   56659     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   56660     return SQLITE_LOCKED_SHAREDCACHE;
   56661   }
   56662 
   56663   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   56664   if( rc ) return rc;
   56665   rc = sqlite3BtreeClearTable(p, iTable, 0);
   56666   if( rc ){
   56667     releasePage(pPage);
   56668     return rc;
   56669   }
   56670 
   56671   *piMoved = 0;
   56672 
   56673   if( iTable>1 ){
   56674 #ifdef SQLITE_OMIT_AUTOVACUUM
   56675     freePage(pPage, &rc);
   56676     releasePage(pPage);
   56677 #else
   56678     if( pBt->autoVacuum ){
   56679       Pgno maxRootPgno;
   56680       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   56681 
   56682       if( iTable==maxRootPgno ){
   56683         /* If the table being dropped is the table with the largest root-page
   56684         ** number in the database, put the root page on the free list.
   56685         */
   56686         freePage(pPage, &rc);
   56687         releasePage(pPage);
   56688         if( rc!=SQLITE_OK ){
   56689           return rc;
   56690         }
   56691       }else{
   56692         /* The table being dropped does not have the largest root-page
   56693         ** number in the database. So move the page that does into the
   56694         ** gap left by the deleted root-page.
   56695         */
   56696         MemPage *pMove;
   56697         releasePage(pPage);
   56698         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   56699         if( rc!=SQLITE_OK ){
   56700           return rc;
   56701         }
   56702         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   56703         releasePage(pMove);
   56704         if( rc!=SQLITE_OK ){
   56705           return rc;
   56706         }
   56707         pMove = 0;
   56708         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   56709         freePage(pMove, &rc);
   56710         releasePage(pMove);
   56711         if( rc!=SQLITE_OK ){
   56712           return rc;
   56713         }
   56714         *piMoved = maxRootPgno;
   56715       }
   56716 
   56717       /* Set the new 'max-root-page' value in the database header. This
   56718       ** is the old value less one, less one more if that happens to
   56719       ** be a root-page number, less one again if that is the
   56720       ** PENDING_BYTE_PAGE.
   56721       */
   56722       maxRootPgno--;
   56723       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   56724              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   56725         maxRootPgno--;
   56726       }
   56727       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   56728 
   56729       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   56730     }else{
   56731       freePage(pPage, &rc);
   56732       releasePage(pPage);
   56733     }
   56734 #endif
   56735   }else{
   56736     /* If sqlite3BtreeDropTable was called on page 1.
   56737     ** This really never should happen except in a corrupt
   56738     ** database.
   56739     */
   56740     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   56741     releasePage(pPage);
   56742   }
   56743   return rc;
   56744 }
   56745 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   56746   int rc;
   56747   sqlite3BtreeEnter(p);
   56748   rc = btreeDropTable(p, iTable, piMoved);
   56749   sqlite3BtreeLeave(p);
   56750   return rc;
   56751 }
   56752 
   56753 
   56754 /*
   56755 ** This function may only be called if the b-tree connection already
   56756 ** has a read or write transaction open on the database.
   56757 **
   56758 ** Read the meta-information out of a database file.  Meta[0]
   56759 ** is the number of free pages currently in the database.  Meta[1]
   56760 ** through meta[15] are available for use by higher layers.  Meta[0]
   56761 ** is read-only, the others are read/write.
   56762 **
   56763 ** The schema layer numbers meta values differently.  At the schema
   56764 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   56765 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   56766 */
   56767 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   56768   BtShared *pBt = p->pBt;
   56769 
   56770   sqlite3BtreeEnter(p);
   56771   assert( p->inTrans>TRANS_NONE );
   56772   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   56773   assert( pBt->pPage1 );
   56774   assert( idx>=0 && idx<=15 );
   56775 
   56776   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   56777 
   56778   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   56779   ** database, mark the database as read-only.  */
   56780 #ifdef SQLITE_OMIT_AUTOVACUUM
   56781   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
   56782     pBt->btsFlags |= BTS_READ_ONLY;
   56783   }
   56784 #endif
   56785 
   56786   sqlite3BtreeLeave(p);
   56787 }
   56788 
   56789 /*
   56790 ** Write meta-information back into the database.  Meta[0] is
   56791 ** read-only and may not be written.
   56792 */
   56793 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   56794   BtShared *pBt = p->pBt;
   56795   unsigned char *pP1;
   56796   int rc;
   56797   assert( idx>=1 && idx<=15 );
   56798   sqlite3BtreeEnter(p);
   56799   assert( p->inTrans==TRANS_WRITE );
   56800   assert( pBt->pPage1!=0 );
   56801   pP1 = pBt->pPage1->aData;
   56802   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   56803   if( rc==SQLITE_OK ){
   56804     put4byte(&pP1[36 + idx*4], iMeta);
   56805 #ifndef SQLITE_OMIT_AUTOVACUUM
   56806     if( idx==BTREE_INCR_VACUUM ){
   56807       assert( pBt->autoVacuum || iMeta==0 );
   56808       assert( iMeta==0 || iMeta==1 );
   56809       pBt->incrVacuum = (u8)iMeta;
   56810     }
   56811 #endif
   56812   }
   56813   sqlite3BtreeLeave(p);
   56814   return rc;
   56815 }
   56816 
   56817 #ifndef SQLITE_OMIT_BTREECOUNT
   56818 /*
   56819 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   56820 ** number of entries in the b-tree and write the result to *pnEntry.
   56821 **
   56822 ** SQLITE_OK is returned if the operation is successfully executed.
   56823 ** Otherwise, if an error is encountered (i.e. an IO error or database
   56824 ** corruption) an SQLite error code is returned.
   56825 */
   56826 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   56827   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   56828   int rc;                              /* Return code */
   56829 
   56830   if( pCur->pgnoRoot==0 ){
   56831     *pnEntry = 0;
   56832     return SQLITE_OK;
   56833   }
   56834   rc = moveToRoot(pCur);
   56835 
   56836   /* Unless an error occurs, the following loop runs one iteration for each
   56837   ** page in the B-Tree structure (not including overflow pages).
   56838   */
   56839   while( rc==SQLITE_OK ){
   56840     int iIdx;                          /* Index of child node in parent */
   56841     MemPage *pPage;                    /* Current page of the b-tree */
   56842 
   56843     /* If this is a leaf page or the tree is not an int-key tree, then
   56844     ** this page contains countable entries. Increment the entry counter
   56845     ** accordingly.
   56846     */
   56847     pPage = pCur->apPage[pCur->iPage];
   56848     if( pPage->leaf || !pPage->intKey ){
   56849       nEntry += pPage->nCell;
   56850     }
   56851 
   56852     /* pPage is a leaf node. This loop navigates the cursor so that it
   56853     ** points to the first interior cell that it points to the parent of
   56854     ** the next page in the tree that has not yet been visited. The
   56855     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   56856     ** of the page, or to the number of cells in the page if the next page
   56857     ** to visit is the right-child of its parent.
   56858     **
   56859     ** If all pages in the tree have been visited, return SQLITE_OK to the
   56860     ** caller.
   56861     */
   56862     if( pPage->leaf ){
   56863       do {
   56864         if( pCur->iPage==0 ){
   56865           /* All pages of the b-tree have been visited. Return successfully. */
   56866           *pnEntry = nEntry;
   56867           return SQLITE_OK;
   56868         }
   56869         moveToParent(pCur);
   56870       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   56871 
   56872       pCur->aiIdx[pCur->iPage]++;
   56873       pPage = pCur->apPage[pCur->iPage];
   56874     }
   56875 
   56876     /* Descend to the child node of the cell that the cursor currently
   56877     ** points at. This is the right-child if (iIdx==pPage->nCell).
   56878     */
   56879     iIdx = pCur->aiIdx[pCur->iPage];
   56880     if( iIdx==pPage->nCell ){
   56881       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   56882     }else{
   56883       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   56884     }
   56885   }
   56886 
   56887   /* An error has occurred. Return an error code. */
   56888   return rc;
   56889 }
   56890 #endif
   56891 
   56892 /*
   56893 ** Return the pager associated with a BTree.  This routine is used for
   56894 ** testing and debugging only.
   56895 */
   56896 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   56897   return p->pBt->pPager;
   56898 }
   56899 
   56900 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   56901 /*
   56902 ** Append a message to the error message string.
   56903 */
   56904 static void checkAppendMsg(
   56905   IntegrityCk *pCheck,
   56906   char *zMsg1,
   56907   const char *zFormat,
   56908   ...
   56909 ){
   56910   va_list ap;
   56911   if( !pCheck->mxErr ) return;
   56912   pCheck->mxErr--;
   56913   pCheck->nErr++;
   56914   va_start(ap, zFormat);
   56915   if( pCheck->errMsg.nChar ){
   56916     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   56917   }
   56918   if( zMsg1 ){
   56919     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
   56920   }
   56921   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   56922   va_end(ap);
   56923   if( pCheck->errMsg.mallocFailed ){
   56924     pCheck->mallocFailed = 1;
   56925   }
   56926 }
   56927 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   56928 
   56929 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   56930 /*
   56931 ** Add 1 to the reference count for page iPage.  If this is the second
   56932 ** reference to the page, add an error message to pCheck->zErrMsg.
   56933 ** Return 1 if there are 2 ore more references to the page and 0 if
   56934 ** if this is the first reference to the page.
   56935 **
   56936 ** Also check that the page number is in bounds.
   56937 */
   56938 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   56939   if( iPage==0 ) return 1;
   56940   if( iPage>pCheck->nPage ){
   56941     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   56942     return 1;
   56943   }
   56944   if( pCheck->anRef[iPage]==1 ){
   56945     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   56946     return 1;
   56947   }
   56948   return  (pCheck->anRef[iPage]++)>1;
   56949 }
   56950 
   56951 #ifndef SQLITE_OMIT_AUTOVACUUM
   56952 /*
   56953 ** Check that the entry in the pointer-map for page iChild maps to
   56954 ** page iParent, pointer type ptrType. If not, append an error message
   56955 ** to pCheck.
   56956 */
   56957 static void checkPtrmap(
   56958   IntegrityCk *pCheck,   /* Integrity check context */
   56959   Pgno iChild,           /* Child page number */
   56960   u8 eType,              /* Expected pointer map type */
   56961   Pgno iParent,          /* Expected pointer map parent page number */
   56962   char *zContext         /* Context description (used for error msg) */
   56963 ){
   56964   int rc;
   56965   u8 ePtrmapType;
   56966   Pgno iPtrmapParent;
   56967 
   56968   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   56969   if( rc!=SQLITE_OK ){
   56970     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   56971     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   56972     return;
   56973   }
   56974 
   56975   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   56976     checkAppendMsg(pCheck, zContext,
   56977       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   56978       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   56979   }
   56980 }
   56981 #endif
   56982 
   56983 /*
   56984 ** Check the integrity of the freelist or of an overflow page list.
   56985 ** Verify that the number of pages on the list is N.
   56986 */
   56987 static void checkList(
   56988   IntegrityCk *pCheck,  /* Integrity checking context */
   56989   int isFreeList,       /* True for a freelist.  False for overflow page list */
   56990   int iPage,            /* Page number for first page in the list */
   56991   int N,                /* Expected number of pages in the list */
   56992   char *zContext        /* Context for error messages */
   56993 ){
   56994   int i;
   56995   int expected = N;
   56996   int iFirst = iPage;
   56997   while( N-- > 0 && pCheck->mxErr ){
   56998     DbPage *pOvflPage;
   56999     unsigned char *pOvflData;
   57000     if( iPage<1 ){
   57001       checkAppendMsg(pCheck, zContext,
   57002          "%d of %d pages missing from overflow list starting at %d",
   57003           N+1, expected, iFirst);
   57004       break;
   57005     }
   57006     if( checkRef(pCheck, iPage, zContext) ) break;
   57007     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   57008       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   57009       break;
   57010     }
   57011     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   57012     if( isFreeList ){
   57013       int n = get4byte(&pOvflData[4]);
   57014 #ifndef SQLITE_OMIT_AUTOVACUUM
   57015       if( pCheck->pBt->autoVacuum ){
   57016         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   57017       }
   57018 #endif
   57019       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   57020         checkAppendMsg(pCheck, zContext,
   57021            "freelist leaf count too big on page %d", iPage);
   57022         N--;
   57023       }else{
   57024         for(i=0; i<n; i++){
   57025           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   57026 #ifndef SQLITE_OMIT_AUTOVACUUM
   57027           if( pCheck->pBt->autoVacuum ){
   57028             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   57029           }
   57030 #endif
   57031           checkRef(pCheck, iFreePage, zContext);
   57032         }
   57033         N -= n;
   57034       }
   57035     }
   57036 #ifndef SQLITE_OMIT_AUTOVACUUM
   57037     else{
   57038       /* If this database supports auto-vacuum and iPage is not the last
   57039       ** page in this overflow list, check that the pointer-map entry for
   57040       ** the following page matches iPage.
   57041       */
   57042       if( pCheck->pBt->autoVacuum && N>0 ){
   57043         i = get4byte(pOvflData);
   57044         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   57045       }
   57046     }
   57047 #endif
   57048     iPage = get4byte(pOvflData);
   57049     sqlite3PagerUnref(pOvflPage);
   57050   }
   57051 }
   57052 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57053 
   57054 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   57055 /*
   57056 ** Do various sanity checks on a single page of a tree.  Return
   57057 ** the tree depth.  Root pages return 0.  Parents of root pages
   57058 ** return 1, and so forth.
   57059 **
   57060 ** These checks are done:
   57061 **
   57062 **      1.  Make sure that cells and freeblocks do not overlap
   57063 **          but combine to completely cover the page.
   57064 **  NO  2.  Make sure cell keys are in order.
   57065 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   57066 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   57067 **      5.  Check the integrity of overflow pages.
   57068 **      6.  Recursively call checkTreePage on all children.
   57069 **      7.  Verify that the depth of all children is the same.
   57070 **      8.  Make sure this page is at least 33% full or else it is
   57071 **          the root of the tree.
   57072 */
   57073 static int checkTreePage(
   57074   IntegrityCk *pCheck,  /* Context for the sanity check */
   57075   int iPage,            /* Page number of the page to check */
   57076   char *zParentContext, /* Parent context */
   57077   i64 *pnParentMinKey,
   57078   i64 *pnParentMaxKey
   57079 ){
   57080   MemPage *pPage;
   57081   int i, rc, depth, d2, pgno, cnt;
   57082   int hdr, cellStart;
   57083   int nCell;
   57084   u8 *data;
   57085   BtShared *pBt;
   57086   int usableSize;
   57087   char zContext[100];
   57088   char *hit = 0;
   57089   i64 nMinKey = 0;
   57090   i64 nMaxKey = 0;
   57091 
   57092   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   57093 
   57094   /* Check that the page exists
   57095   */
   57096   pBt = pCheck->pBt;
   57097   usableSize = pBt->usableSize;
   57098   if( iPage==0 ) return 0;
   57099   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   57100   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   57101     checkAppendMsg(pCheck, zContext,
   57102        "unable to get the page. error code=%d", rc);
   57103     return 0;
   57104   }
   57105 
   57106   /* Clear MemPage.isInit to make sure the corruption detection code in
   57107   ** btreeInitPage() is executed.  */
   57108   pPage->isInit = 0;
   57109   if( (rc = btreeInitPage(pPage))!=0 ){
   57110     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   57111     checkAppendMsg(pCheck, zContext,
   57112                    "btreeInitPage() returns error code %d", rc);
   57113     releasePage(pPage);
   57114     return 0;
   57115   }
   57116 
   57117   /* Check out all the cells.
   57118   */
   57119   depth = 0;
   57120   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   57121     u8 *pCell;
   57122     u32 sz;
   57123     CellInfo info;
   57124 
   57125     /* Check payload overflow pages
   57126     */
   57127     sqlite3_snprintf(sizeof(zContext), zContext,
   57128              "On tree page %d cell %d: ", iPage, i);
   57129     pCell = findCell(pPage,i);
   57130     btreeParseCellPtr(pPage, pCell, &info);
   57131     sz = info.nData;
   57132     if( !pPage->intKey ) sz += (int)info.nKey;
   57133     /* For intKey pages, check that the keys are in order.
   57134     */
   57135     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   57136     else{
   57137       if( info.nKey <= nMaxKey ){
   57138         checkAppendMsg(pCheck, zContext,
   57139             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   57140       }
   57141       nMaxKey = info.nKey;
   57142     }
   57143     assert( sz==info.nPayload );
   57144     if( (sz>info.nLocal)
   57145      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   57146     ){
   57147       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   57148       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   57149 #ifndef SQLITE_OMIT_AUTOVACUUM
   57150       if( pBt->autoVacuum ){
   57151         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   57152       }
   57153 #endif
   57154       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   57155     }
   57156 
   57157     /* Check sanity of left child page.
   57158     */
   57159     if( !pPage->leaf ){
   57160       pgno = get4byte(pCell);
   57161 #ifndef SQLITE_OMIT_AUTOVACUUM
   57162       if( pBt->autoVacuum ){
   57163         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   57164       }
   57165 #endif
   57166       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   57167       if( i>0 && d2!=depth ){
   57168         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   57169       }
   57170       depth = d2;
   57171     }
   57172   }
   57173 
   57174   if( !pPage->leaf ){
   57175     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   57176     sqlite3_snprintf(sizeof(zContext), zContext,
   57177                      "On page %d at right child: ", iPage);
   57178 #ifndef SQLITE_OMIT_AUTOVACUUM
   57179     if( pBt->autoVacuum ){
   57180       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   57181     }
   57182 #endif
   57183     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   57184   }
   57185 
   57186   /* For intKey leaf pages, check that the min/max keys are in order
   57187   ** with any left/parent/right pages.
   57188   */
   57189   if( pPage->leaf && pPage->intKey ){
   57190     /* if we are a left child page */
   57191     if( pnParentMinKey ){
   57192       /* if we are the left most child page */
   57193       if( !pnParentMaxKey ){
   57194         if( nMaxKey > *pnParentMinKey ){
   57195           checkAppendMsg(pCheck, zContext,
   57196               "Rowid %lld out of order (max larger than parent min of %lld)",
   57197               nMaxKey, *pnParentMinKey);
   57198         }
   57199       }else{
   57200         if( nMinKey <= *pnParentMinKey ){
   57201           checkAppendMsg(pCheck, zContext,
   57202               "Rowid %lld out of order (min less than parent min of %lld)",
   57203               nMinKey, *pnParentMinKey);
   57204         }
   57205         if( nMaxKey > *pnParentMaxKey ){
   57206           checkAppendMsg(pCheck, zContext,
   57207               "Rowid %lld out of order (max larger than parent max of %lld)",
   57208               nMaxKey, *pnParentMaxKey);
   57209         }
   57210         *pnParentMinKey = nMaxKey;
   57211       }
   57212     /* else if we're a right child page */
   57213     } else if( pnParentMaxKey ){
   57214       if( nMinKey <= *pnParentMaxKey ){
   57215         checkAppendMsg(pCheck, zContext,
   57216             "Rowid %lld out of order (min less than parent max of %lld)",
   57217             nMinKey, *pnParentMaxKey);
   57218       }
   57219     }
   57220   }
   57221 
   57222   /* Check for complete coverage of the page
   57223   */
   57224   data = pPage->aData;
   57225   hdr = pPage->hdrOffset;
   57226   hit = sqlite3PageMalloc( pBt->pageSize );
   57227   if( hit==0 ){
   57228     pCheck->mallocFailed = 1;
   57229   }else{
   57230     int contentOffset = get2byteNotZero(&data[hdr+5]);
   57231     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   57232     memset(hit+contentOffset, 0, usableSize-contentOffset);
   57233     memset(hit, 1, contentOffset);
   57234     nCell = get2byte(&data[hdr+3]);
   57235     cellStart = hdr + 12 - 4*pPage->leaf;
   57236     for(i=0; i<nCell; i++){
   57237       int pc = get2byte(&data[cellStart+i*2]);
   57238       u32 size = 65536;
   57239       int j;
   57240       if( pc<=usableSize-4 ){
   57241         size = cellSizePtr(pPage, &data[pc]);
   57242       }
   57243       if( (int)(pc+size-1)>=usableSize ){
   57244         checkAppendMsg(pCheck, 0,
   57245             "Corruption detected in cell %d on page %d",i,iPage);
   57246       }else{
   57247         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   57248       }
   57249     }
   57250     i = get2byte(&data[hdr+1]);
   57251     while( i>0 ){
   57252       int size, j;
   57253       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   57254       size = get2byte(&data[i+2]);
   57255       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   57256       for(j=i+size-1; j>=i; j--) hit[j]++;
   57257       j = get2byte(&data[i]);
   57258       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   57259       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   57260       i = j;
   57261     }
   57262     for(i=cnt=0; i<usableSize; i++){
   57263       if( hit[i]==0 ){
   57264         cnt++;
   57265       }else if( hit[i]>1 ){
   57266         checkAppendMsg(pCheck, 0,
   57267           "Multiple uses for byte %d of page %d", i, iPage);
   57268         break;
   57269       }
   57270     }
   57271     if( cnt!=data[hdr+7] ){
   57272       checkAppendMsg(pCheck, 0,
   57273           "Fragmentation of %d bytes reported as %d on page %d",
   57274           cnt, data[hdr+7], iPage);
   57275     }
   57276   }
   57277   sqlite3PageFree(hit);
   57278   releasePage(pPage);
   57279   return depth+1;
   57280 }
   57281 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57282 
   57283 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   57284 /*
   57285 ** This routine does a complete check of the given BTree file.  aRoot[] is
   57286 ** an array of pages numbers were each page number is the root page of
   57287 ** a table.  nRoot is the number of entries in aRoot.
   57288 **
   57289 ** A read-only or read-write transaction must be opened before calling
   57290 ** this function.
   57291 **
   57292 ** Write the number of error seen in *pnErr.  Except for some memory
   57293 ** allocation errors,  an error message held in memory obtained from
   57294 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   57295 ** returned.  If a memory allocation error occurs, NULL is returned.
   57296 */
   57297 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   57298   Btree *p,     /* The btree to be checked */
   57299   int *aRoot,   /* An array of root pages numbers for individual trees */
   57300   int nRoot,    /* Number of entries in aRoot[] */
   57301   int mxErr,    /* Stop reporting errors after this many */
   57302   int *pnErr    /* Write number of errors seen to this variable */
   57303 ){
   57304   Pgno i;
   57305   int nRef;
   57306   IntegrityCk sCheck;
   57307   BtShared *pBt = p->pBt;
   57308   char zErr[100];
   57309 
   57310   sqlite3BtreeEnter(p);
   57311   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   57312   nRef = sqlite3PagerRefcount(pBt->pPager);
   57313   sCheck.pBt = pBt;
   57314   sCheck.pPager = pBt->pPager;
   57315   sCheck.nPage = btreePagecount(sCheck.pBt);
   57316   sCheck.mxErr = mxErr;
   57317   sCheck.nErr = 0;
   57318   sCheck.mallocFailed = 0;
   57319   *pnErr = 0;
   57320   if( sCheck.nPage==0 ){
   57321     sqlite3BtreeLeave(p);
   57322     return 0;
   57323   }
   57324   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
   57325   if( !sCheck.anRef ){
   57326     *pnErr = 1;
   57327     sqlite3BtreeLeave(p);
   57328     return 0;
   57329   }
   57330   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
   57331   i = PENDING_BYTE_PAGE(pBt);
   57332   if( i<=sCheck.nPage ){
   57333     sCheck.anRef[i] = 1;
   57334   }
   57335   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
   57336   sCheck.errMsg.useMalloc = 2;
   57337 
   57338   /* Check the integrity of the freelist
   57339   */
   57340   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   57341             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   57342 
   57343   /* Check all the tables.
   57344   */
   57345   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   57346     if( aRoot[i]==0 ) continue;
   57347 #ifndef SQLITE_OMIT_AUTOVACUUM
   57348     if( pBt->autoVacuum && aRoot[i]>1 ){
   57349       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   57350     }
   57351 #endif
   57352     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   57353   }
   57354 
   57355   /* Make sure every page in the file is referenced
   57356   */
   57357   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   57358 #ifdef SQLITE_OMIT_AUTOVACUUM
   57359     if( sCheck.anRef[i]==0 ){
   57360       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   57361     }
   57362 #else
   57363     /* If the database supports auto-vacuum, make sure no tables contain
   57364     ** references to pointer-map pages.
   57365     */
   57366     if( sCheck.anRef[i]==0 &&
   57367        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   57368       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   57369     }
   57370     if( sCheck.anRef[i]!=0 &&
   57371        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   57372       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   57373     }
   57374 #endif
   57375   }
   57376 
   57377   /* Make sure this analysis did not leave any unref() pages.
   57378   ** This is an internal consistency check; an integrity check
   57379   ** of the integrity check.
   57380   */
   57381   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   57382     checkAppendMsg(&sCheck, 0,
   57383       "Outstanding page count goes from %d to %d during this analysis",
   57384       nRef, sqlite3PagerRefcount(pBt->pPager)
   57385     );
   57386   }
   57387 
   57388   /* Clean  up and report errors.
   57389   */
   57390   sqlite3BtreeLeave(p);
   57391   sqlite3_free(sCheck.anRef);
   57392   if( sCheck.mallocFailed ){
   57393     sqlite3StrAccumReset(&sCheck.errMsg);
   57394     *pnErr = sCheck.nErr+1;
   57395     return 0;
   57396   }
   57397   *pnErr = sCheck.nErr;
   57398   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   57399   return sqlite3StrAccumFinish(&sCheck.errMsg);
   57400 }
   57401 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   57402 
   57403 /*
   57404 ** Return the full pathname of the underlying database file.
   57405 **
   57406 ** The pager filename is invariant as long as the pager is
   57407 ** open so it is safe to access without the BtShared mutex.
   57408 */
   57409 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   57410   assert( p->pBt->pPager!=0 );
   57411   return sqlite3PagerFilename(p->pBt->pPager);
   57412 }
   57413 
   57414 /*
   57415 ** Return the pathname of the journal file for this database. The return
   57416 ** value of this routine is the same regardless of whether the journal file
   57417 ** has been created or not.
   57418 **
   57419 ** The pager journal filename is invariant as long as the pager is
   57420 ** open so it is safe to access without the BtShared mutex.
   57421 */
   57422 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   57423   assert( p->pBt->pPager!=0 );
   57424   return sqlite3PagerJournalname(p->pBt->pPager);
   57425 }
   57426 
   57427 /*
   57428 ** Return non-zero if a transaction is active.
   57429 */
   57430 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   57431   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   57432   return (p && (p->inTrans==TRANS_WRITE));
   57433 }
   57434 
   57435 #ifndef SQLITE_OMIT_WAL
   57436 /*
   57437 ** Run a checkpoint on the Btree passed as the first argument.
   57438 **
   57439 ** Return SQLITE_LOCKED if this or any other connection has an open
   57440 ** transaction on the shared-cache the argument Btree is connected to.
   57441 **
   57442 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   57443 */
   57444 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
   57445   int rc = SQLITE_OK;
   57446   if( p ){
   57447     BtShared *pBt = p->pBt;
   57448     sqlite3BtreeEnter(p);
   57449     if( pBt->inTransaction!=TRANS_NONE ){
   57450       rc = SQLITE_LOCKED;
   57451     }else{
   57452       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
   57453     }
   57454     sqlite3BtreeLeave(p);
   57455   }
   57456   return rc;
   57457 }
   57458 #endif
   57459 
   57460 /*
   57461 ** Return non-zero if a read (or write) transaction is active.
   57462 */
   57463 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   57464   assert( p );
   57465   assert( sqlite3_mutex_held(p->db->mutex) );
   57466   return p->inTrans!=TRANS_NONE;
   57467 }
   57468 
   57469 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   57470   assert( p );
   57471   assert( sqlite3_mutex_held(p->db->mutex) );
   57472   return p->nBackup!=0;
   57473 }
   57474 
   57475 /*
   57476 ** This function returns a pointer to a blob of memory associated with
   57477 ** a single shared-btree. The memory is used by client code for its own
   57478 ** purposes (for example, to store a high-level schema associated with
   57479 ** the shared-btree). The btree layer manages reference counting issues.
   57480 **
   57481 ** The first time this is called on a shared-btree, nBytes bytes of memory
   57482 ** are allocated, zeroed, and returned to the caller. For each subsequent
   57483 ** call the nBytes parameter is ignored and a pointer to the same blob
   57484 ** of memory returned.
   57485 **
   57486 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   57487 ** allocated, a null pointer is returned. If the blob has already been
   57488 ** allocated, it is returned as normal.
   57489 **
   57490 ** Just before the shared-btree is closed, the function passed as the
   57491 ** xFree argument when the memory allocation was made is invoked on the
   57492 ** blob of allocated memory. The xFree function should not call sqlite3_free()
   57493 ** on the memory, the btree layer does that.
   57494 */
   57495 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   57496   BtShared *pBt = p->pBt;
   57497   sqlite3BtreeEnter(p);
   57498   if( !pBt->pSchema && nBytes ){
   57499     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   57500     pBt->xFreeSchema = xFree;
   57501   }
   57502   sqlite3BtreeLeave(p);
   57503   return pBt->pSchema;
   57504 }
   57505 
   57506 /*
   57507 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   57508 ** btree as the argument handle holds an exclusive lock on the
   57509 ** sqlite_master table. Otherwise SQLITE_OK.
   57510 */
   57511 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   57512   int rc;
   57513   assert( sqlite3_mutex_held(p->db->mutex) );
   57514   sqlite3BtreeEnter(p);
   57515   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   57516   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   57517   sqlite3BtreeLeave(p);
   57518   return rc;
   57519 }
   57520 
   57521 
   57522 #ifndef SQLITE_OMIT_SHARED_CACHE
   57523 /*
   57524 ** Obtain a lock on the table whose root page is iTab.  The
   57525 ** lock is a write lock if isWritelock is true or a read lock
   57526 ** if it is false.
   57527 */
   57528 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   57529   int rc = SQLITE_OK;
   57530   assert( p->inTrans!=TRANS_NONE );
   57531   if( p->sharable ){
   57532     u8 lockType = READ_LOCK + isWriteLock;
   57533     assert( READ_LOCK+1==WRITE_LOCK );
   57534     assert( isWriteLock==0 || isWriteLock==1 );
   57535 
   57536     sqlite3BtreeEnter(p);
   57537     rc = querySharedCacheTableLock(p, iTab, lockType);
   57538     if( rc==SQLITE_OK ){
   57539       rc = setSharedCacheTableLock(p, iTab, lockType);
   57540     }
   57541     sqlite3BtreeLeave(p);
   57542   }
   57543   return rc;
   57544 }
   57545 #endif
   57546 
   57547 #ifndef SQLITE_OMIT_INCRBLOB
   57548 /*
   57549 ** Argument pCsr must be a cursor opened for writing on an
   57550 ** INTKEY table currently pointing at a valid table entry.
   57551 ** This function modifies the data stored as part of that entry.
   57552 **
   57553 ** Only the data content may only be modified, it is not possible to
   57554 ** change the length of the data stored. If this function is called with
   57555 ** parameters that attempt to write past the end of the existing data,
   57556 ** no modifications are made and SQLITE_CORRUPT is returned.
   57557 */
   57558 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   57559   int rc;
   57560   assert( cursorHoldsMutex(pCsr) );
   57561   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   57562   assert( pCsr->isIncrblobHandle );
   57563 
   57564   rc = restoreCursorPosition(pCsr);
   57565   if( rc!=SQLITE_OK ){
   57566     return rc;
   57567   }
   57568   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   57569   if( pCsr->eState!=CURSOR_VALID ){
   57570     return SQLITE_ABORT;
   57571   }
   57572 
   57573   /* Check some assumptions:
   57574   **   (a) the cursor is open for writing,
   57575   **   (b) there is a read/write transaction open,
   57576   **   (c) the connection holds a write-lock on the table (if required),
   57577   **   (d) there are no conflicting read-locks, and
   57578   **   (e) the cursor points at a valid row of an intKey table.
   57579   */
   57580   if( !pCsr->wrFlag ){
   57581     return SQLITE_READONLY;
   57582   }
   57583   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
   57584               && pCsr->pBt->inTransaction==TRANS_WRITE );
   57585   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   57586   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   57587   assert( pCsr->apPage[pCsr->iPage]->intKey );
   57588 
   57589   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   57590 }
   57591 
   57592 /*
   57593 ** Set a flag on this cursor to cache the locations of pages from the
   57594 ** overflow list for the current row. This is used by cursors opened
   57595 ** for incremental blob IO only.
   57596 **
   57597 ** This function sets a flag only. The actual page location cache
   57598 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
   57599 ** accessPayload() (the worker function for sqlite3BtreeData() and
   57600 ** sqlite3BtreePutData()).
   57601 */
   57602 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
   57603   assert( cursorHoldsMutex(pCur) );
   57604   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   57605   invalidateOverflowCache(pCur);
   57606   pCur->isIncrblobHandle = 1;
   57607 }
   57608 #endif
   57609 
   57610 /*
   57611 ** Set both the "read version" (single byte at byte offset 18) and
   57612 ** "write version" (single byte at byte offset 19) fields in the database
   57613 ** header to iVersion.
   57614 */
   57615 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   57616   BtShared *pBt = pBtree->pBt;
   57617   int rc;                         /* Return code */
   57618 
   57619   assert( iVersion==1 || iVersion==2 );
   57620 
   57621   /* If setting the version fields to 1, do not automatically open the
   57622   ** WAL connection, even if the version fields are currently set to 2.
   57623   */
   57624   pBt->btsFlags &= ~BTS_NO_WAL;
   57625   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
   57626 
   57627   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   57628   if( rc==SQLITE_OK ){
   57629     u8 *aData = pBt->pPage1->aData;
   57630     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   57631       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   57632       if( rc==SQLITE_OK ){
   57633         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   57634         if( rc==SQLITE_OK ){
   57635           aData[18] = (u8)iVersion;
   57636           aData[19] = (u8)iVersion;
   57637         }
   57638       }
   57639     }
   57640   }
   57641 
   57642   pBt->btsFlags &= ~BTS_NO_WAL;
   57643   return rc;
   57644 }
   57645 
   57646 /************** End of btree.c ***********************************************/
   57647 /************** Begin file backup.c ******************************************/
   57648 /*
   57649 ** 2009 January 28
   57650 **
   57651 ** The author disclaims copyright to this source code.  In place of
   57652 ** a legal notice, here is a blessing:
   57653 **
   57654 **    May you do good and not evil.
   57655 **    May you find forgiveness for yourself and forgive others.
   57656 **    May you share freely, never taking more than you give.
   57657 **
   57658 *************************************************************************
   57659 ** This file contains the implementation of the sqlite3_backup_XXX()
   57660 ** API functions and the related features.
   57661 */
   57662 
   57663 /* Macro to find the minimum of two numeric values.
   57664 */
   57665 #ifndef MIN
   57666 # define MIN(x,y) ((x)<(y)?(x):(y))
   57667 #endif
   57668 
   57669 /*
   57670 ** Structure allocated for each backup operation.
   57671 */
   57672 struct sqlite3_backup {
   57673   sqlite3* pDestDb;        /* Destination database handle */
   57674   Btree *pDest;            /* Destination b-tree file */
   57675   u32 iDestSchema;         /* Original schema cookie in destination */
   57676   int bDestLocked;         /* True once a write-transaction is open on pDest */
   57677 
   57678   Pgno iNext;              /* Page number of the next source page to copy */
   57679   sqlite3* pSrcDb;         /* Source database handle */
   57680   Btree *pSrc;             /* Source b-tree file */
   57681 
   57682   int rc;                  /* Backup process error code */
   57683 
   57684   /* These two variables are set by every call to backup_step(). They are
   57685   ** read by calls to backup_remaining() and backup_pagecount().
   57686   */
   57687   Pgno nRemaining;         /* Number of pages left to copy */
   57688   Pgno nPagecount;         /* Total number of pages to copy */
   57689 
   57690   int isAttached;          /* True once backup has been registered with pager */
   57691   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   57692 };
   57693 
   57694 /*
   57695 ** THREAD SAFETY NOTES:
   57696 **
   57697 **   Once it has been created using backup_init(), a single sqlite3_backup
   57698 **   structure may be accessed via two groups of thread-safe entry points:
   57699 **
   57700 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   57701 **       backup_finish(). Both these functions obtain the source database
   57702 **       handle mutex and the mutex associated with the source BtShared
   57703 **       structure, in that order.
   57704 **
   57705 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   57706 **       invoked by the pager layer to report various state changes in
   57707 **       the page cache associated with the source database. The mutex
   57708 **       associated with the source database BtShared structure will always
   57709 **       be held when either of these functions are invoked.
   57710 **
   57711 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   57712 **   backup_pagecount() are not thread-safe functions. If they are called
   57713 **   while some other thread is calling backup_step() or backup_finish(),
   57714 **   the values returned may be invalid. There is no way for a call to
   57715 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   57716 **   or backup_pagecount().
   57717 **
   57718 **   Depending on the SQLite configuration, the database handles and/or
   57719 **   the Btree objects may have their own mutexes that require locking.
   57720 **   Non-sharable Btrees (in-memory databases for example), do not have
   57721 **   associated mutexes.
   57722 */
   57723 
   57724 /*
   57725 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   57726 ** in connection handle pDb. If such a database cannot be found, return
   57727 ** a NULL pointer and write an error message to pErrorDb.
   57728 **
   57729 ** If the "temp" database is requested, it may need to be opened by this
   57730 ** function. If an error occurs while doing so, return 0 and write an
   57731 ** error message to pErrorDb.
   57732 */
   57733 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   57734   int i = sqlite3FindDbName(pDb, zDb);
   57735 
   57736   if( i==1 ){
   57737     Parse *pParse;
   57738     int rc = 0;
   57739     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   57740     if( pParse==0 ){
   57741       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   57742       rc = SQLITE_NOMEM;
   57743     }else{
   57744       pParse->db = pDb;
   57745       if( sqlite3OpenTempDatabase(pParse) ){
   57746         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   57747         rc = SQLITE_ERROR;
   57748       }
   57749       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   57750       sqlite3StackFree(pErrorDb, pParse);
   57751     }
   57752     if( rc ){
   57753       return 0;
   57754     }
   57755   }
   57756 
   57757   if( i<0 ){
   57758     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   57759     return 0;
   57760   }
   57761 
   57762   return pDb->aDb[i].pBt;
   57763 }
   57764 
   57765 /*
   57766 ** Attempt to set the page size of the destination to match the page size
   57767 ** of the source.
   57768 */
   57769 static int setDestPgsz(sqlite3_backup *p){
   57770   int rc;
   57771   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
   57772   return rc;
   57773 }
   57774 
   57775 /*
   57776 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   57777 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   57778 ** a pointer to the new sqlite3_backup object.
   57779 **
   57780 ** If an error occurs, NULL is returned and an error code and error message
   57781 ** stored in database handle pDestDb.
   57782 */
   57783 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   57784   sqlite3* pDestDb,                     /* Database to write to */
   57785   const char *zDestDb,                  /* Name of database within pDestDb */
   57786   sqlite3* pSrcDb,                      /* Database connection to read from */
   57787   const char *zSrcDb                    /* Name of database within pSrcDb */
   57788 ){
   57789   sqlite3_backup *p;                    /* Value to return */
   57790 
   57791   /* Lock the source database handle. The destination database
   57792   ** handle is not locked in this routine, but it is locked in
   57793   ** sqlite3_backup_step(). The user is required to ensure that no
   57794   ** other thread accesses the destination handle for the duration
   57795   ** of the backup operation.  Any attempt to use the destination
   57796   ** database connection while a backup is in progress may cause
   57797   ** a malfunction or a deadlock.
   57798   */
   57799   sqlite3_mutex_enter(pSrcDb->mutex);
   57800   sqlite3_mutex_enter(pDestDb->mutex);
   57801 
   57802   if( pSrcDb==pDestDb ){
   57803     sqlite3Error(
   57804         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   57805     );
   57806     p = 0;
   57807   }else {
   57808     /* Allocate space for a new sqlite3_backup object...
   57809     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   57810     ** call to sqlite3_backup_init() and is destroyed by a call to
   57811     ** sqlite3_backup_finish(). */
   57812     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
   57813     if( !p ){
   57814       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   57815     }
   57816   }
   57817 
   57818   /* If the allocation succeeded, populate the new object. */
   57819   if( p ){
   57820     memset(p, 0, sizeof(sqlite3_backup));
   57821     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   57822     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   57823     p->pDestDb = pDestDb;
   57824     p->pSrcDb = pSrcDb;
   57825     p->iNext = 1;
   57826     p->isAttached = 0;
   57827 
   57828     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
   57829       /* One (or both) of the named databases did not exist or an OOM
   57830       ** error was hit.  The error has already been written into the
   57831       ** pDestDb handle.  All that is left to do here is free the
   57832       ** sqlite3_backup structure.
   57833       */
   57834       sqlite3_free(p);
   57835       p = 0;
   57836     }
   57837   }
   57838   if( p ){
   57839     p->pSrc->nBackup++;
   57840   }
   57841 
   57842   sqlite3_mutex_leave(pDestDb->mutex);
   57843   sqlite3_mutex_leave(pSrcDb->mutex);
   57844   return p;
   57845 }
   57846 
   57847 /*
   57848 ** Argument rc is an SQLite error code. Return true if this error is
   57849 ** considered fatal if encountered during a backup operation. All errors
   57850 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   57851 */
   57852 static int isFatalError(int rc){
   57853   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   57854 }
   57855 
   57856 /*
   57857 ** Parameter zSrcData points to a buffer containing the data for
   57858 ** page iSrcPg from the source database. Copy this data into the
   57859 ** destination database.
   57860 */
   57861 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
   57862   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   57863   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   57864   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   57865   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   57866   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   57867 #ifdef SQLITE_HAS_CODEC
   57868   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
   57869   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
   57870 #endif
   57871 
   57872   int rc = SQLITE_OK;
   57873   i64 iOff;
   57874 
   57875   assert( p->bDestLocked );
   57876   assert( !isFatalError(p->rc) );
   57877   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   57878   assert( zSrcData );
   57879 
   57880   /* Catch the case where the destination is an in-memory database and the
   57881   ** page sizes of the source and destination differ.
   57882   */
   57883   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   57884     rc = SQLITE_READONLY;
   57885   }
   57886 
   57887 #ifdef SQLITE_HAS_CODEC
   57888   /* Backup is not possible if the page size of the destination is changing
   57889   ** and a codec is in use.
   57890   */
   57891   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   57892     rc = SQLITE_READONLY;
   57893   }
   57894 
   57895   /* Backup is not possible if the number of bytes of reserve space differ
   57896   ** between source and destination.  If there is a difference, try to
   57897   ** fix the destination to agree with the source.  If that is not possible,
   57898   ** then the backup cannot proceed.
   57899   */
   57900   if( nSrcReserve!=nDestReserve ){
   57901     u32 newPgsz = nSrcPgsz;
   57902     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
   57903     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
   57904   }
   57905 #endif
   57906 
   57907   /* This loop runs once for each destination page spanned by the source
   57908   ** page. For each iteration, variable iOff is set to the byte offset
   57909   ** of the destination page.
   57910   */
   57911   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   57912     DbPage *pDestPg = 0;
   57913     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   57914     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   57915     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   57916      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   57917     ){
   57918       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   57919       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   57920       u8 *zOut = &zDestData[iOff%nDestPgsz];
   57921 
   57922       /* Copy the data from the source page into the destination page.
   57923       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   57924       ** and the pager code use this trick (clearing the first byte
   57925       ** of the page 'extra' space to invalidate the Btree layers
   57926       ** cached parse of the page). MemPage.isInit is marked
   57927       ** "MUST BE FIRST" for this purpose.
   57928       */
   57929       memcpy(zOut, zIn, nCopy);
   57930       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   57931     }
   57932     sqlite3PagerUnref(pDestPg);
   57933   }
   57934 
   57935   return rc;
   57936 }
   57937 
   57938 /*
   57939 ** If pFile is currently larger than iSize bytes, then truncate it to
   57940 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   57941 ** this function is a no-op.
   57942 **
   57943 ** Return SQLITE_OK if everything is successful, or an SQLite error
   57944 ** code if an error occurs.
   57945 */
   57946 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   57947   i64 iCurrent;
   57948   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   57949   if( rc==SQLITE_OK && iCurrent>iSize ){
   57950     rc = sqlite3OsTruncate(pFile, iSize);
   57951   }
   57952   return rc;
   57953 }
   57954 
   57955 /*
   57956 ** Register this backup object with the associated source pager for
   57957 ** callbacks when pages are changed or the cache invalidated.
   57958 */
   57959 static void attachBackupObject(sqlite3_backup *p){
   57960   sqlite3_backup **pp;
   57961   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   57962   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   57963   p->pNext = *pp;
   57964   *pp = p;
   57965   p->isAttached = 1;
   57966 }
   57967 
   57968 /*
   57969 ** Copy nPage pages from the source b-tree to the destination.
   57970 */
   57971 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   57972   int rc;
   57973   int destMode;       /* Destination journal mode */
   57974   int pgszSrc = 0;    /* Source page size */
   57975   int pgszDest = 0;   /* Destination page size */
   57976 
   57977   sqlite3_mutex_enter(p->pSrcDb->mutex);
   57978   sqlite3BtreeEnter(p->pSrc);
   57979   if( p->pDestDb ){
   57980     sqlite3_mutex_enter(p->pDestDb->mutex);
   57981   }
   57982 
   57983   rc = p->rc;
   57984   if( !isFatalError(rc) ){
   57985     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   57986     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   57987     int ii;                            /* Iterator variable */
   57988     int nSrcPage = -1;                 /* Size of source db in pages */
   57989     int bCloseTrans = 0;               /* True if src db requires unlocking */
   57990 
   57991     /* If the source pager is currently in a write-transaction, return
   57992     ** SQLITE_BUSY immediately.
   57993     */
   57994     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   57995       rc = SQLITE_BUSY;
   57996     }else{
   57997       rc = SQLITE_OK;
   57998     }
   57999 
   58000     /* Lock the destination database, if it is not locked already. */
   58001     if( SQLITE_OK==rc && p->bDestLocked==0
   58002      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   58003     ){
   58004       p->bDestLocked = 1;
   58005       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   58006     }
   58007 
   58008     /* If there is no open read-transaction on the source database, open
   58009     ** one now. If a transaction is opened here, then it will be closed
   58010     ** before this function exits.
   58011     */
   58012     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   58013       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   58014       bCloseTrans = 1;
   58015     }
   58016 
   58017     /* Do not allow backup if the destination database is in WAL mode
   58018     ** and the page sizes are different between source and destination */
   58019     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   58020     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   58021     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   58022     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   58023       rc = SQLITE_READONLY;
   58024     }
   58025 
   58026     /* Now that there is a read-lock on the source database, query the
   58027     ** source pager for the number of pages in the database.
   58028     */
   58029     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   58030     assert( nSrcPage>=0 );
   58031     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   58032       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   58033       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   58034         DbPage *pSrcPg;                             /* Source page object */
   58035         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   58036         if( rc==SQLITE_OK ){
   58037           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
   58038           sqlite3PagerUnref(pSrcPg);
   58039         }
   58040       }
   58041       p->iNext++;
   58042     }
   58043     if( rc==SQLITE_OK ){
   58044       p->nPagecount = nSrcPage;
   58045       p->nRemaining = nSrcPage+1-p->iNext;
   58046       if( p->iNext>(Pgno)nSrcPage ){
   58047         rc = SQLITE_DONE;
   58048       }else if( !p->isAttached ){
   58049         attachBackupObject(p);
   58050       }
   58051     }
   58052 
   58053     /* Update the schema version field in the destination database. This
   58054     ** is to make sure that the schema-version really does change in
   58055     ** the case where the source and destination databases have the
   58056     ** same schema version.
   58057     */
   58058     if( rc==SQLITE_DONE ){
   58059       rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
   58060       if( rc==SQLITE_OK ){
   58061         if( p->pDestDb ){
   58062           sqlite3ResetInternalSchema(p->pDestDb, -1);
   58063         }
   58064         if( destMode==PAGER_JOURNALMODE_WAL ){
   58065           rc = sqlite3BtreeSetVersion(p->pDest, 2);
   58066         }
   58067       }
   58068       if( rc==SQLITE_OK ){
   58069         int nDestTruncate;
   58070         /* Set nDestTruncate to the final number of pages in the destination
   58071         ** database. The complication here is that the destination page
   58072         ** size may be different to the source page size.
   58073         **
   58074         ** If the source page size is smaller than the destination page size,
   58075         ** round up. In this case the call to sqlite3OsTruncate() below will
   58076         ** fix the size of the file. However it is important to call
   58077         ** sqlite3PagerTruncateImage() here so that any pages in the
   58078         ** destination file that lie beyond the nDestTruncate page mark are
   58079         ** journalled by PagerCommitPhaseOne() before they are destroyed
   58080         ** by the file truncation.
   58081         */
   58082         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   58083         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   58084         if( pgszSrc<pgszDest ){
   58085           int ratio = pgszDest/pgszSrc;
   58086           nDestTruncate = (nSrcPage+ratio-1)/ratio;
   58087           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   58088             nDestTruncate--;
   58089           }
   58090         }else{
   58091           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   58092         }
   58093         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   58094 
   58095         if( pgszSrc<pgszDest ){
   58096           /* If the source page-size is smaller than the destination page-size,
   58097           ** two extra things may need to happen:
   58098           **
   58099           **   * The destination may need to be truncated, and
   58100           **
   58101           **   * Data stored on the pages immediately following the
   58102           **     pending-byte page in the source database may need to be
   58103           **     copied into the destination database.
   58104           */
   58105           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   58106           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   58107           i64 iOff;
   58108           i64 iEnd;
   58109 
   58110           assert( pFile );
   58111           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   58112                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   58113              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   58114           ));
   58115 
   58116           /* This call ensures that all data required to recreate the original
   58117           ** database has been stored in the journal for pDestPager and the
   58118           ** journal synced to disk. So at this point we may safely modify
   58119           ** the database file in any way, knowing that if a power failure
   58120           ** occurs, the original database will be reconstructed from the
   58121           ** journal file.  */
   58122           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
   58123 
   58124           /* Write the extra pages and truncate the database file as required */
   58125           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   58126           for(
   58127             iOff=PENDING_BYTE+pgszSrc;
   58128             rc==SQLITE_OK && iOff<iEnd;
   58129             iOff+=pgszSrc
   58130           ){
   58131             PgHdr *pSrcPg = 0;
   58132             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   58133             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   58134             if( rc==SQLITE_OK ){
   58135               u8 *zData = sqlite3PagerGetData(pSrcPg);
   58136               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   58137             }
   58138             sqlite3PagerUnref(pSrcPg);
   58139           }
   58140           if( rc==SQLITE_OK ){
   58141             rc = backupTruncateFile(pFile, iSize);
   58142           }
   58143 
   58144           /* Sync the database file to disk. */
   58145           if( rc==SQLITE_OK ){
   58146             rc = sqlite3PagerSync(pDestPager);
   58147           }
   58148         }else{
   58149           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   58150         }
   58151 
   58152         /* Finish committing the transaction to the destination database. */
   58153         if( SQLITE_OK==rc
   58154          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
   58155         ){
   58156           rc = SQLITE_DONE;
   58157         }
   58158       }
   58159     }
   58160 
   58161     /* If bCloseTrans is true, then this function opened a read transaction
   58162     ** on the source database. Close the read transaction here. There is
   58163     ** no need to check the return values of the btree methods here, as
   58164     ** "committing" a read-only transaction cannot fail.
   58165     */
   58166     if( bCloseTrans ){
   58167       TESTONLY( int rc2 );
   58168       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   58169       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
   58170       assert( rc2==SQLITE_OK );
   58171     }
   58172 
   58173     if( rc==SQLITE_IOERR_NOMEM ){
   58174       rc = SQLITE_NOMEM;
   58175     }
   58176     p->rc = rc;
   58177   }
   58178   if( p->pDestDb ){
   58179     sqlite3_mutex_leave(p->pDestDb->mutex);
   58180   }
   58181   sqlite3BtreeLeave(p->pSrc);
   58182   sqlite3_mutex_leave(p->pSrcDb->mutex);
   58183   return rc;
   58184 }
   58185 
   58186 /*
   58187 ** Release all resources associated with an sqlite3_backup* handle.
   58188 */
   58189 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   58190   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   58191   MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
   58192   int rc;                              /* Value to return */
   58193 
   58194   /* Enter the mutexes */
   58195   if( p==0 ) return SQLITE_OK;
   58196   sqlite3_mutex_enter(p->pSrcDb->mutex);
   58197   sqlite3BtreeEnter(p->pSrc);
   58198   MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
   58199   if( p->pDestDb ){
   58200     sqlite3_mutex_enter(p->pDestDb->mutex);
   58201   }
   58202 
   58203   /* Detach this backup from the source pager. */
   58204   if( p->pDestDb ){
   58205     p->pSrc->nBackup--;
   58206   }
   58207   if( p->isAttached ){
   58208     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   58209     while( *pp!=p ){
   58210       pp = &(*pp)->pNext;
   58211     }
   58212     *pp = p->pNext;
   58213   }
   58214 
   58215   /* If a transaction is still open on the Btree, roll it back. */
   58216   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
   58217 
   58218   /* Set the error code of the destination database handle. */
   58219   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   58220   sqlite3Error(p->pDestDb, rc, 0);
   58221 
   58222   /* Exit the mutexes and free the backup context structure. */
   58223   if( p->pDestDb ){
   58224     sqlite3_mutex_leave(p->pDestDb->mutex);
   58225   }
   58226   sqlite3BtreeLeave(p->pSrc);
   58227   if( p->pDestDb ){
   58228     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   58229     ** call to sqlite3_backup_init() and is destroyed by a call to
   58230     ** sqlite3_backup_finish(). */
   58231     sqlite3_free(p);
   58232   }
   58233   sqlite3_mutex_leave(mutex);
   58234   return rc;
   58235 }
   58236 
   58237 /*
   58238 ** Return the number of pages still to be backed up as of the most recent
   58239 ** call to sqlite3_backup_step().
   58240 */
   58241 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   58242   return p->nRemaining;
   58243 }
   58244 
   58245 /*
   58246 ** Return the total number of pages in the source database as of the most
   58247 ** recent call to sqlite3_backup_step().
   58248 */
   58249 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   58250   return p->nPagecount;
   58251 }
   58252 
   58253 /*
   58254 ** This function is called after the contents of page iPage of the
   58255 ** source database have been modified. If page iPage has already been
   58256 ** copied into the destination database, then the data written to the
   58257 ** destination is now invalidated. The destination copy of iPage needs
   58258 ** to be updated with the new data before the backup operation is
   58259 ** complete.
   58260 **
   58261 ** It is assumed that the mutex associated with the BtShared object
   58262 ** corresponding to the source database is held when this function is
   58263 ** called.
   58264 */
   58265 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   58266   sqlite3_backup *p;                   /* Iterator variable */
   58267   for(p=pBackup; p; p=p->pNext){
   58268     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   58269     if( !isFatalError(p->rc) && iPage<p->iNext ){
   58270       /* The backup process p has already copied page iPage. But now it
   58271       ** has been modified by a transaction on the source pager. Copy
   58272       ** the new data into the backup.
   58273       */
   58274       int rc;
   58275       assert( p->pDestDb );
   58276       sqlite3_mutex_enter(p->pDestDb->mutex);
   58277       rc = backupOnePage(p, iPage, aData);
   58278       sqlite3_mutex_leave(p->pDestDb->mutex);
   58279       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   58280       if( rc!=SQLITE_OK ){
   58281         p->rc = rc;
   58282       }
   58283     }
   58284   }
   58285 }
   58286 
   58287 /*
   58288 ** Restart the backup process. This is called when the pager layer
   58289 ** detects that the database has been modified by an external database
   58290 ** connection. In this case there is no way of knowing which of the
   58291 ** pages that have been copied into the destination database are still
   58292 ** valid and which are not, so the entire process needs to be restarted.
   58293 **
   58294 ** It is assumed that the mutex associated with the BtShared object
   58295 ** corresponding to the source database is held when this function is
   58296 ** called.
   58297 */
   58298 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   58299   sqlite3_backup *p;                   /* Iterator variable */
   58300   for(p=pBackup; p; p=p->pNext){
   58301     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   58302     p->iNext = 1;
   58303   }
   58304 }
   58305 
   58306 #ifndef SQLITE_OMIT_VACUUM
   58307 /*
   58308 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   58309 ** must be active for both files.
   58310 **
   58311 ** The size of file pTo may be reduced by this operation. If anything
   58312 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   58313 ** transaction is committed before returning.
   58314 */
   58315 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   58316   int rc;
   58317   sqlite3_file *pFd;              /* File descriptor for database pTo */
   58318   sqlite3_backup b;
   58319   sqlite3BtreeEnter(pTo);
   58320   sqlite3BtreeEnter(pFrom);
   58321 
   58322   assert( sqlite3BtreeIsInTrans(pTo) );
   58323   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   58324   if( pFd->pMethods ){
   58325     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
   58326     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
   58327     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   58328     if( rc ) goto copy_finished;
   58329   }
   58330 
   58331   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   58332   ** to 0. This is used by the implementations of sqlite3_backup_step()
   58333   ** and sqlite3_backup_finish() to detect that they are being called
   58334   ** from this function, not directly by the user.
   58335   */
   58336   memset(&b, 0, sizeof(b));
   58337   b.pSrcDb = pFrom->db;
   58338   b.pSrc = pFrom;
   58339   b.pDest = pTo;
   58340   b.iNext = 1;
   58341 
   58342   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   58343   ** file. By passing this as the number of pages to copy to
   58344   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   58345   ** within a single call (unless an error occurs). The assert() statement
   58346   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   58347   ** or an error code.
   58348   */
   58349   sqlite3_backup_step(&b, 0x7FFFFFFF);
   58350   assert( b.rc!=SQLITE_OK );
   58351   rc = sqlite3_backup_finish(&b);
   58352   if( rc==SQLITE_OK ){
   58353     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
   58354   }else{
   58355     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   58356   }
   58357 
   58358   assert( sqlite3BtreeIsInTrans(pTo)==0 );
   58359 copy_finished:
   58360   sqlite3BtreeLeave(pFrom);
   58361   sqlite3BtreeLeave(pTo);
   58362   return rc;
   58363 }
   58364 #endif /* SQLITE_OMIT_VACUUM */
   58365 
   58366 /************** End of backup.c **********************************************/
   58367 /************** Begin file vdbemem.c *****************************************/
   58368 /*
   58369 ** 2004 May 26
   58370 **
   58371 ** The author disclaims copyright to this source code.  In place of
   58372 ** a legal notice, here is a blessing:
   58373 **
   58374 **    May you do good and not evil.
   58375 **    May you find forgiveness for yourself and forgive others.
   58376 **    May you share freely, never taking more than you give.
   58377 **
   58378 *************************************************************************
   58379 **
   58380 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   58381 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   58382 ** only within the VDBE.  Interface routines refer to a Mem using the
   58383 ** name sqlite_value
   58384 */
   58385 
   58386 /*
   58387 ** If pMem is an object with a valid string representation, this routine
   58388 ** ensures the internal encoding for the string representation is
   58389 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   58390 **
   58391 ** If pMem is not a string object, or the encoding of the string
   58392 ** representation is already stored using the requested encoding, then this
   58393 ** routine is a no-op.
   58394 **
   58395 ** SQLITE_OK is returned if the conversion is successful (or not required).
   58396 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   58397 ** between formats.
   58398 */
   58399 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   58400   int rc;
   58401   assert( (pMem->flags&MEM_RowSet)==0 );
   58402   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   58403            || desiredEnc==SQLITE_UTF16BE );
   58404   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   58405     return SQLITE_OK;
   58406   }
   58407   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58408 #ifdef SQLITE_OMIT_UTF16
   58409   return SQLITE_ERROR;
   58410 #else
   58411 
   58412   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   58413   ** then the encoding of the value may not have changed.
   58414   */
   58415   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   58416   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   58417   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   58418   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   58419   return rc;
   58420 #endif
   58421 }
   58422 
   58423 /*
   58424 ** Make sure pMem->z points to a writable allocation of at least
   58425 ** n bytes.
   58426 **
   58427 ** If the memory cell currently contains string or blob data
   58428 ** and the third argument passed to this function is true, the
   58429 ** current content of the cell is preserved. Otherwise, it may
   58430 ** be discarded.
   58431 **
   58432 ** This function sets the MEM_Dyn flag and clears any xDel callback.
   58433 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
   58434 ** not set, Mem.n is zeroed.
   58435 */
   58436 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
   58437   assert( 1 >=
   58438     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
   58439     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
   58440     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
   58441     ((pMem->flags&MEM_Static) ? 1 : 0)
   58442   );
   58443   assert( (pMem->flags&MEM_RowSet)==0 );
   58444 
   58445   if( n<32 ) n = 32;
   58446   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   58447     if( preserve && pMem->z==pMem->zMalloc ){
   58448       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   58449       preserve = 0;
   58450     }else{
   58451       sqlite3DbFree(pMem->db, pMem->zMalloc);
   58452       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   58453     }
   58454   }
   58455 
   58456   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
   58457     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   58458   }
   58459   if( pMem->flags&MEM_Dyn && pMem->xDel ){
   58460     assert( pMem->xDel!=SQLITE_DYNAMIC );
   58461     pMem->xDel((void *)(pMem->z));
   58462   }
   58463 
   58464   pMem->z = pMem->zMalloc;
   58465   if( pMem->z==0 ){
   58466     pMem->flags = MEM_Null;
   58467   }else{
   58468     pMem->flags &= ~(MEM_Ephem|MEM_Static);
   58469   }
   58470   pMem->xDel = 0;
   58471   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
   58472 }
   58473 
   58474 /*
   58475 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   58476 ** that any TEXT or BLOB content is stored in memory obtained from
   58477 ** malloc().  In this way, we know that the memory is safe to be
   58478 ** overwritten or altered.
   58479 **
   58480 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   58481 */
   58482 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   58483   int f;
   58484   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58485   assert( (pMem->flags&MEM_RowSet)==0 );
   58486   ExpandBlob(pMem);
   58487   f = pMem->flags;
   58488   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   58489     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   58490       return SQLITE_NOMEM;
   58491     }
   58492     pMem->z[pMem->n] = 0;
   58493     pMem->z[pMem->n+1] = 0;
   58494     pMem->flags |= MEM_Term;
   58495 #ifdef SQLITE_DEBUG
   58496     pMem->pScopyFrom = 0;
   58497 #endif
   58498   }
   58499 
   58500   return SQLITE_OK;
   58501 }
   58502 
   58503 /*
   58504 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   58505 ** blob stored in dynamically allocated space.
   58506 */
   58507 #ifndef SQLITE_OMIT_INCRBLOB
   58508 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   58509   if( pMem->flags & MEM_Zero ){
   58510     int nByte;
   58511     assert( pMem->flags&MEM_Blob );
   58512     assert( (pMem->flags&MEM_RowSet)==0 );
   58513     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58514 
   58515     /* Set nByte to the number of bytes required to store the expanded blob. */
   58516     nByte = pMem->n + pMem->u.nZero;
   58517     if( nByte<=0 ){
   58518       nByte = 1;
   58519     }
   58520     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   58521       return SQLITE_NOMEM;
   58522     }
   58523 
   58524     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   58525     pMem->n += pMem->u.nZero;
   58526     pMem->flags &= ~(MEM_Zero|MEM_Term);
   58527   }
   58528   return SQLITE_OK;
   58529 }
   58530 #endif
   58531 
   58532 
   58533 /*
   58534 ** Make sure the given Mem is \u0000 terminated.
   58535 */
   58536 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   58537   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58538   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   58539     return SQLITE_OK;   /* Nothing to do */
   58540   }
   58541   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   58542     return SQLITE_NOMEM;
   58543   }
   58544   pMem->z[pMem->n] = 0;
   58545   pMem->z[pMem->n+1] = 0;
   58546   pMem->flags |= MEM_Term;
   58547   return SQLITE_OK;
   58548 }
   58549 
   58550 /*
   58551 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   58552 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   58553 ** is a no-op.
   58554 **
   58555 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   58556 **
   58557 ** A MEM_Null value will never be passed to this function. This function is
   58558 ** used for converting values to text for returning to the user (i.e. via
   58559 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   58560 ** keys are strings. In the former case a NULL pointer is returned the
   58561 ** user and the later is an internal programming error.
   58562 */
   58563 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   58564   int rc = SQLITE_OK;
   58565   int fg = pMem->flags;
   58566   const int nByte = 32;
   58567 
   58568   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58569   assert( !(fg&MEM_Zero) );
   58570   assert( !(fg&(MEM_Str|MEM_Blob)) );
   58571   assert( fg&(MEM_Int|MEM_Real) );
   58572   assert( (pMem->flags&MEM_RowSet)==0 );
   58573   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58574 
   58575 
   58576   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   58577     return SQLITE_NOMEM;
   58578   }
   58579 
   58580   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   58581   ** string representation of the value. Then, if the required encoding
   58582   ** is UTF-16le or UTF-16be do a translation.
   58583   **
   58584   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   58585   */
   58586   if( fg & MEM_Int ){
   58587     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   58588   }else{
   58589     assert( fg & MEM_Real );
   58590     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   58591   }
   58592   pMem->n = sqlite3Strlen30(pMem->z);
   58593   pMem->enc = SQLITE_UTF8;
   58594   pMem->flags |= MEM_Str|MEM_Term;
   58595   sqlite3VdbeChangeEncoding(pMem, enc);
   58596   return rc;
   58597 }
   58598 
   58599 /*
   58600 ** Memory cell pMem contains the context of an aggregate function.
   58601 ** This routine calls the finalize method for that function.  The
   58602 ** result of the aggregate is stored back into pMem.
   58603 **
   58604 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   58605 ** otherwise.
   58606 */
   58607 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   58608   int rc = SQLITE_OK;
   58609   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   58610     sqlite3_context ctx;
   58611     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   58612     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58613     memset(&ctx, 0, sizeof(ctx));
   58614     ctx.s.flags = MEM_Null;
   58615     ctx.s.db = pMem->db;
   58616     ctx.pMem = pMem;
   58617     ctx.pFunc = pFunc;
   58618     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   58619     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   58620     sqlite3DbFree(pMem->db, pMem->zMalloc);
   58621     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   58622     rc = ctx.isError;
   58623   }
   58624   return rc;
   58625 }
   58626 
   58627 /*
   58628 ** If the memory cell contains a string value that must be freed by
   58629 ** invoking an external callback, free it now. Calling this function
   58630 ** does not free any Mem.zMalloc buffer.
   58631 */
   58632 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   58633   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   58634   if( p->flags&MEM_Agg ){
   58635     sqlite3VdbeMemFinalize(p, p->u.pDef);
   58636     assert( (p->flags & MEM_Agg)==0 );
   58637     sqlite3VdbeMemRelease(p);
   58638   }else if( p->flags&MEM_Dyn && p->xDel ){
   58639     assert( (p->flags&MEM_RowSet)==0 );
   58640     assert( p->xDel!=SQLITE_DYNAMIC );
   58641     p->xDel((void *)p->z);
   58642     p->xDel = 0;
   58643   }else if( p->flags&MEM_RowSet ){
   58644     sqlite3RowSetClear(p->u.pRowSet);
   58645   }else if( p->flags&MEM_Frame ){
   58646     sqlite3VdbeMemSetNull(p);
   58647   }
   58648 }
   58649 
   58650 /*
   58651 ** Release any memory held by the Mem. This may leave the Mem in an
   58652 ** inconsistent state, for example with (Mem.z==0) and
   58653 ** (Mem.type==SQLITE_TEXT).
   58654 */
   58655 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   58656   VdbeMemRelease(p);
   58657   sqlite3DbFree(p->db, p->zMalloc);
   58658   p->z = 0;
   58659   p->zMalloc = 0;
   58660   p->xDel = 0;
   58661 }
   58662 
   58663 /*
   58664 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   58665 ** If the double is too large, return 0x8000000000000000.
   58666 **
   58667 ** Most systems appear to do this simply by assigning
   58668 ** variables and without the extra range tests.  But
   58669 ** there are reports that windows throws an expection
   58670 ** if the floating point value is out of range. (See ticket #2880.)
   58671 ** Because we do not completely understand the problem, we will
   58672 ** take the conservative approach and always do range tests
   58673 ** before attempting the conversion.
   58674 */
   58675 static i64 doubleToInt64(double r){
   58676 #ifdef SQLITE_OMIT_FLOATING_POINT
   58677   /* When floating-point is omitted, double and int64 are the same thing */
   58678   return r;
   58679 #else
   58680   /*
   58681   ** Many compilers we encounter do not define constants for the
   58682   ** minimum and maximum 64-bit integers, or they define them
   58683   ** inconsistently.  And many do not understand the "LL" notation.
   58684   ** So we define our own static constants here using nothing
   58685   ** larger than a 32-bit integer constant.
   58686   */
   58687   static const i64 maxInt = LARGEST_INT64;
   58688   static const i64 minInt = SMALLEST_INT64;
   58689 
   58690   if( r<(double)minInt ){
   58691     return minInt;
   58692   }else if( r>(double)maxInt ){
   58693     /* minInt is correct here - not maxInt.  It turns out that assigning
   58694     ** a very large positive number to an integer results in a very large
   58695     ** negative integer.  This makes no sense, but it is what x86 hardware
   58696     ** does so for compatibility we will do the same in software. */
   58697     return minInt;
   58698   }else{
   58699     return (i64)r;
   58700   }
   58701 #endif
   58702 }
   58703 
   58704 /*
   58705 ** Return some kind of integer value which is the best we can do
   58706 ** at representing the value that *pMem describes as an integer.
   58707 ** If pMem is an integer, then the value is exact.  If pMem is
   58708 ** a floating-point then the value returned is the integer part.
   58709 ** If pMem is a string or blob, then we make an attempt to convert
   58710 ** it into a integer and return that.  If pMem represents an
   58711 ** an SQL-NULL value, return 0.
   58712 **
   58713 ** If pMem represents a string value, its encoding might be changed.
   58714 */
   58715 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   58716   int flags;
   58717   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58718   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58719   flags = pMem->flags;
   58720   if( flags & MEM_Int ){
   58721     return pMem->u.i;
   58722   }else if( flags & MEM_Real ){
   58723     return doubleToInt64(pMem->r);
   58724   }else if( flags & (MEM_Str|MEM_Blob) ){
   58725     i64 value = 0;
   58726     assert( pMem->z || pMem->n==0 );
   58727     testcase( pMem->z==0 );
   58728     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   58729     return value;
   58730   }else{
   58731     return 0;
   58732   }
   58733 }
   58734 
   58735 /*
   58736 ** Return the best representation of pMem that we can get into a
   58737 ** double.  If pMem is already a double or an integer, return its
   58738 ** value.  If it is a string or blob, try to convert it to a double.
   58739 ** If it is a NULL, return 0.0.
   58740 */
   58741 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   58742   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58743   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58744   if( pMem->flags & MEM_Real ){
   58745     return pMem->r;
   58746   }else if( pMem->flags & MEM_Int ){
   58747     return (double)pMem->u.i;
   58748   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   58749     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   58750     double val = (double)0;
   58751     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   58752     return val;
   58753   }else{
   58754     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   58755     return (double)0;
   58756   }
   58757 }
   58758 
   58759 /*
   58760 ** The MEM structure is already a MEM_Real.  Try to also make it a
   58761 ** MEM_Int if we can.
   58762 */
   58763 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   58764   assert( pMem->flags & MEM_Real );
   58765   assert( (pMem->flags & MEM_RowSet)==0 );
   58766   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58767   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58768 
   58769   pMem->u.i = doubleToInt64(pMem->r);
   58770 
   58771   /* Only mark the value as an integer if
   58772   **
   58773   **    (1) the round-trip conversion real->int->real is a no-op, and
   58774   **    (2) The integer is neither the largest nor the smallest
   58775   **        possible integer (ticket #3922)
   58776   **
   58777   ** The second and third terms in the following conditional enforces
   58778   ** the second condition under the assumption that addition overflow causes
   58779   ** values to wrap around.  On x86 hardware, the third term is always
   58780   ** true and could be omitted.  But we leave it in because other
   58781   ** architectures might behave differently.
   58782   */
   58783   if( pMem->r==(double)pMem->u.i
   58784    && pMem->u.i>SMALLEST_INT64
   58785 #if defined(__i486__) || defined(__x86_64__)
   58786    && ALWAYS(pMem->u.i<LARGEST_INT64)
   58787 #else
   58788    && pMem->u.i<LARGEST_INT64
   58789 #endif
   58790   ){
   58791     pMem->flags |= MEM_Int;
   58792   }
   58793 }
   58794 
   58795 /*
   58796 ** Convert pMem to type integer.  Invalidate any prior representations.
   58797 */
   58798 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   58799   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58800   assert( (pMem->flags & MEM_RowSet)==0 );
   58801   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58802 
   58803   pMem->u.i = sqlite3VdbeIntValue(pMem);
   58804   MemSetTypeFlag(pMem, MEM_Int);
   58805   return SQLITE_OK;
   58806 }
   58807 
   58808 /*
   58809 ** Convert pMem so that it is of type MEM_Real.
   58810 ** Invalidate any prior representations.
   58811 */
   58812 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   58813   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58814   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58815 
   58816   pMem->r = sqlite3VdbeRealValue(pMem);
   58817   MemSetTypeFlag(pMem, MEM_Real);
   58818   return SQLITE_OK;
   58819 }
   58820 
   58821 /*
   58822 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   58823 ** Invalidate any prior representations.
   58824 **
   58825 ** Every effort is made to force the conversion, even if the input
   58826 ** is a string that does not look completely like a number.  Convert
   58827 ** as much of the string as we can and ignore the rest.
   58828 */
   58829 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   58830   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   58831     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   58832     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   58833     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
   58834       MemSetTypeFlag(pMem, MEM_Int);
   58835     }else{
   58836       pMem->r = sqlite3VdbeRealValue(pMem);
   58837       MemSetTypeFlag(pMem, MEM_Real);
   58838       sqlite3VdbeIntegerAffinity(pMem);
   58839     }
   58840   }
   58841   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   58842   pMem->flags &= ~(MEM_Str|MEM_Blob);
   58843   return SQLITE_OK;
   58844 }
   58845 
   58846 /*
   58847 ** Delete any previous value and set the value stored in *pMem to NULL.
   58848 */
   58849 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   58850   if( pMem->flags & MEM_Frame ){
   58851     VdbeFrame *pFrame = pMem->u.pFrame;
   58852     pFrame->pParent = pFrame->v->pDelFrame;
   58853     pFrame->v->pDelFrame = pFrame;
   58854   }
   58855   if( pMem->flags & MEM_RowSet ){
   58856     sqlite3RowSetClear(pMem->u.pRowSet);
   58857   }
   58858   MemSetTypeFlag(pMem, MEM_Null);
   58859   pMem->type = SQLITE_NULL;
   58860 }
   58861 
   58862 /*
   58863 ** Delete any previous value and set the value to be a BLOB of length
   58864 ** n containing all zeros.
   58865 */
   58866 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   58867   sqlite3VdbeMemRelease(pMem);
   58868   pMem->flags = MEM_Blob|MEM_Zero;
   58869   pMem->type = SQLITE_BLOB;
   58870   pMem->n = 0;
   58871   if( n<0 ) n = 0;
   58872   pMem->u.nZero = n;
   58873   pMem->enc = SQLITE_UTF8;
   58874 
   58875 #ifdef SQLITE_OMIT_INCRBLOB
   58876   sqlite3VdbeMemGrow(pMem, n, 0);
   58877   if( pMem->z ){
   58878     pMem->n = n;
   58879     memset(pMem->z, 0, n);
   58880   }
   58881 #endif
   58882 }
   58883 
   58884 /*
   58885 ** Delete any previous value and set the value stored in *pMem to val,
   58886 ** manifest type INTEGER.
   58887 */
   58888 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   58889   sqlite3VdbeMemRelease(pMem);
   58890   pMem->u.i = val;
   58891   pMem->flags = MEM_Int;
   58892   pMem->type = SQLITE_INTEGER;
   58893 }
   58894 
   58895 #ifndef SQLITE_OMIT_FLOATING_POINT
   58896 /*
   58897 ** Delete any previous value and set the value stored in *pMem to val,
   58898 ** manifest type REAL.
   58899 */
   58900 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   58901   if( sqlite3IsNaN(val) ){
   58902     sqlite3VdbeMemSetNull(pMem);
   58903   }else{
   58904     sqlite3VdbeMemRelease(pMem);
   58905     pMem->r = val;
   58906     pMem->flags = MEM_Real;
   58907     pMem->type = SQLITE_FLOAT;
   58908   }
   58909 }
   58910 #endif
   58911 
   58912 /*
   58913 ** Delete any previous value and set the value of pMem to be an
   58914 ** empty boolean index.
   58915 */
   58916 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   58917   sqlite3 *db = pMem->db;
   58918   assert( db!=0 );
   58919   assert( (pMem->flags & MEM_RowSet)==0 );
   58920   sqlite3VdbeMemRelease(pMem);
   58921   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   58922   if( db->mallocFailed ){
   58923     pMem->flags = MEM_Null;
   58924   }else{
   58925     assert( pMem->zMalloc );
   58926     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   58927                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   58928     assert( pMem->u.pRowSet!=0 );
   58929     pMem->flags = MEM_RowSet;
   58930   }
   58931 }
   58932 
   58933 /*
   58934 ** Return true if the Mem object contains a TEXT or BLOB that is
   58935 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   58936 */
   58937 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   58938   assert( p->db!=0 );
   58939   if( p->flags & (MEM_Str|MEM_Blob) ){
   58940     int n = p->n;
   58941     if( p->flags & MEM_Zero ){
   58942       n += p->u.nZero;
   58943     }
   58944     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   58945   }
   58946   return 0;
   58947 }
   58948 
   58949 #ifdef SQLITE_DEBUG
   58950 /*
   58951 ** This routine prepares a memory cell for modication by breaking
   58952 ** its link to a shallow copy and by marking any current shallow
   58953 ** copies of this cell as invalid.
   58954 **
   58955 ** This is used for testing and debugging only - to make sure shallow
   58956 ** copies are not misused.
   58957 */
   58958 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   58959   int i;
   58960   Mem *pX;
   58961   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
   58962     if( pX->pScopyFrom==pMem ){
   58963       pX->flags |= MEM_Invalid;
   58964       pX->pScopyFrom = 0;
   58965     }
   58966   }
   58967   pMem->pScopyFrom = 0;
   58968 }
   58969 #endif /* SQLITE_DEBUG */
   58970 
   58971 /*
   58972 ** Size of struct Mem not including the Mem.zMalloc member.
   58973 */
   58974 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
   58975 
   58976 /*
   58977 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   58978 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   58979 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   58980 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   58981 */
   58982 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   58983   assert( (pFrom->flags & MEM_RowSet)==0 );
   58984   VdbeMemRelease(pTo);
   58985   memcpy(pTo, pFrom, MEMCELLSIZE);
   58986   pTo->xDel = 0;
   58987   if( (pFrom->flags&MEM_Static)==0 ){
   58988     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   58989     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   58990     pTo->flags |= srcType;
   58991   }
   58992 }
   58993 
   58994 /*
   58995 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   58996 ** freed before the copy is made.
   58997 */
   58998 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   58999   int rc = SQLITE_OK;
   59000 
   59001   assert( (pFrom->flags & MEM_RowSet)==0 );
   59002   VdbeMemRelease(pTo);
   59003   memcpy(pTo, pFrom, MEMCELLSIZE);
   59004   pTo->flags &= ~MEM_Dyn;
   59005 
   59006   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   59007     if( 0==(pFrom->flags&MEM_Static) ){
   59008       pTo->flags |= MEM_Ephem;
   59009       rc = sqlite3VdbeMemMakeWriteable(pTo);
   59010     }
   59011   }
   59012 
   59013   return rc;
   59014 }
   59015 
   59016 /*
   59017 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   59018 ** freed. If pFrom contains ephemeral data, a copy is made.
   59019 **
   59020 ** pFrom contains an SQL NULL when this routine returns.
   59021 */
   59022 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   59023   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   59024   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   59025   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   59026 
   59027   sqlite3VdbeMemRelease(pTo);
   59028   memcpy(pTo, pFrom, sizeof(Mem));
   59029   pFrom->flags = MEM_Null;
   59030   pFrom->xDel = 0;
   59031   pFrom->zMalloc = 0;
   59032 }
   59033 
   59034 /*
   59035 ** Change the value of a Mem to be a string or a BLOB.
   59036 **
   59037 ** The memory management strategy depends on the value of the xDel
   59038 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   59039 ** string is copied into a (possibly existing) buffer managed by the
   59040 ** Mem structure. Otherwise, any existing buffer is freed and the
   59041 ** pointer copied.
   59042 **
   59043 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   59044 ** size limit) then no memory allocation occurs.  If the string can be
   59045 ** stored without allocating memory, then it is.  If a memory allocation
   59046 ** is required to store the string, then value of pMem is unchanged.  In
   59047 ** either case, SQLITE_TOOBIG is returned.
   59048 */
   59049 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   59050   Mem *pMem,          /* Memory cell to set to string value */
   59051   const char *z,      /* String pointer */
   59052   int n,              /* Bytes in string, or negative */
   59053   u8 enc,             /* Encoding of z.  0 for BLOBs */
   59054   void (*xDel)(void*) /* Destructor function */
   59055 ){
   59056   int nByte = n;      /* New value for pMem->n */
   59057   int iLimit;         /* Maximum allowed string or blob size */
   59058   u16 flags = 0;      /* New value for pMem->flags */
   59059 
   59060   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   59061   assert( (pMem->flags & MEM_RowSet)==0 );
   59062 
   59063   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   59064   if( !z ){
   59065     sqlite3VdbeMemSetNull(pMem);
   59066     return SQLITE_OK;
   59067   }
   59068 
   59069   if( pMem->db ){
   59070     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   59071   }else{
   59072     iLimit = SQLITE_MAX_LENGTH;
   59073   }
   59074   flags = (enc==0?MEM_Blob:MEM_Str);
   59075   if( nByte<0 ){
   59076     assert( enc!=0 );
   59077     if( enc==SQLITE_UTF8 ){
   59078       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   59079     }else{
   59080       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   59081     }
   59082     flags |= MEM_Term;
   59083   }
   59084 
   59085   /* The following block sets the new values of Mem.z and Mem.xDel. It
   59086   ** also sets a flag in local variable "flags" to indicate the memory
   59087   ** management (one of MEM_Dyn or MEM_Static).
   59088   */
   59089   if( xDel==SQLITE_TRANSIENT ){
   59090     int nAlloc = nByte;
   59091     if( flags&MEM_Term ){
   59092       nAlloc += (enc==SQLITE_UTF8?1:2);
   59093     }
   59094     if( nByte>iLimit ){
   59095       return SQLITE_TOOBIG;
   59096     }
   59097     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   59098       return SQLITE_NOMEM;
   59099     }
   59100     memcpy(pMem->z, z, nAlloc);
   59101   }else if( xDel==SQLITE_DYNAMIC ){
   59102     sqlite3VdbeMemRelease(pMem);
   59103     pMem->zMalloc = pMem->z = (char *)z;
   59104     pMem->xDel = 0;
   59105   }else{
   59106     sqlite3VdbeMemRelease(pMem);
   59107     pMem->z = (char *)z;
   59108     pMem->xDel = xDel;
   59109     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   59110   }
   59111 
   59112   pMem->n = nByte;
   59113   pMem->flags = flags;
   59114   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   59115   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
   59116 
   59117 #ifndef SQLITE_OMIT_UTF16
   59118   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   59119     return SQLITE_NOMEM;
   59120   }
   59121 #endif
   59122 
   59123   if( nByte>iLimit ){
   59124     return SQLITE_TOOBIG;
   59125   }
   59126 
   59127   return SQLITE_OK;
   59128 }
   59129 
   59130 /*
   59131 ** Compare the values contained by the two memory cells, returning
   59132 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   59133 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   59134 ** and reals) sorted numerically, followed by text ordered by the collating
   59135 ** sequence pColl and finally blob's ordered by memcmp().
   59136 **
   59137 ** Two NULL values are considered equal by this function.
   59138 */
   59139 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   59140   int rc;
   59141   int f1, f2;
   59142   int combined_flags;
   59143 
   59144   f1 = pMem1->flags;
   59145   f2 = pMem2->flags;
   59146   combined_flags = f1|f2;
   59147   assert( (combined_flags & MEM_RowSet)==0 );
   59148 
   59149   /* If one value is NULL, it is less than the other. If both values
   59150   ** are NULL, return 0.
   59151   */
   59152   if( combined_flags&MEM_Null ){
   59153     return (f2&MEM_Null) - (f1&MEM_Null);
   59154   }
   59155 
   59156   /* If one value is a number and the other is not, the number is less.
   59157   ** If both are numbers, compare as reals if one is a real, or as integers
   59158   ** if both values are integers.
   59159   */
   59160   if( combined_flags&(MEM_Int|MEM_Real) ){
   59161     if( !(f1&(MEM_Int|MEM_Real)) ){
   59162       return 1;
   59163     }
   59164     if( !(f2&(MEM_Int|MEM_Real)) ){
   59165       return -1;
   59166     }
   59167     if( (f1 & f2 & MEM_Int)==0 ){
   59168       double r1, r2;
   59169       if( (f1&MEM_Real)==0 ){
   59170         r1 = (double)pMem1->u.i;
   59171       }else{
   59172         r1 = pMem1->r;
   59173       }
   59174       if( (f2&MEM_Real)==0 ){
   59175         r2 = (double)pMem2->u.i;
   59176       }else{
   59177         r2 = pMem2->r;
   59178       }
   59179       if( r1<r2 ) return -1;
   59180       if( r1>r2 ) return 1;
   59181       return 0;
   59182     }else{
   59183       assert( f1&MEM_Int );
   59184       assert( f2&MEM_Int );
   59185       if( pMem1->u.i < pMem2->u.i ) return -1;
   59186       if( pMem1->u.i > pMem2->u.i ) return 1;
   59187       return 0;
   59188     }
   59189   }
   59190 
   59191   /* If one value is a string and the other is a blob, the string is less.
   59192   ** If both are strings, compare using the collating functions.
   59193   */
   59194   if( combined_flags&MEM_Str ){
   59195     if( (f1 & MEM_Str)==0 ){
   59196       return 1;
   59197     }
   59198     if( (f2 & MEM_Str)==0 ){
   59199       return -1;
   59200     }
   59201 
   59202     assert( pMem1->enc==pMem2->enc );
   59203     assert( pMem1->enc==SQLITE_UTF8 ||
   59204             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   59205 
   59206     /* The collation sequence must be defined at this point, even if
   59207     ** the user deletes the collation sequence after the vdbe program is
   59208     ** compiled (this was not always the case).
   59209     */
   59210     assert( !pColl || pColl->xCmp );
   59211 
   59212     if( pColl ){
   59213       if( pMem1->enc==pColl->enc ){
   59214         /* The strings are already in the correct encoding.  Call the
   59215         ** comparison function directly */
   59216         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   59217       }else{
   59218         const void *v1, *v2;
   59219         int n1, n2;
   59220         Mem c1;
   59221         Mem c2;
   59222         memset(&c1, 0, sizeof(c1));
   59223         memset(&c2, 0, sizeof(c2));
   59224         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   59225         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   59226         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   59227         n1 = v1==0 ? 0 : c1.n;
   59228         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   59229         n2 = v2==0 ? 0 : c2.n;
   59230         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   59231         sqlite3VdbeMemRelease(&c1);
   59232         sqlite3VdbeMemRelease(&c2);
   59233         return rc;
   59234       }
   59235     }
   59236     /* If a NULL pointer was passed as the collate function, fall through
   59237     ** to the blob case and use memcmp().  */
   59238   }
   59239 
   59240   /* Both values must be blobs.  Compare using memcmp().  */
   59241   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   59242   if( rc==0 ){
   59243     rc = pMem1->n - pMem2->n;
   59244   }
   59245   return rc;
   59246 }
   59247 
   59248 /*
   59249 ** Move data out of a btree key or data field and into a Mem structure.
   59250 ** The data or key is taken from the entry that pCur is currently pointing
   59251 ** to.  offset and amt determine what portion of the data or key to retrieve.
   59252 ** key is true to get the key or false to get data.  The result is written
   59253 ** into the pMem element.
   59254 **
   59255 ** The pMem structure is assumed to be uninitialized.  Any prior content
   59256 ** is overwritten without being freed.
   59257 **
   59258 ** If this routine fails for any reason (malloc returns NULL or unable
   59259 ** to read from the disk) then the pMem is left in an inconsistent state.
   59260 */
   59261 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   59262   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   59263   int offset,       /* Offset from the start of data to return bytes from. */
   59264   int amt,          /* Number of bytes to return. */
   59265   int key,          /* If true, retrieve from the btree key, not data. */
   59266   Mem *pMem         /* OUT: Return data in this Mem structure. */
   59267 ){
   59268   char *zData;        /* Data from the btree layer */
   59269   int available = 0;  /* Number of bytes available on the local btree page */
   59270   int rc = SQLITE_OK; /* Return code */
   59271 
   59272   assert( sqlite3BtreeCursorIsValid(pCur) );
   59273 
   59274   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   59275   ** that both the BtShared and database handle mutexes are held. */
   59276   assert( (pMem->flags & MEM_RowSet)==0 );
   59277   if( key ){
   59278     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   59279   }else{
   59280     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   59281   }
   59282   assert( zData!=0 );
   59283 
   59284   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
   59285     sqlite3VdbeMemRelease(pMem);
   59286     pMem->z = &zData[offset];
   59287     pMem->flags = MEM_Blob|MEM_Ephem;
   59288   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   59289     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
   59290     pMem->enc = 0;
   59291     pMem->type = SQLITE_BLOB;
   59292     if( key ){
   59293       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   59294     }else{
   59295       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   59296     }
   59297     pMem->z[amt] = 0;
   59298     pMem->z[amt+1] = 0;
   59299     if( rc!=SQLITE_OK ){
   59300       sqlite3VdbeMemRelease(pMem);
   59301     }
   59302   }
   59303   pMem->n = amt;
   59304 
   59305   return rc;
   59306 }
   59307 
   59308 /* This function is only available internally, it is not part of the
   59309 ** external API. It works in a similar way to sqlite3_value_text(),
   59310 ** except the data returned is in the encoding specified by the second
   59311 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   59312 ** SQLITE_UTF8.
   59313 **
   59314 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   59315 ** If that is the case, then the result must be aligned on an even byte
   59316 ** boundary.
   59317 */
   59318 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   59319   if( !pVal ) return 0;
   59320 
   59321   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   59322   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   59323   assert( (pVal->flags & MEM_RowSet)==0 );
   59324 
   59325   if( pVal->flags&MEM_Null ){
   59326     return 0;
   59327   }
   59328   assert( (MEM_Blob>>3) == MEM_Str );
   59329   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   59330   ExpandBlob(pVal);
   59331   if( pVal->flags&MEM_Str ){
   59332     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   59333     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   59334       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   59335       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   59336         return 0;
   59337       }
   59338     }
   59339     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
   59340   }else{
   59341     assert( (pVal->flags&MEM_Blob)==0 );
   59342     sqlite3VdbeMemStringify(pVal, enc);
   59343     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   59344   }
   59345   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   59346               || pVal->db->mallocFailed );
   59347   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   59348     return pVal->z;
   59349   }else{
   59350     return 0;
   59351   }
   59352 }
   59353 
   59354 /*
   59355 ** Create a new sqlite3_value object.
   59356 */
   59357 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   59358   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   59359   if( p ){
   59360     p->flags = MEM_Null;
   59361     p->type = SQLITE_NULL;
   59362     p->db = db;
   59363   }
   59364   return p;
   59365 }
   59366 
   59367 /*
   59368 ** Create a new sqlite3_value object, containing the value of pExpr.
   59369 **
   59370 ** This only works for very simple expressions that consist of one constant
   59371 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   59372 ** be converted directly into a value, then the value is allocated and
   59373 ** a pointer written to *ppVal. The caller is responsible for deallocating
   59374 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   59375 ** cannot be converted to a value, then *ppVal is set to NULL.
   59376 */
   59377 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   59378   sqlite3 *db,              /* The database connection */
   59379   Expr *pExpr,              /* The expression to evaluate */
   59380   u8 enc,                   /* Encoding to use */
   59381   u8 affinity,              /* Affinity to use */
   59382   sqlite3_value **ppVal     /* Write the new value here */
   59383 ){
   59384   int op;
   59385   char *zVal = 0;
   59386   sqlite3_value *pVal = 0;
   59387   int negInt = 1;
   59388   const char *zNeg = "";
   59389 
   59390   if( !pExpr ){
   59391     *ppVal = 0;
   59392     return SQLITE_OK;
   59393   }
   59394   op = pExpr->op;
   59395 
   59396   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
   59397   ** The ifdef here is to enable us to achieve 100% branch test coverage even
   59398   ** when SQLITE_ENABLE_STAT3 is omitted.
   59399   */
   59400 #ifdef SQLITE_ENABLE_STAT3
   59401   if( op==TK_REGISTER ) op = pExpr->op2;
   59402 #else
   59403   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   59404 #endif
   59405 
   59406   /* Handle negative integers in a single step.  This is needed in the
   59407   ** case when the value is -9223372036854775808.
   59408   */
   59409   if( op==TK_UMINUS
   59410    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   59411     pExpr = pExpr->pLeft;
   59412     op = pExpr->op;
   59413     negInt = -1;
   59414     zNeg = "-";
   59415   }
   59416 
   59417   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   59418     pVal = sqlite3ValueNew(db);
   59419     if( pVal==0 ) goto no_mem;
   59420     if( ExprHasProperty(pExpr, EP_IntValue) ){
   59421       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   59422     }else{
   59423       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   59424       if( zVal==0 ) goto no_mem;
   59425       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   59426       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
   59427     }
   59428     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   59429       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   59430     }else{
   59431       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   59432     }
   59433     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   59434     if( enc!=SQLITE_UTF8 ){
   59435       sqlite3VdbeChangeEncoding(pVal, enc);
   59436     }
   59437   }else if( op==TK_UMINUS ) {
   59438     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   59439     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
   59440       sqlite3VdbeMemNumerify(pVal);
   59441       if( pVal->u.i==SMALLEST_INT64 ){
   59442         pVal->flags &= MEM_Int;
   59443         pVal->flags |= MEM_Real;
   59444         pVal->r = (double)LARGEST_INT64;
   59445       }else{
   59446         pVal->u.i = -pVal->u.i;
   59447       }
   59448       pVal->r = -pVal->r;
   59449       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   59450     }
   59451   }else if( op==TK_NULL ){
   59452     pVal = sqlite3ValueNew(db);
   59453     if( pVal==0 ) goto no_mem;
   59454   }
   59455 #ifndef SQLITE_OMIT_BLOB_LITERAL
   59456   else if( op==TK_BLOB ){
   59457     int nVal;
   59458     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   59459     assert( pExpr->u.zToken[1]=='\'' );
   59460     pVal = sqlite3ValueNew(db);
   59461     if( !pVal ) goto no_mem;
   59462     zVal = &pExpr->u.zToken[2];
   59463     nVal = sqlite3Strlen30(zVal)-1;
   59464     assert( zVal[nVal]=='\'' );
   59465     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   59466                          0, SQLITE_DYNAMIC);
   59467   }
   59468 #endif
   59469 
   59470   if( pVal ){
   59471     sqlite3VdbeMemStoreType(pVal);
   59472   }
   59473   *ppVal = pVal;
   59474   return SQLITE_OK;
   59475 
   59476 no_mem:
   59477   db->mallocFailed = 1;
   59478   sqlite3DbFree(db, zVal);
   59479   sqlite3ValueFree(pVal);
   59480   *ppVal = 0;
   59481   return SQLITE_NOMEM;
   59482 }
   59483 
   59484 /*
   59485 ** Change the string value of an sqlite3_value object
   59486 */
   59487 SQLITE_PRIVATE void sqlite3ValueSetStr(
   59488   sqlite3_value *v,     /* Value to be set */
   59489   int n,                /* Length of string z */
   59490   const void *z,        /* Text of the new string */
   59491   u8 enc,               /* Encoding to use */
   59492   void (*xDel)(void*)   /* Destructor for the string */
   59493 ){
   59494   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   59495 }
   59496 
   59497 /*
   59498 ** Free an sqlite3_value object
   59499 */
   59500 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   59501   if( !v ) return;
   59502   sqlite3VdbeMemRelease((Mem *)v);
   59503   sqlite3DbFree(((Mem*)v)->db, v);
   59504 }
   59505 
   59506 /*
   59507 ** Return the number of bytes in the sqlite3_value object assuming
   59508 ** that it uses the encoding "enc"
   59509 */
   59510 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   59511   Mem *p = (Mem*)pVal;
   59512   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   59513     if( p->flags & MEM_Zero ){
   59514       return p->n + p->u.nZero;
   59515     }else{
   59516       return p->n;
   59517     }
   59518   }
   59519   return 0;
   59520 }
   59521 
   59522 /************** End of vdbemem.c *********************************************/
   59523 /************** Begin file vdbeaux.c *****************************************/
   59524 /*
   59525 ** 2003 September 6
   59526 **
   59527 ** The author disclaims copyright to this source code.  In place of
   59528 ** a legal notice, here is a blessing:
   59529 **
   59530 **    May you do good and not evil.
   59531 **    May you find forgiveness for yourself and forgive others.
   59532 **    May you share freely, never taking more than you give.
   59533 **
   59534 *************************************************************************
   59535 ** This file contains code used for creating, destroying, and populating
   59536 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   59537 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   59538 ** But that file was getting too big so this subroutines were split out.
   59539 */
   59540 
   59541 
   59542 
   59543 /*
   59544 ** When debugging the code generator in a symbolic debugger, one can
   59545 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
   59546 ** as they are added to the instruction stream.
   59547 */
   59548 #ifdef SQLITE_DEBUG
   59549 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
   59550 #endif
   59551 
   59552 
   59553 /*
   59554 ** Create a new virtual database engine.
   59555 */
   59556 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
   59557   Vdbe *p;
   59558   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   59559   if( p==0 ) return 0;
   59560   p->db = db;
   59561   if( db->pVdbe ){
   59562     db->pVdbe->pPrev = p;
   59563   }
   59564   p->pNext = db->pVdbe;
   59565   p->pPrev = 0;
   59566   db->pVdbe = p;
   59567   p->magic = VDBE_MAGIC_INIT;
   59568   return p;
   59569 }
   59570 
   59571 /*
   59572 ** Remember the SQL string for a prepared statement.
   59573 */
   59574 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   59575   assert( isPrepareV2==1 || isPrepareV2==0 );
   59576   if( p==0 ) return;
   59577 #ifdef SQLITE_OMIT_TRACE
   59578   if( !isPrepareV2 ) return;
   59579 #endif
   59580   assert( p->zSql==0 );
   59581   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   59582   p->isPrepareV2 = (u8)isPrepareV2;
   59583 }
   59584 
   59585 /*
   59586 ** Return the SQL associated with a prepared statement
   59587 */
   59588 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   59589   Vdbe *p = (Vdbe *)pStmt;
   59590   return (p && p->isPrepareV2) ? p->zSql : 0;
   59591 }
   59592 
   59593 /*
   59594 ** Swap all content between two VDBE structures.
   59595 */
   59596 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   59597   Vdbe tmp, *pTmp;
   59598   char *zTmp;
   59599   tmp = *pA;
   59600   *pA = *pB;
   59601   *pB = tmp;
   59602   pTmp = pA->pNext;
   59603   pA->pNext = pB->pNext;
   59604   pB->pNext = pTmp;
   59605   pTmp = pA->pPrev;
   59606   pA->pPrev = pB->pPrev;
   59607   pB->pPrev = pTmp;
   59608   zTmp = pA->zSql;
   59609   pA->zSql = pB->zSql;
   59610   pB->zSql = zTmp;
   59611   pB->isPrepareV2 = pA->isPrepareV2;
   59612 }
   59613 
   59614 #ifdef SQLITE_DEBUG
   59615 /*
   59616 ** Turn tracing on or off
   59617 */
   59618 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
   59619   p->trace = trace;
   59620 }
   59621 #endif
   59622 
   59623 /*
   59624 ** Resize the Vdbe.aOp array so that it is at least one op larger than
   59625 ** it was.
   59626 **
   59627 ** If an out-of-memory error occurs while resizing the array, return
   59628 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
   59629 ** unchanged (this is so that any opcodes already allocated can be
   59630 ** correctly deallocated along with the rest of the Vdbe).
   59631 */
   59632 static int growOpArray(Vdbe *p){
   59633   VdbeOp *pNew;
   59634   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   59635   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   59636   if( pNew ){
   59637     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   59638     p->aOp = pNew;
   59639   }
   59640   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   59641 }
   59642 
   59643 /*
   59644 ** Add a new instruction to the list of instructions current in the
   59645 ** VDBE.  Return the address of the new instruction.
   59646 **
   59647 ** Parameters:
   59648 **
   59649 **    p               Pointer to the VDBE
   59650 **
   59651 **    op              The opcode for this instruction
   59652 **
   59653 **    p1, p2, p3      Operands
   59654 **
   59655 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   59656 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   59657 ** operand.
   59658 */
   59659 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   59660   int i;
   59661   VdbeOp *pOp;
   59662 
   59663   i = p->nOp;
   59664   assert( p->magic==VDBE_MAGIC_INIT );
   59665   assert( op>0 && op<0xff );
   59666   if( p->nOpAlloc<=i ){
   59667     if( growOpArray(p) ){
   59668       return 1;
   59669     }
   59670   }
   59671   p->nOp++;
   59672   pOp = &p->aOp[i];
   59673   pOp->opcode = (u8)op;
   59674   pOp->p5 = 0;
   59675   pOp->p1 = p1;
   59676   pOp->p2 = p2;
   59677   pOp->p3 = p3;
   59678   pOp->p4.p = 0;
   59679   pOp->p4type = P4_NOTUSED;
   59680 #ifdef SQLITE_DEBUG
   59681   pOp->zComment = 0;
   59682   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   59683 #endif
   59684 #ifdef VDBE_PROFILE
   59685   pOp->cycles = 0;
   59686   pOp->cnt = 0;
   59687 #endif
   59688   return i;
   59689 }
   59690 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   59691   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   59692 }
   59693 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   59694   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   59695 }
   59696 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   59697   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   59698 }
   59699 
   59700 
   59701 /*
   59702 ** Add an opcode that includes the p4 value as a pointer.
   59703 */
   59704 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   59705   Vdbe *p,            /* Add the opcode to this VM */
   59706   int op,             /* The new opcode */
   59707   int p1,             /* The P1 operand */
   59708   int p2,             /* The P2 operand */
   59709   int p3,             /* The P3 operand */
   59710   const char *zP4,    /* The P4 operand */
   59711   int p4type          /* P4 operand type */
   59712 ){
   59713   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   59714   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   59715   return addr;
   59716 }
   59717 
   59718 /*
   59719 ** Add an OP_ParseSchema opcode.  This routine is broken out from
   59720 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
   59721 ** as having been used.
   59722 **
   59723 ** The zWhere string must have been obtained from sqlite3_malloc().
   59724 ** This routine will take ownership of the allocated memory.
   59725 */
   59726 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   59727   int j;
   59728   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
   59729   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
   59730   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
   59731 }
   59732 
   59733 /*
   59734 ** Add an opcode that includes the p4 value as an integer.
   59735 */
   59736 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   59737   Vdbe *p,            /* Add the opcode to this VM */
   59738   int op,             /* The new opcode */
   59739   int p1,             /* The P1 operand */
   59740   int p2,             /* The P2 operand */
   59741   int p3,             /* The P3 operand */
   59742   int p4              /* The P4 operand as an integer */
   59743 ){
   59744   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   59745   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   59746   return addr;
   59747 }
   59748 
   59749 /*
   59750 ** Create a new symbolic label for an instruction that has yet to be
   59751 ** coded.  The symbolic label is really just a negative number.  The
   59752 ** label can be used as the P2 value of an operation.  Later, when
   59753 ** the label is resolved to a specific address, the VDBE will scan
   59754 ** through its operation list and change all values of P2 which match
   59755 ** the label into the resolved address.
   59756 **
   59757 ** The VDBE knows that a P2 value is a label because labels are
   59758 ** always negative and P2 values are suppose to be non-negative.
   59759 ** Hence, a negative P2 value is a label that has yet to be resolved.
   59760 **
   59761 ** Zero is returned if a malloc() fails.
   59762 */
   59763 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
   59764   int i = p->nLabel++;
   59765   assert( p->magic==VDBE_MAGIC_INIT );
   59766   if( (i & (i-1))==0 ){
   59767     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   59768                                        (i*2+1)*sizeof(p->aLabel[0]));
   59769   }
   59770   if( p->aLabel ){
   59771     p->aLabel[i] = -1;
   59772   }
   59773   return -1-i;
   59774 }
   59775 
   59776 /*
   59777 ** Resolve label "x" to be the address of the next instruction to
   59778 ** be inserted.  The parameter "x" must have been obtained from
   59779 ** a prior call to sqlite3VdbeMakeLabel().
   59780 */
   59781 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   59782   int j = -1-x;
   59783   assert( p->magic==VDBE_MAGIC_INIT );
   59784   assert( j>=0 && j<p->nLabel );
   59785   if( p->aLabel ){
   59786     p->aLabel[j] = p->nOp;
   59787   }
   59788 }
   59789 
   59790 /*
   59791 ** Mark the VDBE as one that can only be run one time.
   59792 */
   59793 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   59794   p->runOnlyOnce = 1;
   59795 }
   59796 
   59797 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   59798 
   59799 /*
   59800 ** The following type and function are used to iterate through all opcodes
   59801 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   59802 ** invoke directly or indirectly. It should be used as follows:
   59803 **
   59804 **   Op *pOp;
   59805 **   VdbeOpIter sIter;
   59806 **
   59807 **   memset(&sIter, 0, sizeof(sIter));
   59808 **   sIter.v = v;                            // v is of type Vdbe*
   59809 **   while( (pOp = opIterNext(&sIter)) ){
   59810 **     // Do something with pOp
   59811 **   }
   59812 **   sqlite3DbFree(v->db, sIter.apSub);
   59813 **
   59814 */
   59815 typedef struct VdbeOpIter VdbeOpIter;
   59816 struct VdbeOpIter {
   59817   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   59818   SubProgram **apSub;        /* Array of subprograms */
   59819   int nSub;                  /* Number of entries in apSub */
   59820   int iAddr;                 /* Address of next instruction to return */
   59821   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   59822 };
   59823 static Op *opIterNext(VdbeOpIter *p){
   59824   Vdbe *v = p->v;
   59825   Op *pRet = 0;
   59826   Op *aOp;
   59827   int nOp;
   59828 
   59829   if( p->iSub<=p->nSub ){
   59830 
   59831     if( p->iSub==0 ){
   59832       aOp = v->aOp;
   59833       nOp = v->nOp;
   59834     }else{
   59835       aOp = p->apSub[p->iSub-1]->aOp;
   59836       nOp = p->apSub[p->iSub-1]->nOp;
   59837     }
   59838     assert( p->iAddr<nOp );
   59839 
   59840     pRet = &aOp[p->iAddr];
   59841     p->iAddr++;
   59842     if( p->iAddr==nOp ){
   59843       p->iSub++;
   59844       p->iAddr = 0;
   59845     }
   59846 
   59847     if( pRet->p4type==P4_SUBPROGRAM ){
   59848       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   59849       int j;
   59850       for(j=0; j<p->nSub; j++){
   59851         if( p->apSub[j]==pRet->p4.pProgram ) break;
   59852       }
   59853       if( j==p->nSub ){
   59854         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   59855         if( !p->apSub ){
   59856           pRet = 0;
   59857         }else{
   59858           p->apSub[p->nSub++] = pRet->p4.pProgram;
   59859         }
   59860       }
   59861     }
   59862   }
   59863 
   59864   return pRet;
   59865 }
   59866 
   59867 /*
   59868 ** Check if the program stored in the VM associated with pParse may
   59869 ** throw an ABORT exception (causing the statement, but not entire transaction
   59870 ** to be rolled back). This condition is true if the main program or any
   59871 ** sub-programs contains any of the following:
   59872 **
   59873 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   59874 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   59875 **   *  OP_Destroy
   59876 **   *  OP_VUpdate
   59877 **   *  OP_VRename
   59878 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   59879 **
   59880 ** Then check that the value of Parse.mayAbort is true if an
   59881 ** ABORT may be thrown, or false otherwise. Return true if it does
   59882 ** match, or false otherwise. This function is intended to be used as
   59883 ** part of an assert statement in the compiler. Similar to:
   59884 **
   59885 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   59886 */
   59887 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   59888   int hasAbort = 0;
   59889   Op *pOp;
   59890   VdbeOpIter sIter;
   59891   memset(&sIter, 0, sizeof(sIter));
   59892   sIter.v = v;
   59893 
   59894   while( (pOp = opIterNext(&sIter))!=0 ){
   59895     int opcode = pOp->opcode;
   59896     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   59897 #ifndef SQLITE_OMIT_FOREIGN_KEY
   59898      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   59899 #endif
   59900      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   59901       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   59902     ){
   59903       hasAbort = 1;
   59904       break;
   59905     }
   59906   }
   59907   sqlite3DbFree(v->db, sIter.apSub);
   59908 
   59909   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
   59910   ** If malloc failed, then the while() loop above may not have iterated
   59911   ** through all opcodes and hasAbort may be set incorrectly. Return
   59912   ** true for this case to prevent the assert() in the callers frame
   59913   ** from failing.  */
   59914   return ( v->db->mallocFailed || hasAbort==mayAbort );
   59915 }
   59916 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   59917 
   59918 /*
   59919 ** Loop through the program looking for P2 values that are negative
   59920 ** on jump instructions.  Each such value is a label.  Resolve the
   59921 ** label by setting the P2 value to its correct non-zero value.
   59922 **
   59923 ** This routine is called once after all opcodes have been inserted.
   59924 **
   59925 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   59926 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   59927 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   59928 **
   59929 ** The Op.opflags field is set on all opcodes.
   59930 */
   59931 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   59932   int i;
   59933   int nMaxArgs = *pMaxFuncArgs;
   59934   Op *pOp;
   59935   int *aLabel = p->aLabel;
   59936   p->readOnly = 1;
   59937   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   59938     u8 opcode = pOp->opcode;
   59939 
   59940     pOp->opflags = sqlite3OpcodeProperty[opcode];
   59941     if( opcode==OP_Function || opcode==OP_AggStep ){
   59942       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   59943     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
   59944       p->readOnly = 0;
   59945 #ifndef SQLITE_OMIT_VIRTUALTABLE
   59946     }else if( opcode==OP_VUpdate ){
   59947       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   59948     }else if( opcode==OP_VFilter ){
   59949       int n;
   59950       assert( p->nOp - i >= 3 );
   59951       assert( pOp[-1].opcode==OP_Integer );
   59952       n = pOp[-1].p1;
   59953       if( n>nMaxArgs ) nMaxArgs = n;
   59954 #endif
   59955     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
   59956       pOp->p4.xAdvance = sqlite3BtreeNext;
   59957       pOp->p4type = P4_ADVANCE;
   59958     }else if( opcode==OP_Prev ){
   59959       pOp->p4.xAdvance = sqlite3BtreePrevious;
   59960       pOp->p4type = P4_ADVANCE;
   59961     }
   59962 
   59963     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   59964       assert( -1-pOp->p2<p->nLabel );
   59965       pOp->p2 = aLabel[-1-pOp->p2];
   59966     }
   59967   }
   59968   sqlite3DbFree(p->db, p->aLabel);
   59969   p->aLabel = 0;
   59970 
   59971   *pMaxFuncArgs = nMaxArgs;
   59972 }
   59973 
   59974 /*
   59975 ** Return the address of the next instruction to be inserted.
   59976 */
   59977 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   59978   assert( p->magic==VDBE_MAGIC_INIT );
   59979   return p->nOp;
   59980 }
   59981 
   59982 /*
   59983 ** This function returns a pointer to the array of opcodes associated with
   59984 ** the Vdbe passed as the first argument. It is the callers responsibility
   59985 ** to arrange for the returned array to be eventually freed using the
   59986 ** vdbeFreeOpArray() function.
   59987 **
   59988 ** Before returning, *pnOp is set to the number of entries in the returned
   59989 ** array. Also, *pnMaxArg is set to the larger of its current value and
   59990 ** the number of entries in the Vdbe.apArg[] array required to execute the
   59991 ** returned program.
   59992 */
   59993 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   59994   VdbeOp *aOp = p->aOp;
   59995   assert( aOp && !p->db->mallocFailed );
   59996 
   59997   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   59998   assert( p->btreeMask==0 );
   59999 
   60000   resolveP2Values(p, pnMaxArg);
   60001   *pnOp = p->nOp;
   60002   p->aOp = 0;
   60003   return aOp;
   60004 }
   60005 
   60006 /*
   60007 ** Add a whole list of operations to the operation stack.  Return the
   60008 ** address of the first operation added.
   60009 */
   60010 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   60011   int addr;
   60012   assert( p->magic==VDBE_MAGIC_INIT );
   60013   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
   60014     return 0;
   60015   }
   60016   addr = p->nOp;
   60017   if( ALWAYS(nOp>0) ){
   60018     int i;
   60019     VdbeOpList const *pIn = aOp;
   60020     for(i=0; i<nOp; i++, pIn++){
   60021       int p2 = pIn->p2;
   60022       VdbeOp *pOut = &p->aOp[i+addr];
   60023       pOut->opcode = pIn->opcode;
   60024       pOut->p1 = pIn->p1;
   60025       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
   60026         pOut->p2 = addr + ADDR(p2);
   60027       }else{
   60028         pOut->p2 = p2;
   60029       }
   60030       pOut->p3 = pIn->p3;
   60031       pOut->p4type = P4_NOTUSED;
   60032       pOut->p4.p = 0;
   60033       pOut->p5 = 0;
   60034 #ifdef SQLITE_DEBUG
   60035       pOut->zComment = 0;
   60036       if( sqlite3VdbeAddopTrace ){
   60037         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   60038       }
   60039 #endif
   60040     }
   60041     p->nOp += nOp;
   60042   }
   60043   return addr;
   60044 }
   60045 
   60046 /*
   60047 ** Change the value of the P1 operand for a specific instruction.
   60048 ** This routine is useful when a large program is loaded from a
   60049 ** static array using sqlite3VdbeAddOpList but we want to make a
   60050 ** few minor changes to the program.
   60051 */
   60052 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
   60053   assert( p!=0 );
   60054   if( ((u32)p->nOp)>addr ){
   60055     p->aOp[addr].p1 = val;
   60056   }
   60057 }
   60058 
   60059 /*
   60060 ** Change the value of the P2 operand for a specific instruction.
   60061 ** This routine is useful for setting a jump destination.
   60062 */
   60063 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
   60064   assert( p!=0 );
   60065   if( ((u32)p->nOp)>addr ){
   60066     p->aOp[addr].p2 = val;
   60067   }
   60068 }
   60069 
   60070 /*
   60071 ** Change the value of the P3 operand for a specific instruction.
   60072 */
   60073 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
   60074   assert( p!=0 );
   60075   if( ((u32)p->nOp)>addr ){
   60076     p->aOp[addr].p3 = val;
   60077   }
   60078 }
   60079 
   60080 /*
   60081 ** Change the value of the P5 operand for the most recently
   60082 ** added operation.
   60083 */
   60084 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   60085   assert( p!=0 );
   60086   if( p->aOp ){
   60087     assert( p->nOp>0 );
   60088     p->aOp[p->nOp-1].p5 = val;
   60089   }
   60090 }
   60091 
   60092 /*
   60093 ** Change the P2 operand of instruction addr so that it points to
   60094 ** the address of the next instruction to be coded.
   60095 */
   60096 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   60097   assert( addr>=0 || p->db->mallocFailed );
   60098   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
   60099 }
   60100 
   60101 
   60102 /*
   60103 ** If the input FuncDef structure is ephemeral, then free it.  If
   60104 ** the FuncDef is not ephermal, then do nothing.
   60105 */
   60106 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   60107   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
   60108     sqlite3DbFree(db, pDef);
   60109   }
   60110 }
   60111 
   60112 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   60113 
   60114 /*
   60115 ** Delete a P4 value if necessary.
   60116 */
   60117 static void freeP4(sqlite3 *db, int p4type, void *p4){
   60118   if( p4 ){
   60119     assert( db );
   60120     switch( p4type ){
   60121       case P4_REAL:
   60122       case P4_INT64:
   60123       case P4_DYNAMIC:
   60124       case P4_KEYINFO:
   60125       case P4_INTARRAY:
   60126       case P4_KEYINFO_HANDOFF: {
   60127         sqlite3DbFree(db, p4);
   60128         break;
   60129       }
   60130       case P4_MPRINTF: {
   60131         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
   60132         break;
   60133       }
   60134       case P4_VDBEFUNC: {
   60135         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
   60136         freeEphemeralFunction(db, pVdbeFunc->pFunc);
   60137         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
   60138         sqlite3DbFree(db, pVdbeFunc);
   60139         break;
   60140       }
   60141       case P4_FUNCDEF: {
   60142         freeEphemeralFunction(db, (FuncDef*)p4);
   60143         break;
   60144       }
   60145       case P4_MEM: {
   60146         if( db->pnBytesFreed==0 ){
   60147           sqlite3ValueFree((sqlite3_value*)p4);
   60148         }else{
   60149           Mem *p = (Mem*)p4;
   60150           sqlite3DbFree(db, p->zMalloc);
   60151           sqlite3DbFree(db, p);
   60152         }
   60153         break;
   60154       }
   60155       case P4_VTAB : {
   60156         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   60157         break;
   60158       }
   60159     }
   60160   }
   60161 }
   60162 
   60163 /*
   60164 ** Free the space allocated for aOp and any p4 values allocated for the
   60165 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   60166 ** nOp entries.
   60167 */
   60168 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   60169   if( aOp ){
   60170     Op *pOp;
   60171     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   60172       freeP4(db, pOp->p4type, pOp->p4.p);
   60173 #ifdef SQLITE_DEBUG
   60174       sqlite3DbFree(db, pOp->zComment);
   60175 #endif
   60176     }
   60177   }
   60178   sqlite3DbFree(db, aOp);
   60179 }
   60180 
   60181 /*
   60182 ** Link the SubProgram object passed as the second argument into the linked
   60183 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   60184 ** objects when the VM is no longer required.
   60185 */
   60186 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   60187   p->pNext = pVdbe->pProgram;
   60188   pVdbe->pProgram = p;
   60189 }
   60190 
   60191 /*
   60192 ** Change the opcode at addr into OP_Noop
   60193 */
   60194 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
   60195   if( p->aOp ){
   60196     VdbeOp *pOp = &p->aOp[addr];
   60197     sqlite3 *db = p->db;
   60198     freeP4(db, pOp->p4type, pOp->p4.p);
   60199     memset(pOp, 0, sizeof(pOp[0]));
   60200     pOp->opcode = OP_Noop;
   60201   }
   60202 }
   60203 
   60204 /*
   60205 ** Change the value of the P4 operand for a specific instruction.
   60206 ** This routine is useful when a large program is loaded from a
   60207 ** static array using sqlite3VdbeAddOpList but we want to make a
   60208 ** few minor changes to the program.
   60209 **
   60210 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   60211 ** the string is made into memory obtained from sqlite3_malloc().
   60212 ** A value of n==0 means copy bytes of zP4 up to and including the
   60213 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   60214 **
   60215 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
   60216 ** A copy is made of the KeyInfo structure into memory obtained from
   60217 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
   60218 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
   60219 ** stored in memory that the caller has obtained from sqlite3_malloc. The
   60220 ** caller should not free the allocation, it will be freed when the Vdbe is
   60221 ** finalized.
   60222 **
   60223 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   60224 ** to a string or structure that is guaranteed to exist for the lifetime of
   60225 ** the Vdbe. In these cases we can just copy the pointer.
   60226 **
   60227 ** If addr<0 then change P4 on the most recently inserted instruction.
   60228 */
   60229 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   60230   Op *pOp;
   60231   sqlite3 *db;
   60232   assert( p!=0 );
   60233   db = p->db;
   60234   assert( p->magic==VDBE_MAGIC_INIT );
   60235   if( p->aOp==0 || db->mallocFailed ){
   60236     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
   60237       freeP4(db, n, (void*)*(char**)&zP4);
   60238     }
   60239     return;
   60240   }
   60241   assert( p->nOp>0 );
   60242   assert( addr<p->nOp );
   60243   if( addr<0 ){
   60244     addr = p->nOp - 1;
   60245   }
   60246   pOp = &p->aOp[addr];
   60247   freeP4(db, pOp->p4type, pOp->p4.p);
   60248   pOp->p4.p = 0;
   60249   if( n==P4_INT32 ){
   60250     /* Note: this cast is safe, because the origin data point was an int
   60251     ** that was cast to a (const char *). */
   60252     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   60253     pOp->p4type = P4_INT32;
   60254   }else if( zP4==0 ){
   60255     pOp->p4.p = 0;
   60256     pOp->p4type = P4_NOTUSED;
   60257   }else if( n==P4_KEYINFO ){
   60258     KeyInfo *pKeyInfo;
   60259     int nField, nByte;
   60260 
   60261     nField = ((KeyInfo*)zP4)->nField;
   60262     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   60263     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
   60264     pOp->p4.pKeyInfo = pKeyInfo;
   60265     if( pKeyInfo ){
   60266       u8 *aSortOrder;
   60267       memcpy((char*)pKeyInfo, zP4, nByte - nField);
   60268       aSortOrder = pKeyInfo->aSortOrder;
   60269       if( aSortOrder ){
   60270         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   60271         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
   60272       }
   60273       pOp->p4type = P4_KEYINFO;
   60274     }else{
   60275       p->db->mallocFailed = 1;
   60276       pOp->p4type = P4_NOTUSED;
   60277     }
   60278   }else if( n==P4_KEYINFO_HANDOFF ){
   60279     pOp->p4.p = (void*)zP4;
   60280     pOp->p4type = P4_KEYINFO;
   60281   }else if( n==P4_VTAB ){
   60282     pOp->p4.p = (void*)zP4;
   60283     pOp->p4type = P4_VTAB;
   60284     sqlite3VtabLock((VTable *)zP4);
   60285     assert( ((VTable *)zP4)->db==p->db );
   60286   }else if( n<0 ){
   60287     pOp->p4.p = (void*)zP4;
   60288     pOp->p4type = (signed char)n;
   60289   }else{
   60290     if( n==0 ) n = sqlite3Strlen30(zP4);
   60291     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   60292     pOp->p4type = P4_DYNAMIC;
   60293   }
   60294 }
   60295 
   60296 #ifndef NDEBUG
   60297 /*
   60298 ** Change the comment on the the most recently coded instruction.  Or
   60299 ** insert a No-op and add the comment to that new instruction.  This
   60300 ** makes the code easier to read during debugging.  None of this happens
   60301 ** in a production build.
   60302 */
   60303 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   60304   assert( p->nOp>0 || p->aOp==0 );
   60305   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   60306   if( p->nOp ){
   60307     assert( p->aOp );
   60308     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
   60309     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
   60310   }
   60311 }
   60312 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   60313   va_list ap;
   60314   if( p ){
   60315     va_start(ap, zFormat);
   60316     vdbeVComment(p, zFormat, ap);
   60317     va_end(ap);
   60318   }
   60319 }
   60320 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   60321   va_list ap;
   60322   if( p ){
   60323     sqlite3VdbeAddOp0(p, OP_Noop);
   60324     va_start(ap, zFormat);
   60325     vdbeVComment(p, zFormat, ap);
   60326     va_end(ap);
   60327   }
   60328 }
   60329 #endif  /* NDEBUG */
   60330 
   60331 /*
   60332 ** Return the opcode for a given address.  If the address is -1, then
   60333 ** return the most recently inserted opcode.
   60334 **
   60335 ** If a memory allocation error has occurred prior to the calling of this
   60336 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   60337 ** is readable but not writable, though it is cast to a writable value.
   60338 ** The return of a dummy opcode allows the call to continue functioning
   60339 ** after a OOM fault without having to check to see if the return from
   60340 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   60341 ** dummy will never be written to.  This is verified by code inspection and
   60342 ** by running with Valgrind.
   60343 **
   60344 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
   60345 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
   60346 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
   60347 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
   60348 ** having to double-check to make sure that the result is non-negative. But
   60349 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
   60350 ** check the value of p->nOp-1 before continuing.
   60351 */
   60352 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   60353   /* C89 specifies that the constant "dummy" will be initialized to all
   60354   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   60355   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   60356   assert( p->magic==VDBE_MAGIC_INIT );
   60357   if( addr<0 ){
   60358 #ifdef SQLITE_OMIT_TRACE
   60359     if( p->nOp==0 ) return (VdbeOp*)&dummy;
   60360 #endif
   60361     addr = p->nOp - 1;
   60362   }
   60363   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   60364   if( p->db->mallocFailed ){
   60365     return (VdbeOp*)&dummy;
   60366   }else{
   60367     return &p->aOp[addr];
   60368   }
   60369 }
   60370 
   60371 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   60372      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   60373 /*
   60374 ** Compute a string that describes the P4 parameter for an opcode.
   60375 ** Use zTemp for any required temporary buffer space.
   60376 */
   60377 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   60378   char *zP4 = zTemp;
   60379   assert( nTemp>=20 );
   60380   switch( pOp->p4type ){
   60381     case P4_KEYINFO_STATIC:
   60382     case P4_KEYINFO: {
   60383       int i, j;
   60384       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   60385       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
   60386       i = sqlite3Strlen30(zTemp);
   60387       for(j=0; j<pKeyInfo->nField; j++){
   60388         CollSeq *pColl = pKeyInfo->aColl[j];
   60389         if( pColl ){
   60390           int n = sqlite3Strlen30(pColl->zName);
   60391           if( i+n>nTemp-6 ){
   60392             memcpy(&zTemp[i],",...",4);
   60393             break;
   60394           }
   60395           zTemp[i++] = ',';
   60396           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
   60397             zTemp[i++] = '-';
   60398           }
   60399           memcpy(&zTemp[i], pColl->zName,n+1);
   60400           i += n;
   60401         }else if( i+4<nTemp-6 ){
   60402           memcpy(&zTemp[i],",nil",4);
   60403           i += 4;
   60404         }
   60405       }
   60406       zTemp[i++] = ')';
   60407       zTemp[i] = 0;
   60408       assert( i<nTemp );
   60409       break;
   60410     }
   60411     case P4_COLLSEQ: {
   60412       CollSeq *pColl = pOp->p4.pColl;
   60413       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
   60414       break;
   60415     }
   60416     case P4_FUNCDEF: {
   60417       FuncDef *pDef = pOp->p4.pFunc;
   60418       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   60419       break;
   60420     }
   60421     case P4_INT64: {
   60422       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   60423       break;
   60424     }
   60425     case P4_INT32: {
   60426       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   60427       break;
   60428     }
   60429     case P4_REAL: {
   60430       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   60431       break;
   60432     }
   60433     case P4_MEM: {
   60434       Mem *pMem = pOp->p4.pMem;
   60435       if( pMem->flags & MEM_Str ){
   60436         zP4 = pMem->z;
   60437       }else if( pMem->flags & MEM_Int ){
   60438         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   60439       }else if( pMem->flags & MEM_Real ){
   60440         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   60441       }else if( pMem->flags & MEM_Null ){
   60442         sqlite3_snprintf(nTemp, zTemp, "NULL");
   60443       }else{
   60444         assert( pMem->flags & MEM_Blob );
   60445         zP4 = "(blob)";
   60446       }
   60447       break;
   60448     }
   60449 #ifndef SQLITE_OMIT_VIRTUALTABLE
   60450     case P4_VTAB: {
   60451       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   60452       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   60453       break;
   60454     }
   60455 #endif
   60456     case P4_INTARRAY: {
   60457       sqlite3_snprintf(nTemp, zTemp, "intarray");
   60458       break;
   60459     }
   60460     case P4_SUBPROGRAM: {
   60461       sqlite3_snprintf(nTemp, zTemp, "program");
   60462       break;
   60463     }
   60464     case P4_ADVANCE: {
   60465       zTemp[0] = 0;
   60466       break;
   60467     }
   60468     default: {
   60469       zP4 = pOp->p4.z;
   60470       if( zP4==0 ){
   60471         zP4 = zTemp;
   60472         zTemp[0] = 0;
   60473       }
   60474     }
   60475   }
   60476   assert( zP4!=0 );
   60477   return zP4;
   60478 }
   60479 #endif
   60480 
   60481 /*
   60482 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   60483 **
   60484 ** The prepared statements need to know in advance the complete set of
   60485 ** attached databases that will be use.  A mask of these databases
   60486 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
   60487 ** p->btreeMask of databases that will require a lock.
   60488 */
   60489 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   60490   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
   60491   assert( i<(int)sizeof(p->btreeMask)*8 );
   60492   p->btreeMask |= ((yDbMask)1)<<i;
   60493   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
   60494     p->lockMask |= ((yDbMask)1)<<i;
   60495   }
   60496 }
   60497 
   60498 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   60499 /*
   60500 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   60501 ** this routine obtains the mutex associated with each BtShared structure
   60502 ** that may be accessed by the VM passed as an argument. In doing so it also
   60503 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   60504 ** that the correct busy-handler callback is invoked if required.
   60505 **
   60506 ** If SQLite is not threadsafe but does support shared-cache mode, then
   60507 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
   60508 ** of all of BtShared structures accessible via the database handle
   60509 ** associated with the VM.
   60510 **
   60511 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   60512 ** function is a no-op.
   60513 **
   60514 ** The p->btreeMask field is a bitmask of all btrees that the prepared
   60515 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
   60516 ** corresponding to btrees that use shared cache.  Then the runtime of
   60517 ** this routine is N*N.  But as N is rarely more than 1, this should not
   60518 ** be a problem.
   60519 */
   60520 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
   60521   int i;
   60522   yDbMask mask;
   60523   sqlite3 *db;
   60524   Db *aDb;
   60525   int nDb;
   60526   if( p->lockMask==0 ) return;  /* The common case */
   60527   db = p->db;
   60528   aDb = db->aDb;
   60529   nDb = db->nDb;
   60530   for(i=0, mask=1; i<nDb; i++, mask += mask){
   60531     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
   60532       sqlite3BtreeEnter(aDb[i].pBt);
   60533     }
   60534   }
   60535 }
   60536 #endif
   60537 
   60538 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
   60539 /*
   60540 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
   60541 */
   60542 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
   60543   int i;
   60544   yDbMask mask;
   60545   sqlite3 *db;
   60546   Db *aDb;
   60547   int nDb;
   60548   if( p->lockMask==0 ) return;  /* The common case */
   60549   db = p->db;
   60550   aDb = db->aDb;
   60551   nDb = db->nDb;
   60552   for(i=0, mask=1; i<nDb; i++, mask += mask){
   60553     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
   60554       sqlite3BtreeLeave(aDb[i].pBt);
   60555     }
   60556   }
   60557 }
   60558 #endif
   60559 
   60560 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   60561 /*
   60562 ** Print a single opcode.  This routine is used for debugging only.
   60563 */
   60564 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   60565   char *zP4;
   60566   char zPtr[50];
   60567   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
   60568   if( pOut==0 ) pOut = stdout;
   60569   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   60570   fprintf(pOut, zFormat1, pc,
   60571       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   60572 #ifdef SQLITE_DEBUG
   60573       pOp->zComment ? pOp->zComment : ""
   60574 #else
   60575       ""
   60576 #endif
   60577   );
   60578   fflush(pOut);
   60579 }
   60580 #endif
   60581 
   60582 /*
   60583 ** Release an array of N Mem elements
   60584 */
   60585 static void releaseMemArray(Mem *p, int N){
   60586   if( p && N ){
   60587     Mem *pEnd;
   60588     sqlite3 *db = p->db;
   60589     u8 malloc_failed = db->mallocFailed;
   60590     if( db->pnBytesFreed ){
   60591       for(pEnd=&p[N]; p<pEnd; p++){
   60592         sqlite3DbFree(db, p->zMalloc);
   60593       }
   60594       return;
   60595     }
   60596     for(pEnd=&p[N]; p<pEnd; p++){
   60597       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   60598 
   60599       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   60600       ** that takes advantage of the fact that the memory cell value is
   60601       ** being set to NULL after releasing any dynamic resources.
   60602       **
   60603       ** The justification for duplicating code is that according to
   60604       ** callgrind, this causes a certain test case to hit the CPU 4.7
   60605       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   60606       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   60607       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   60608       ** with no indexes using a single prepared INSERT statement, bind()
   60609       ** and reset(). Inserts are grouped into a transaction.
   60610       */
   60611       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   60612         sqlite3VdbeMemRelease(p);
   60613       }else if( p->zMalloc ){
   60614         sqlite3DbFree(db, p->zMalloc);
   60615         p->zMalloc = 0;
   60616       }
   60617 
   60618       p->flags = MEM_Invalid;
   60619     }
   60620     db->mallocFailed = malloc_failed;
   60621   }
   60622 }
   60623 
   60624 /*
   60625 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   60626 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   60627 */
   60628 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   60629   int i;
   60630   Mem *aMem = VdbeFrameMem(p);
   60631   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   60632   for(i=0; i<p->nChildCsr; i++){
   60633     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   60634   }
   60635   releaseMemArray(aMem, p->nChildMem);
   60636   sqlite3DbFree(p->v->db, p);
   60637 }
   60638 
   60639 #ifndef SQLITE_OMIT_EXPLAIN
   60640 /*
   60641 ** Give a listing of the program in the virtual machine.
   60642 **
   60643 ** The interface is the same as sqlite3VdbeExec().  But instead of
   60644 ** running the code, it invokes the callback once for each instruction.
   60645 ** This feature is used to implement "EXPLAIN".
   60646 **
   60647 ** When p->explain==1, each instruction is listed.  When
   60648 ** p->explain==2, only OP_Explain instructions are listed and these
   60649 ** are shown in a different format.  p->explain==2 is used to implement
   60650 ** EXPLAIN QUERY PLAN.
   60651 **
   60652 ** When p->explain==1, first the main program is listed, then each of
   60653 ** the trigger subprograms are listed one by one.
   60654 */
   60655 SQLITE_PRIVATE int sqlite3VdbeList(
   60656   Vdbe *p                   /* The VDBE */
   60657 ){
   60658   int nRow;                            /* Stop when row count reaches this */
   60659   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   60660   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   60661   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   60662   sqlite3 *db = p->db;                 /* The database connection */
   60663   int i;                               /* Loop counter */
   60664   int rc = SQLITE_OK;                  /* Return code */
   60665   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
   60666 
   60667   assert( p->explain );
   60668   assert( p->magic==VDBE_MAGIC_RUN );
   60669   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   60670 
   60671   /* Even though this opcode does not use dynamic strings for
   60672   ** the result, result columns may become dynamic if the user calls
   60673   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   60674   */
   60675   releaseMemArray(pMem, 8);
   60676   p->pResultSet = 0;
   60677 
   60678   if( p->rc==SQLITE_NOMEM ){
   60679     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   60680     ** sqlite3_column_text16() failed.  */
   60681     db->mallocFailed = 1;
   60682     return SQLITE_ERROR;
   60683   }
   60684 
   60685   /* When the number of output rows reaches nRow, that means the
   60686   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   60687   ** nRow is the sum of the number of rows in the main program, plus
   60688   ** the sum of the number of rows in all trigger subprograms encountered
   60689   ** so far.  The nRow value will increase as new trigger subprograms are
   60690   ** encountered, but p->pc will eventually catch up to nRow.
   60691   */
   60692   nRow = p->nOp;
   60693   if( p->explain==1 ){
   60694     /* The first 8 memory cells are used for the result set.  So we will
   60695     ** commandeer the 9th cell to use as storage for an array of pointers
   60696     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   60697     ** cells.  */
   60698     assert( p->nMem>9 );
   60699     pSub = &p->aMem[9];
   60700     if( pSub->flags&MEM_Blob ){
   60701       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   60702       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   60703       nSub = pSub->n/sizeof(Vdbe*);
   60704       apSub = (SubProgram **)pSub->z;
   60705     }
   60706     for(i=0; i<nSub; i++){
   60707       nRow += apSub[i]->nOp;
   60708     }
   60709   }
   60710 
   60711   do{
   60712     i = p->pc++;
   60713   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   60714   if( i>=nRow ){
   60715     p->rc = SQLITE_OK;
   60716     rc = SQLITE_DONE;
   60717   }else if( db->u1.isInterrupted ){
   60718     p->rc = SQLITE_INTERRUPT;
   60719     rc = SQLITE_ERROR;
   60720     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   60721   }else{
   60722     char *z;
   60723     Op *pOp;
   60724     if( i<p->nOp ){
   60725       /* The output line number is small enough that we are still in the
   60726       ** main program. */
   60727       pOp = &p->aOp[i];
   60728     }else{
   60729       /* We are currently listing subprograms.  Figure out which one and
   60730       ** pick up the appropriate opcode. */
   60731       int j;
   60732       i -= p->nOp;
   60733       for(j=0; i>=apSub[j]->nOp; j++){
   60734         i -= apSub[j]->nOp;
   60735       }
   60736       pOp = &apSub[j]->aOp[i];
   60737     }
   60738     if( p->explain==1 ){
   60739       pMem->flags = MEM_Int;
   60740       pMem->type = SQLITE_INTEGER;
   60741       pMem->u.i = i;                                /* Program counter */
   60742       pMem++;
   60743 
   60744       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   60745       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   60746       assert( pMem->z!=0 );
   60747       pMem->n = sqlite3Strlen30(pMem->z);
   60748       pMem->type = SQLITE_TEXT;
   60749       pMem->enc = SQLITE_UTF8;
   60750       pMem++;
   60751 
   60752       /* When an OP_Program opcode is encounter (the only opcode that has
   60753       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   60754       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   60755       ** has not already been seen.
   60756       */
   60757       if( pOp->p4type==P4_SUBPROGRAM ){
   60758         int nByte = (nSub+1)*sizeof(SubProgram*);
   60759         int j;
   60760         for(j=0; j<nSub; j++){
   60761           if( apSub[j]==pOp->p4.pProgram ) break;
   60762         }
   60763         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
   60764           apSub = (SubProgram **)pSub->z;
   60765           apSub[nSub++] = pOp->p4.pProgram;
   60766           pSub->flags |= MEM_Blob;
   60767           pSub->n = nSub*sizeof(SubProgram*);
   60768         }
   60769       }
   60770     }
   60771 
   60772     pMem->flags = MEM_Int;
   60773     pMem->u.i = pOp->p1;                          /* P1 */
   60774     pMem->type = SQLITE_INTEGER;
   60775     pMem++;
   60776 
   60777     pMem->flags = MEM_Int;
   60778     pMem->u.i = pOp->p2;                          /* P2 */
   60779     pMem->type = SQLITE_INTEGER;
   60780     pMem++;
   60781 
   60782     pMem->flags = MEM_Int;
   60783     pMem->u.i = pOp->p3;                          /* P3 */
   60784     pMem->type = SQLITE_INTEGER;
   60785     pMem++;
   60786 
   60787     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   60788       assert( p->db->mallocFailed );
   60789       return SQLITE_ERROR;
   60790     }
   60791     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   60792     z = displayP4(pOp, pMem->z, 32);
   60793     if( z!=pMem->z ){
   60794       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
   60795     }else{
   60796       assert( pMem->z!=0 );
   60797       pMem->n = sqlite3Strlen30(pMem->z);
   60798       pMem->enc = SQLITE_UTF8;
   60799     }
   60800     pMem->type = SQLITE_TEXT;
   60801     pMem++;
   60802 
   60803     if( p->explain==1 ){
   60804       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   60805         assert( p->db->mallocFailed );
   60806         return SQLITE_ERROR;
   60807       }
   60808       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   60809       pMem->n = 2;
   60810       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   60811       pMem->type = SQLITE_TEXT;
   60812       pMem->enc = SQLITE_UTF8;
   60813       pMem++;
   60814 
   60815 #ifdef SQLITE_DEBUG
   60816       if( pOp->zComment ){
   60817         pMem->flags = MEM_Str|MEM_Term;
   60818         pMem->z = pOp->zComment;
   60819         pMem->n = sqlite3Strlen30(pMem->z);
   60820         pMem->enc = SQLITE_UTF8;
   60821         pMem->type = SQLITE_TEXT;
   60822       }else
   60823 #endif
   60824       {
   60825         pMem->flags = MEM_Null;                       /* Comment */
   60826         pMem->type = SQLITE_NULL;
   60827       }
   60828     }
   60829 
   60830     p->nResColumn = 8 - 4*(p->explain-1);
   60831     p->pResultSet = &p->aMem[1];
   60832     p->rc = SQLITE_OK;
   60833     rc = SQLITE_ROW;
   60834   }
   60835   return rc;
   60836 }
   60837 #endif /* SQLITE_OMIT_EXPLAIN */
   60838 
   60839 #ifdef SQLITE_DEBUG
   60840 /*
   60841 ** Print the SQL that was used to generate a VDBE program.
   60842 */
   60843 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   60844   int nOp = p->nOp;
   60845   VdbeOp *pOp;
   60846   if( nOp<1 ) return;
   60847   pOp = &p->aOp[0];
   60848   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   60849     const char *z = pOp->p4.z;
   60850     while( sqlite3Isspace(*z) ) z++;
   60851     printf("SQL: [%s]\n", z);
   60852   }
   60853 }
   60854 #endif
   60855 
   60856 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   60857 /*
   60858 ** Print an IOTRACE message showing SQL content.
   60859 */
   60860 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   60861   int nOp = p->nOp;
   60862   VdbeOp *pOp;
   60863   if( sqlite3IoTrace==0 ) return;
   60864   if( nOp<1 ) return;
   60865   pOp = &p->aOp[0];
   60866   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   60867     int i, j;
   60868     char z[1000];
   60869     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   60870     for(i=0; sqlite3Isspace(z[i]); i++){}
   60871     for(j=0; z[i]; i++){
   60872       if( sqlite3Isspace(z[i]) ){
   60873         if( z[i-1]!=' ' ){
   60874           z[j++] = ' ';
   60875         }
   60876       }else{
   60877         z[j++] = z[i];
   60878       }
   60879     }
   60880     z[j] = 0;
   60881     sqlite3IoTrace("SQL %s\n", z);
   60882   }
   60883 }
   60884 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   60885 
   60886 /*
   60887 ** Allocate space from a fixed size buffer and return a pointer to
   60888 ** that space.  If insufficient space is available, return NULL.
   60889 **
   60890 ** The pBuf parameter is the initial value of a pointer which will
   60891 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   60892 ** NULL, it means that memory space has already been allocated and that
   60893 ** this routine should not allocate any new memory.  When pBuf is not
   60894 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   60895 ** is NULL.
   60896 **
   60897 ** nByte is the number of bytes of space needed.
   60898 **
   60899 ** *ppFrom points to available space and pEnd points to the end of the
   60900 ** available space.  When space is allocated, *ppFrom is advanced past
   60901 ** the end of the allocated space.
   60902 **
   60903 ** *pnByte is a counter of the number of bytes of space that have failed
   60904 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   60905 ** request, then increment *pnByte by the amount of the request.
   60906 */
   60907 static void *allocSpace(
   60908   void *pBuf,          /* Where return pointer will be stored */
   60909   int nByte,           /* Number of bytes to allocate */
   60910   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   60911   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   60912   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   60913 ){
   60914   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   60915   if( pBuf ) return pBuf;
   60916   nByte = ROUND8(nByte);
   60917   if( &(*ppFrom)[nByte] <= pEnd ){
   60918     pBuf = (void*)*ppFrom;
   60919     *ppFrom += nByte;
   60920   }else{
   60921     *pnByte += nByte;
   60922   }
   60923   return pBuf;
   60924 }
   60925 
   60926 /*
   60927 ** Rewind the VDBE back to the beginning in preparation for
   60928 ** running it.
   60929 */
   60930 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
   60931 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   60932   int i;
   60933 #endif
   60934   assert( p!=0 );
   60935   assert( p->magic==VDBE_MAGIC_INIT );
   60936 
   60937   /* There should be at least one opcode.
   60938   */
   60939   assert( p->nOp>0 );
   60940 
   60941   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   60942   p->magic = VDBE_MAGIC_RUN;
   60943 
   60944 #ifdef SQLITE_DEBUG
   60945   for(i=1; i<p->nMem; i++){
   60946     assert( p->aMem[i].db==p->db );
   60947   }
   60948 #endif
   60949   p->pc = -1;
   60950   p->rc = SQLITE_OK;
   60951   p->errorAction = OE_Abort;
   60952   p->magic = VDBE_MAGIC_RUN;
   60953   p->nChange = 0;
   60954   p->cacheCtr = 1;
   60955   p->minWriteFileFormat = 255;
   60956   p->iStatement = 0;
   60957   p->nFkConstraint = 0;
   60958 #ifdef VDBE_PROFILE
   60959   for(i=0; i<p->nOp; i++){
   60960     p->aOp[i].cnt = 0;
   60961     p->aOp[i].cycles = 0;
   60962   }
   60963 #endif
   60964 }
   60965 
   60966 /*
   60967 ** Prepare a virtual machine for execution for the first time after
   60968 ** creating the virtual machine.  This involves things such
   60969 ** as allocating stack space and initializing the program counter.
   60970 ** After the VDBE has be prepped, it can be executed by one or more
   60971 ** calls to sqlite3VdbeExec().
   60972 **
   60973 ** This function may be called exact once on a each virtual machine.
   60974 ** After this routine is called the VM has been "packaged" and is ready
   60975 ** to run.  After this routine is called, futher calls to
   60976 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
   60977 ** the Vdbe from the Parse object that helped generate it so that the
   60978 ** the Vdbe becomes an independent entity and the Parse object can be
   60979 ** destroyed.
   60980 **
   60981 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
   60982 ** to its initial state after it has been run.
   60983 */
   60984 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   60985   Vdbe *p,                       /* The VDBE */
   60986   Parse *pParse                  /* Parsing context */
   60987 ){
   60988   sqlite3 *db;                   /* The database connection */
   60989   int nVar;                      /* Number of parameters */
   60990   int nMem;                      /* Number of VM memory registers */
   60991   int nCursor;                   /* Number of cursors required */
   60992   int nArg;                      /* Number of arguments in subprograms */
   60993   int nOnce;                     /* Number of OP_Once instructions */
   60994   int n;                         /* Loop counter */
   60995   u8 *zCsr;                      /* Memory available for allocation */
   60996   u8 *zEnd;                      /* First byte past allocated memory */
   60997   int nByte;                     /* How much extra memory is needed */
   60998 
   60999   assert( p!=0 );
   61000   assert( p->nOp>0 );
   61001   assert( pParse!=0 );
   61002   assert( p->magic==VDBE_MAGIC_INIT );
   61003   db = p->db;
   61004   assert( db->mallocFailed==0 );
   61005   nVar = pParse->nVar;
   61006   nMem = pParse->nMem;
   61007   nCursor = pParse->nTab;
   61008   nArg = pParse->nMaxArg;
   61009   nOnce = pParse->nOnce;
   61010   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
   61011 
   61012   /* For each cursor required, also allocate a memory cell. Memory
   61013   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   61014   ** the vdbe program. Instead they are used to allocate space for
   61015   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   61016   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   61017   ** stores the blob of memory associated with cursor 1, etc.
   61018   **
   61019   ** See also: allocateCursor().
   61020   */
   61021   nMem += nCursor;
   61022 
   61023   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   61024   ** an array to marshal SQL function arguments in.
   61025   */
   61026   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
   61027   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
   61028 
   61029   resolveP2Values(p, &nArg);
   61030   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
   61031   if( pParse->explain && nMem<10 ){
   61032     nMem = 10;
   61033   }
   61034   memset(zCsr, 0, zEnd-zCsr);
   61035   zCsr += (zCsr - (u8*)0)&7;
   61036   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   61037   p->expired = 0;
   61038 
   61039   /* Memory for registers, parameters, cursor, etc, is allocated in two
   61040   ** passes.  On the first pass, we try to reuse unused space at the
   61041   ** end of the opcode array.  If we are unable to satisfy all memory
   61042   ** requirements by reusing the opcode array tail, then the second
   61043   ** pass will fill in the rest using a fresh allocation.
   61044   **
   61045   ** This two-pass approach that reuses as much memory as possible from
   61046   ** the leftover space at the end of the opcode array can significantly
   61047   ** reduce the amount of memory held by a prepared statement.
   61048   */
   61049   do {
   61050     nByte = 0;
   61051     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   61052     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   61053     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   61054     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   61055     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   61056                           &zCsr, zEnd, &nByte);
   61057     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
   61058     if( nByte ){
   61059       p->pFree = sqlite3DbMallocZero(db, nByte);
   61060     }
   61061     zCsr = p->pFree;
   61062     zEnd = &zCsr[nByte];
   61063   }while( nByte && !db->mallocFailed );
   61064 
   61065   p->nCursor = (u16)nCursor;
   61066   p->nOnceFlag = nOnce;
   61067   if( p->aVar ){
   61068     p->nVar = (ynVar)nVar;
   61069     for(n=0; n<nVar; n++){
   61070       p->aVar[n].flags = MEM_Null;
   61071       p->aVar[n].db = db;
   61072     }
   61073   }
   61074   if( p->azVar ){
   61075     p->nzVar = pParse->nzVar;
   61076     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
   61077     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
   61078   }
   61079   if( p->aMem ){
   61080     p->aMem--;                      /* aMem[] goes from 1..nMem */
   61081     p->nMem = nMem;                 /*       not from 0..nMem-1 */
   61082     for(n=1; n<=nMem; n++){
   61083       p->aMem[n].flags = MEM_Invalid;
   61084       p->aMem[n].db = db;
   61085     }
   61086   }
   61087   p->explain = pParse->explain;
   61088   sqlite3VdbeRewind(p);
   61089 }
   61090 
   61091 /*
   61092 ** Close a VDBE cursor and release all the resources that cursor
   61093 ** happens to hold.
   61094 */
   61095 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   61096   if( pCx==0 ){
   61097     return;
   61098   }
   61099   sqlite3VdbeSorterClose(p->db, pCx);
   61100   if( pCx->pBt ){
   61101     sqlite3BtreeClose(pCx->pBt);
   61102     /* The pCx->pCursor will be close automatically, if it exists, by
   61103     ** the call above. */
   61104   }else if( pCx->pCursor ){
   61105     sqlite3BtreeCloseCursor(pCx->pCursor);
   61106   }
   61107 #ifndef SQLITE_OMIT_VIRTUALTABLE
   61108   if( pCx->pVtabCursor ){
   61109     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   61110     const sqlite3_module *pModule = pCx->pModule;
   61111     p->inVtabMethod = 1;
   61112     pModule->xClose(pVtabCursor);
   61113     p->inVtabMethod = 0;
   61114   }
   61115 #endif
   61116 }
   61117 
   61118 /*
   61119 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   61120 ** is used, for example, when a trigger sub-program is halted to restore
   61121 ** control to the main program.
   61122 */
   61123 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   61124   Vdbe *v = pFrame->v;
   61125   v->aOnceFlag = pFrame->aOnceFlag;
   61126   v->nOnceFlag = pFrame->nOnceFlag;
   61127   v->aOp = pFrame->aOp;
   61128   v->nOp = pFrame->nOp;
   61129   v->aMem = pFrame->aMem;
   61130   v->nMem = pFrame->nMem;
   61131   v->apCsr = pFrame->apCsr;
   61132   v->nCursor = pFrame->nCursor;
   61133   v->db->lastRowid = pFrame->lastRowid;
   61134   v->nChange = pFrame->nChange;
   61135   return pFrame->pc;
   61136 }
   61137 
   61138 /*
   61139 ** Close all cursors.
   61140 **
   61141 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   61142 ** cell array. This is necessary as the memory cell array may contain
   61143 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   61144 ** open cursors.
   61145 */
   61146 static void closeAllCursors(Vdbe *p){
   61147   if( p->pFrame ){
   61148     VdbeFrame *pFrame;
   61149     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   61150     sqlite3VdbeFrameRestore(pFrame);
   61151   }
   61152   p->pFrame = 0;
   61153   p->nFrame = 0;
   61154 
   61155   if( p->apCsr ){
   61156     int i;
   61157     for(i=0; i<p->nCursor; i++){
   61158       VdbeCursor *pC = p->apCsr[i];
   61159       if( pC ){
   61160         sqlite3VdbeFreeCursor(p, pC);
   61161         p->apCsr[i] = 0;
   61162       }
   61163     }
   61164   }
   61165   if( p->aMem ){
   61166     releaseMemArray(&p->aMem[1], p->nMem);
   61167   }
   61168   while( p->pDelFrame ){
   61169     VdbeFrame *pDel = p->pDelFrame;
   61170     p->pDelFrame = pDel->pParent;
   61171     sqlite3VdbeFrameDelete(pDel);
   61172   }
   61173 }
   61174 
   61175 /*
   61176 ** Clean up the VM after execution.
   61177 **
   61178 ** This routine will automatically close any cursors, lists, and/or
   61179 ** sorters that were left open.  It also deletes the values of
   61180 ** variables in the aVar[] array.
   61181 */
   61182 static void Cleanup(Vdbe *p){
   61183   sqlite3 *db = p->db;
   61184 
   61185 #ifdef SQLITE_DEBUG
   61186   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   61187   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   61188   int i;
   61189   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   61190   if( p->aMem ){
   61191     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
   61192   }
   61193 #endif
   61194 
   61195   sqlite3DbFree(db, p->zErrMsg);
   61196   p->zErrMsg = 0;
   61197   p->pResultSet = 0;
   61198 }
   61199 
   61200 /*
   61201 ** Set the number of result columns that will be returned by this SQL
   61202 ** statement. This is now set at compile time, rather than during
   61203 ** execution of the vdbe program so that sqlite3_column_count() can
   61204 ** be called on an SQL statement before sqlite3_step().
   61205 */
   61206 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   61207   Mem *pColName;
   61208   int n;
   61209   sqlite3 *db = p->db;
   61210 
   61211   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   61212   sqlite3DbFree(db, p->aColName);
   61213   n = nResColumn*COLNAME_N;
   61214   p->nResColumn = (u16)nResColumn;
   61215   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   61216   if( p->aColName==0 ) return;
   61217   while( n-- > 0 ){
   61218     pColName->flags = MEM_Null;
   61219     pColName->db = p->db;
   61220     pColName++;
   61221   }
   61222 }
   61223 
   61224 /*
   61225 ** Set the name of the idx'th column to be returned by the SQL statement.
   61226 ** zName must be a pointer to a nul terminated string.
   61227 **
   61228 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   61229 **
   61230 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   61231 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   61232 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   61233 */
   61234 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   61235   Vdbe *p,                         /* Vdbe being configured */
   61236   int idx,                         /* Index of column zName applies to */
   61237   int var,                         /* One of the COLNAME_* constants */
   61238   const char *zName,               /* Pointer to buffer containing name */
   61239   void (*xDel)(void*)              /* Memory management strategy for zName */
   61240 ){
   61241   int rc;
   61242   Mem *pColName;
   61243   assert( idx<p->nResColumn );
   61244   assert( var<COLNAME_N );
   61245   if( p->db->mallocFailed ){
   61246     assert( !zName || xDel!=SQLITE_DYNAMIC );
   61247     return SQLITE_NOMEM;
   61248   }
   61249   assert( p->aColName!=0 );
   61250   pColName = &(p->aColName[idx+var*p->nResColumn]);
   61251   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   61252   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   61253   return rc;
   61254 }
   61255 
   61256 /*
   61257 ** A read or write transaction may or may not be active on database handle
   61258 ** db. If a transaction is active, commit it. If there is a
   61259 ** write-transaction spanning more than one database file, this routine
   61260 ** takes care of the master journal trickery.
   61261 */
   61262 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   61263   int i;
   61264   int nTrans = 0;  /* Number of databases with an active write-transaction */
   61265   int rc = SQLITE_OK;
   61266   int needXcommit = 0;
   61267 
   61268 #ifdef SQLITE_OMIT_VIRTUALTABLE
   61269   /* With this option, sqlite3VtabSync() is defined to be simply
   61270   ** SQLITE_OK so p is not used.
   61271   */
   61272   UNUSED_PARAMETER(p);
   61273 #endif
   61274 
   61275   /* Before doing anything else, call the xSync() callback for any
   61276   ** virtual module tables written in this transaction. This has to
   61277   ** be done before determining whether a master journal file is
   61278   ** required, as an xSync() callback may add an attached database
   61279   ** to the transaction.
   61280   */
   61281   rc = sqlite3VtabSync(db, &p->zErrMsg);
   61282 
   61283   /* This loop determines (a) if the commit hook should be invoked and
   61284   ** (b) how many database files have open write transactions, not
   61285   ** including the temp database. (b) is important because if more than
   61286   ** one database file has an open write transaction, a master journal
   61287   ** file is required for an atomic commit.
   61288   */
   61289   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61290     Btree *pBt = db->aDb[i].pBt;
   61291     if( sqlite3BtreeIsInTrans(pBt) ){
   61292       needXcommit = 1;
   61293       if( i!=1 ) nTrans++;
   61294       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
   61295     }
   61296   }
   61297   if( rc!=SQLITE_OK ){
   61298     return rc;
   61299   }
   61300 
   61301   /* If there are any write-transactions at all, invoke the commit hook */
   61302   if( needXcommit && db->xCommitCallback ){
   61303     rc = db->xCommitCallback(db->pCommitArg);
   61304     if( rc ){
   61305       return SQLITE_CONSTRAINT;
   61306     }
   61307   }
   61308 
   61309   /* The simple case - no more than one database file (not counting the
   61310   ** TEMP database) has a transaction active.   There is no need for the
   61311   ** master-journal.
   61312   **
   61313   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   61314   ** string, it means the main database is :memory: or a temp file.  In
   61315   ** that case we do not support atomic multi-file commits, so use the
   61316   ** simple case then too.
   61317   */
   61318   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   61319    || nTrans<=1
   61320   ){
   61321     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61322       Btree *pBt = db->aDb[i].pBt;
   61323       if( pBt ){
   61324         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   61325       }
   61326     }
   61327 
   61328     /* Do the commit only if all databases successfully complete phase 1.
   61329     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   61330     ** IO error while deleting or truncating a journal file. It is unlikely,
   61331     ** but could happen. In this case abandon processing and return the error.
   61332     */
   61333     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61334       Btree *pBt = db->aDb[i].pBt;
   61335       if( pBt ){
   61336         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
   61337       }
   61338     }
   61339     if( rc==SQLITE_OK ){
   61340       sqlite3VtabCommit(db);
   61341     }
   61342   }
   61343 
   61344   /* The complex case - There is a multi-file write-transaction active.
   61345   ** This requires a master journal file to ensure the transaction is
   61346   ** committed atomicly.
   61347   */
   61348 #ifndef SQLITE_OMIT_DISKIO
   61349   else{
   61350     sqlite3_vfs *pVfs = db->pVfs;
   61351     int needSync = 0;
   61352     char *zMaster = 0;   /* File-name for the master journal */
   61353     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   61354     sqlite3_file *pMaster = 0;
   61355     i64 offset = 0;
   61356     int res;
   61357     int retryCount = 0;
   61358     int nMainFile;
   61359 
   61360     /* Select a master journal file name */
   61361     nMainFile = sqlite3Strlen30(zMainFile);
   61362     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
   61363     if( zMaster==0 ) return SQLITE_NOMEM;
   61364     do {
   61365       u32 iRandom;
   61366       if( retryCount ){
   61367         if( retryCount>100 ){
   61368           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
   61369           sqlite3OsDelete(pVfs, zMaster, 0);
   61370           break;
   61371         }else if( retryCount==1 ){
   61372           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
   61373         }
   61374       }
   61375       retryCount++;
   61376       sqlite3_randomness(sizeof(iRandom), &iRandom);
   61377       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
   61378                                (iRandom>>8)&0xffffff, iRandom&0xff);
   61379       /* The antipenultimate character of the master journal name must
   61380       ** be "9" to avoid name collisions when using 8+3 filenames. */
   61381       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
   61382       sqlite3FileSuffix3(zMainFile, zMaster);
   61383       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   61384     }while( rc==SQLITE_OK && res );
   61385     if( rc==SQLITE_OK ){
   61386       /* Open the master journal. */
   61387       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   61388           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   61389           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   61390       );
   61391     }
   61392     if( rc!=SQLITE_OK ){
   61393       sqlite3DbFree(db, zMaster);
   61394       return rc;
   61395     }
   61396 
   61397     /* Write the name of each database file in the transaction into the new
   61398     ** master journal file. If an error occurs at this point close
   61399     ** and delete the master journal file. All the individual journal files
   61400     ** still have 'null' as the master journal pointer, so they will roll
   61401     ** back independently if a failure occurs.
   61402     */
   61403     for(i=0; i<db->nDb; i++){
   61404       Btree *pBt = db->aDb[i].pBt;
   61405       if( sqlite3BtreeIsInTrans(pBt) ){
   61406         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   61407         if( zFile==0 ){
   61408           continue;  /* Ignore TEMP and :memory: databases */
   61409         }
   61410         assert( zFile[0]!=0 );
   61411         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   61412           needSync = 1;
   61413         }
   61414         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   61415         offset += sqlite3Strlen30(zFile)+1;
   61416         if( rc!=SQLITE_OK ){
   61417           sqlite3OsCloseFree(pMaster);
   61418           sqlite3OsDelete(pVfs, zMaster, 0);
   61419           sqlite3DbFree(db, zMaster);
   61420           return rc;
   61421         }
   61422       }
   61423     }
   61424 
   61425     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   61426     ** flag is set this is not required.
   61427     */
   61428     if( needSync
   61429      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   61430      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   61431     ){
   61432       sqlite3OsCloseFree(pMaster);
   61433       sqlite3OsDelete(pVfs, zMaster, 0);
   61434       sqlite3DbFree(db, zMaster);
   61435       return rc;
   61436     }
   61437 
   61438     /* Sync all the db files involved in the transaction. The same call
   61439     ** sets the master journal pointer in each individual journal. If
   61440     ** an error occurs here, do not delete the master journal file.
   61441     **
   61442     ** If the error occurs during the first call to
   61443     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   61444     ** master journal file will be orphaned. But we cannot delete it,
   61445     ** in case the master journal file name was written into the journal
   61446     ** file before the failure occurred.
   61447     */
   61448     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   61449       Btree *pBt = db->aDb[i].pBt;
   61450       if( pBt ){
   61451         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   61452       }
   61453     }
   61454     sqlite3OsCloseFree(pMaster);
   61455     assert( rc!=SQLITE_BUSY );
   61456     if( rc!=SQLITE_OK ){
   61457       sqlite3DbFree(db, zMaster);
   61458       return rc;
   61459     }
   61460 
   61461     /* Delete the master journal file. This commits the transaction. After
   61462     ** doing this the directory is synced again before any individual
   61463     ** transaction files are deleted.
   61464     */
   61465     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   61466     sqlite3DbFree(db, zMaster);
   61467     zMaster = 0;
   61468     if( rc ){
   61469       return rc;
   61470     }
   61471 
   61472     /* All files and directories have already been synced, so the following
   61473     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   61474     ** deleting or truncating journals. If something goes wrong while
   61475     ** this is happening we don't really care. The integrity of the
   61476     ** transaction is already guaranteed, but some stray 'cold' journals
   61477     ** may be lying around. Returning an error code won't help matters.
   61478     */
   61479     disable_simulated_io_errors();
   61480     sqlite3BeginBenignMalloc();
   61481     for(i=0; i<db->nDb; i++){
   61482       Btree *pBt = db->aDb[i].pBt;
   61483       if( pBt ){
   61484         sqlite3BtreeCommitPhaseTwo(pBt, 1);
   61485       }
   61486     }
   61487     sqlite3EndBenignMalloc();
   61488     enable_simulated_io_errors();
   61489 
   61490     sqlite3VtabCommit(db);
   61491   }
   61492 #endif
   61493 
   61494   return rc;
   61495 }
   61496 
   61497 /*
   61498 ** This routine checks that the sqlite3.activeVdbeCnt count variable
   61499 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   61500 ** currently active. An assertion fails if the two counts do not match.
   61501 ** This is an internal self-check only - it is not an essential processing
   61502 ** step.
   61503 **
   61504 ** This is a no-op if NDEBUG is defined.
   61505 */
   61506 #ifndef NDEBUG
   61507 static void checkActiveVdbeCnt(sqlite3 *db){
   61508   Vdbe *p;
   61509   int cnt = 0;
   61510   int nWrite = 0;
   61511   p = db->pVdbe;
   61512   while( p ){
   61513     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
   61514       cnt++;
   61515       if( p->readOnly==0 ) nWrite++;
   61516     }
   61517     p = p->pNext;
   61518   }
   61519   assert( cnt==db->activeVdbeCnt );
   61520   assert( nWrite==db->writeVdbeCnt );
   61521 }
   61522 #else
   61523 #define checkActiveVdbeCnt(x)
   61524 #endif
   61525 
   61526 /*
   61527 ** If the Vdbe passed as the first argument opened a statement-transaction,
   61528 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   61529 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   61530 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   61531 ** statement transaction is commtted.
   61532 **
   61533 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   61534 ** Otherwise SQLITE_OK.
   61535 */
   61536 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   61537   sqlite3 *const db = p->db;
   61538   int rc = SQLITE_OK;
   61539 
   61540   /* If p->iStatement is greater than zero, then this Vdbe opened a
   61541   ** statement transaction that should be closed here. The only exception
   61542   ** is that an IO error may have occured, causing an emergency rollback.
   61543   ** In this case (db->nStatement==0), and there is nothing to do.
   61544   */
   61545   if( db->nStatement && p->iStatement ){
   61546     int i;
   61547     const int iSavepoint = p->iStatement-1;
   61548 
   61549     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   61550     assert( db->nStatement>0 );
   61551     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   61552 
   61553     for(i=0; i<db->nDb; i++){
   61554       int rc2 = SQLITE_OK;
   61555       Btree *pBt = db->aDb[i].pBt;
   61556       if( pBt ){
   61557         if( eOp==SAVEPOINT_ROLLBACK ){
   61558           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   61559         }
   61560         if( rc2==SQLITE_OK ){
   61561           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   61562         }
   61563         if( rc==SQLITE_OK ){
   61564           rc = rc2;
   61565         }
   61566       }
   61567     }
   61568     db->nStatement--;
   61569     p->iStatement = 0;
   61570 
   61571     if( rc==SQLITE_OK ){
   61572       if( eOp==SAVEPOINT_ROLLBACK ){
   61573         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
   61574       }
   61575       if( rc==SQLITE_OK ){
   61576         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
   61577       }
   61578     }
   61579 
   61580     /* If the statement transaction is being rolled back, also restore the
   61581     ** database handles deferred constraint counter to the value it had when
   61582     ** the statement transaction was opened.  */
   61583     if( eOp==SAVEPOINT_ROLLBACK ){
   61584       db->nDeferredCons = p->nStmtDefCons;
   61585     }
   61586   }
   61587   return rc;
   61588 }
   61589 
   61590 /*
   61591 ** This function is called when a transaction opened by the database
   61592 ** handle associated with the VM passed as an argument is about to be
   61593 ** committed. If there are outstanding deferred foreign key constraint
   61594 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   61595 **
   61596 ** If there are outstanding FK violations and this function returns
   61597 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
   61598 ** an error message to it. Then return SQLITE_ERROR.
   61599 */
   61600 #ifndef SQLITE_OMIT_FOREIGN_KEY
   61601 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   61602   sqlite3 *db = p->db;
   61603   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
   61604     p->rc = SQLITE_CONSTRAINT;
   61605     p->errorAction = OE_Abort;
   61606     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
   61607     return SQLITE_ERROR;
   61608   }
   61609   return SQLITE_OK;
   61610 }
   61611 #endif
   61612 
   61613 /*
   61614 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   61615 ** has made changes and is in autocommit mode, then commit those
   61616 ** changes.  If a rollback is needed, then do the rollback.
   61617 **
   61618 ** This routine is the only way to move the state of a VM from
   61619 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   61620 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   61621 **
   61622 ** Return an error code.  If the commit could not complete because of
   61623 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   61624 ** means the close did not happen and needs to be repeated.
   61625 */
   61626 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   61627   int rc;                         /* Used to store transient return codes */
   61628   sqlite3 *db = p->db;
   61629 
   61630   /* This function contains the logic that determines if a statement or
   61631   ** transaction will be committed or rolled back as a result of the
   61632   ** execution of this virtual machine.
   61633   **
   61634   ** If any of the following errors occur:
   61635   **
   61636   **     SQLITE_NOMEM
   61637   **     SQLITE_IOERR
   61638   **     SQLITE_FULL
   61639   **     SQLITE_INTERRUPT
   61640   **
   61641   ** Then the internal cache might have been left in an inconsistent
   61642   ** state.  We need to rollback the statement transaction, if there is
   61643   ** one, or the complete transaction if there is no statement transaction.
   61644   */
   61645 
   61646   if( p->db->mallocFailed ){
   61647     p->rc = SQLITE_NOMEM;
   61648   }
   61649   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
   61650   closeAllCursors(p);
   61651   if( p->magic!=VDBE_MAGIC_RUN ){
   61652     return SQLITE_OK;
   61653   }
   61654   checkActiveVdbeCnt(db);
   61655 
   61656   /* No commit or rollback needed if the program never started */
   61657   if( p->pc>=0 ){
   61658     int mrc;   /* Primary error code from p->rc */
   61659     int eStatementOp = 0;
   61660     int isSpecialError;            /* Set to true if a 'special' error */
   61661 
   61662     /* Lock all btrees used by the statement */
   61663     sqlite3VdbeEnter(p);
   61664 
   61665     /* Check for one of the special errors */
   61666     mrc = p->rc & 0xff;
   61667     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
   61668     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   61669                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   61670     if( isSpecialError ){
   61671       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   61672       ** no rollback is necessary. Otherwise, at least a savepoint
   61673       ** transaction must be rolled back to restore the database to a
   61674       ** consistent state.
   61675       **
   61676       ** Even if the statement is read-only, it is important to perform
   61677       ** a statement or transaction rollback operation. If the error
   61678       ** occured while writing to the journal, sub-journal or database
   61679       ** file as part of an effort to free up cache space (see function
   61680       ** pagerStress() in pager.c), the rollback is required to restore
   61681       ** the pager to a consistent state.
   61682       */
   61683       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   61684         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   61685           eStatementOp = SAVEPOINT_ROLLBACK;
   61686         }else{
   61687           /* We are forced to roll back the active transaction. Before doing
   61688           ** so, abort any other statements this handle currently has active.
   61689           */
   61690           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61691           sqlite3CloseSavepoints(db);
   61692           db->autoCommit = 1;
   61693         }
   61694       }
   61695     }
   61696 
   61697     /* Check for immediate foreign key violations. */
   61698     if( p->rc==SQLITE_OK ){
   61699       sqlite3VdbeCheckFk(p, 0);
   61700     }
   61701 
   61702     /* If the auto-commit flag is set and this is the only active writer
   61703     ** VM, then we do either a commit or rollback of the current transaction.
   61704     **
   61705     ** Note: This block also runs if one of the special errors handled
   61706     ** above has occurred.
   61707     */
   61708     if( !sqlite3VtabInSync(db)
   61709      && db->autoCommit
   61710      && db->writeVdbeCnt==(p->readOnly==0)
   61711     ){
   61712       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   61713         rc = sqlite3VdbeCheckFk(p, 1);
   61714         if( rc!=SQLITE_OK ){
   61715           if( NEVER(p->readOnly) ){
   61716             sqlite3VdbeLeave(p);
   61717             return SQLITE_ERROR;
   61718           }
   61719           rc = SQLITE_CONSTRAINT;
   61720         }else{
   61721           /* The auto-commit flag is true, the vdbe program was successful
   61722           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   61723           ** key constraints to hold up the transaction. This means a commit
   61724           ** is required. */
   61725           rc = vdbeCommit(db, p);
   61726         }
   61727         if( rc==SQLITE_BUSY && p->readOnly ){
   61728           sqlite3VdbeLeave(p);
   61729           return SQLITE_BUSY;
   61730         }else if( rc!=SQLITE_OK ){
   61731           p->rc = rc;
   61732           sqlite3RollbackAll(db, SQLITE_OK);
   61733         }else{
   61734           db->nDeferredCons = 0;
   61735           sqlite3CommitInternalChanges(db);
   61736         }
   61737       }else{
   61738         sqlite3RollbackAll(db, SQLITE_OK);
   61739       }
   61740       db->nStatement = 0;
   61741     }else if( eStatementOp==0 ){
   61742       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   61743         eStatementOp = SAVEPOINT_RELEASE;
   61744       }else if( p->errorAction==OE_Abort ){
   61745         eStatementOp = SAVEPOINT_ROLLBACK;
   61746       }else{
   61747         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61748         sqlite3CloseSavepoints(db);
   61749         db->autoCommit = 1;
   61750       }
   61751     }
   61752 
   61753     /* If eStatementOp is non-zero, then a statement transaction needs to
   61754     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   61755     ** do so. If this operation returns an error, and the current statement
   61756     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   61757     ** current statement error code.
   61758     */
   61759     if( eStatementOp ){
   61760       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   61761       if( rc ){
   61762         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
   61763           p->rc = rc;
   61764           sqlite3DbFree(db, p->zErrMsg);
   61765           p->zErrMsg = 0;
   61766         }
   61767         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   61768         sqlite3CloseSavepoints(db);
   61769         db->autoCommit = 1;
   61770       }
   61771     }
   61772 
   61773     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   61774     ** has been rolled back, update the database connection change-counter.
   61775     */
   61776     if( p->changeCntOn ){
   61777       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   61778         sqlite3VdbeSetChanges(db, p->nChange);
   61779       }else{
   61780         sqlite3VdbeSetChanges(db, 0);
   61781       }
   61782       p->nChange = 0;
   61783     }
   61784 
   61785     /* Release the locks */
   61786     sqlite3VdbeLeave(p);
   61787   }
   61788 
   61789   /* We have successfully halted and closed the VM.  Record this fact. */
   61790   if( p->pc>=0 ){
   61791     db->activeVdbeCnt--;
   61792     if( !p->readOnly ){
   61793       db->writeVdbeCnt--;
   61794     }
   61795     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
   61796   }
   61797   p->magic = VDBE_MAGIC_HALT;
   61798   checkActiveVdbeCnt(db);
   61799   if( p->db->mallocFailed ){
   61800     p->rc = SQLITE_NOMEM;
   61801   }
   61802 
   61803   /* If the auto-commit flag is set to true, then any locks that were held
   61804   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   61805   ** to invoke any required unlock-notify callbacks.
   61806   */
   61807   if( db->autoCommit ){
   61808     sqlite3ConnectionUnlocked(db);
   61809   }
   61810 
   61811   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
   61812   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
   61813 }
   61814 
   61815 
   61816 /*
   61817 ** Each VDBE holds the result of the most recent sqlite3_step() call
   61818 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   61819 */
   61820 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   61821   p->rc = SQLITE_OK;
   61822 }
   61823 
   61824 /*
   61825 ** Copy the error code and error message belonging to the VDBE passed
   61826 ** as the first argument to its database handle (so that they will be
   61827 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
   61828 **
   61829 ** This function does not clear the VDBE error code or message, just
   61830 ** copies them to the database handle.
   61831 */
   61832 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
   61833   sqlite3 *db = p->db;
   61834   int rc = p->rc;
   61835   if( p->zErrMsg ){
   61836     u8 mallocFailed = db->mallocFailed;
   61837     sqlite3BeginBenignMalloc();
   61838     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   61839     sqlite3EndBenignMalloc();
   61840     db->mallocFailed = mallocFailed;
   61841     db->errCode = rc;
   61842   }else{
   61843     sqlite3Error(db, rc, 0);
   61844   }
   61845   return rc;
   61846 }
   61847 
   61848 /*
   61849 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   61850 ** Write any error messages into *pzErrMsg.  Return the result code.
   61851 **
   61852 ** After this routine is run, the VDBE should be ready to be executed
   61853 ** again.
   61854 **
   61855 ** To look at it another way, this routine resets the state of the
   61856 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   61857 ** VDBE_MAGIC_INIT.
   61858 */
   61859 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   61860   sqlite3 *db;
   61861   db = p->db;
   61862 
   61863   /* If the VM did not run to completion or if it encountered an
   61864   ** error, then it might not have been halted properly.  So halt
   61865   ** it now.
   61866   */
   61867   sqlite3VdbeHalt(p);
   61868 
   61869   /* If the VDBE has be run even partially, then transfer the error code
   61870   ** and error message from the VDBE into the main database structure.  But
   61871   ** if the VDBE has just been set to run but has not actually executed any
   61872   ** instructions yet, leave the main database error information unchanged.
   61873   */
   61874   if( p->pc>=0 ){
   61875     sqlite3VdbeTransferError(p);
   61876     sqlite3DbFree(db, p->zErrMsg);
   61877     p->zErrMsg = 0;
   61878     if( p->runOnlyOnce ) p->expired = 1;
   61879   }else if( p->rc && p->expired ){
   61880     /* The expired flag was set on the VDBE before the first call
   61881     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   61882     ** called), set the database error in this case as well.
   61883     */
   61884     sqlite3Error(db, p->rc, 0);
   61885     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   61886     sqlite3DbFree(db, p->zErrMsg);
   61887     p->zErrMsg = 0;
   61888   }
   61889 
   61890   /* Reclaim all memory used by the VDBE
   61891   */
   61892   Cleanup(p);
   61893 
   61894   /* Save profiling information from this VDBE run.
   61895   */
   61896 #ifdef VDBE_PROFILE
   61897   {
   61898     FILE *out = fopen("vdbe_profile.out", "a");
   61899     if( out ){
   61900       int i;
   61901       fprintf(out, "---- ");
   61902       for(i=0; i<p->nOp; i++){
   61903         fprintf(out, "%02x", p->aOp[i].opcode);
   61904       }
   61905       fprintf(out, "\n");
   61906       for(i=0; i<p->nOp; i++){
   61907         fprintf(out, "%6d %10lld %8lld ",
   61908            p->aOp[i].cnt,
   61909            p->aOp[i].cycles,
   61910            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   61911         );
   61912         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   61913       }
   61914       fclose(out);
   61915     }
   61916   }
   61917 #endif
   61918   p->magic = VDBE_MAGIC_INIT;
   61919   return p->rc & db->errMask;
   61920 }
   61921 
   61922 /*
   61923 ** Clean up and delete a VDBE after execution.  Return an integer which is
   61924 ** the result code.  Write any error message text into *pzErrMsg.
   61925 */
   61926 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   61927   int rc = SQLITE_OK;
   61928   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   61929     rc = sqlite3VdbeReset(p);
   61930     assert( (rc & p->db->errMask)==rc );
   61931   }
   61932   sqlite3VdbeDelete(p);
   61933   return rc;
   61934 }
   61935 
   61936 /*
   61937 ** Call the destructor for each auxdata entry in pVdbeFunc for which
   61938 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
   61939 ** are always destroyed.  To destroy all auxdata entries, call this
   61940 ** routine with mask==0.
   61941 */
   61942 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
   61943   int i;
   61944   for(i=0; i<pVdbeFunc->nAux; i++){
   61945     struct AuxData *pAux = &pVdbeFunc->apAux[i];
   61946     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
   61947       if( pAux->xDelete ){
   61948         pAux->xDelete(pAux->pAux);
   61949       }
   61950       pAux->pAux = 0;
   61951     }
   61952   }
   61953 }
   61954 
   61955 /*
   61956 ** Free all memory associated with the Vdbe passed as the second argument.
   61957 ** The difference between this function and sqlite3VdbeDelete() is that
   61958 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   61959 ** the database connection.
   61960 */
   61961 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
   61962   SubProgram *pSub, *pNext;
   61963   int i;
   61964   assert( p->db==0 || p->db==db );
   61965   releaseMemArray(p->aVar, p->nVar);
   61966   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   61967   for(pSub=p->pProgram; pSub; pSub=pNext){
   61968     pNext = pSub->pNext;
   61969     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   61970     sqlite3DbFree(db, pSub);
   61971   }
   61972   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
   61973   vdbeFreeOpArray(db, p->aOp, p->nOp);
   61974   sqlite3DbFree(db, p->aLabel);
   61975   sqlite3DbFree(db, p->aColName);
   61976   sqlite3DbFree(db, p->zSql);
   61977   sqlite3DbFree(db, p->pFree);
   61978 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   61979   sqlite3DbFree(db, p->zExplain);
   61980   sqlite3DbFree(db, p->pExplain);
   61981 #endif
   61982   sqlite3DbFree(db, p);
   61983 }
   61984 
   61985 /*
   61986 ** Delete an entire VDBE.
   61987 */
   61988 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   61989   sqlite3 *db;
   61990 
   61991   if( NEVER(p==0) ) return;
   61992   db = p->db;
   61993   if( p->pPrev ){
   61994     p->pPrev->pNext = p->pNext;
   61995   }else{
   61996     assert( db->pVdbe==p );
   61997     db->pVdbe = p->pNext;
   61998   }
   61999   if( p->pNext ){
   62000     p->pNext->pPrev = p->pPrev;
   62001   }
   62002   p->magic = VDBE_MAGIC_DEAD;
   62003   p->db = 0;
   62004   sqlite3VdbeDeleteObject(db, p);
   62005 }
   62006 
   62007 /*
   62008 ** Make sure the cursor p is ready to read or write the row to which it
   62009 ** was last positioned.  Return an error code if an OOM fault or I/O error
   62010 ** prevents us from positioning the cursor to its correct position.
   62011 **
   62012 ** If a MoveTo operation is pending on the given cursor, then do that
   62013 ** MoveTo now.  If no move is pending, check to see if the row has been
   62014 ** deleted out from under the cursor and if it has, mark the row as
   62015 ** a NULL row.
   62016 **
   62017 ** If the cursor is already pointing to the correct row and that row has
   62018 ** not been deleted out from under the cursor, then this routine is a no-op.
   62019 */
   62020 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   62021   if( p->deferredMoveto ){
   62022     int res, rc;
   62023 #ifdef SQLITE_TEST
   62024     extern int sqlite3_search_count;
   62025 #endif
   62026     assert( p->isTable );
   62027     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   62028     if( rc ) return rc;
   62029     p->lastRowid = p->movetoTarget;
   62030     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   62031     p->rowidIsValid = 1;
   62032 #ifdef SQLITE_TEST
   62033     sqlite3_search_count++;
   62034 #endif
   62035     p->deferredMoveto = 0;
   62036     p->cacheStatus = CACHE_STALE;
   62037   }else if( ALWAYS(p->pCursor) ){
   62038     int hasMoved;
   62039     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   62040     if( rc ) return rc;
   62041     if( hasMoved ){
   62042       p->cacheStatus = CACHE_STALE;
   62043       p->nullRow = 1;
   62044     }
   62045   }
   62046   return SQLITE_OK;
   62047 }
   62048 
   62049 /*
   62050 ** The following functions:
   62051 **
   62052 ** sqlite3VdbeSerialType()
   62053 ** sqlite3VdbeSerialTypeLen()
   62054 ** sqlite3VdbeSerialLen()
   62055 ** sqlite3VdbeSerialPut()
   62056 ** sqlite3VdbeSerialGet()
   62057 **
   62058 ** encapsulate the code that serializes values for storage in SQLite
   62059 ** data and index records. Each serialized value consists of a
   62060 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   62061 ** integer, stored as a varint.
   62062 **
   62063 ** In an SQLite index record, the serial type is stored directly before
   62064 ** the blob of data that it corresponds to. In a table record, all serial
   62065 ** types are stored at the start of the record, and the blobs of data at
   62066 ** the end. Hence these functions allow the caller to handle the
   62067 ** serial-type and data blob seperately.
   62068 **
   62069 ** The following table describes the various storage classes for data:
   62070 **
   62071 **   serial type        bytes of data      type
   62072 **   --------------     ---------------    ---------------
   62073 **      0                     0            NULL
   62074 **      1                     1            signed integer
   62075 **      2                     2            signed integer
   62076 **      3                     3            signed integer
   62077 **      4                     4            signed integer
   62078 **      5                     6            signed integer
   62079 **      6                     8            signed integer
   62080 **      7                     8            IEEE float
   62081 **      8                     0            Integer constant 0
   62082 **      9                     0            Integer constant 1
   62083 **     10,11                               reserved for expansion
   62084 **    N>=12 and even       (N-12)/2        BLOB
   62085 **    N>=13 and odd        (N-13)/2        text
   62086 **
   62087 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   62088 ** of SQLite will not understand those serial types.
   62089 */
   62090 
   62091 /*
   62092 ** Return the serial-type for the value stored in pMem.
   62093 */
   62094 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   62095   int flags = pMem->flags;
   62096   int n;
   62097 
   62098   if( flags&MEM_Null ){
   62099     return 0;
   62100   }
   62101   if( flags&MEM_Int ){
   62102     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   62103 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   62104     i64 i = pMem->u.i;
   62105     u64 u;
   62106     if( file_format>=4 && (i&1)==i ){
   62107       return 8+(u32)i;
   62108     }
   62109     if( i<0 ){
   62110       if( i<(-MAX_6BYTE) ) return 6;
   62111       /* Previous test prevents:  u = -(-9223372036854775808) */
   62112       u = -i;
   62113     }else{
   62114       u = i;
   62115     }
   62116     if( u<=127 ) return 1;
   62117     if( u<=32767 ) return 2;
   62118     if( u<=8388607 ) return 3;
   62119     if( u<=2147483647 ) return 4;
   62120     if( u<=MAX_6BYTE ) return 5;
   62121     return 6;
   62122   }
   62123   if( flags&MEM_Real ){
   62124     return 7;
   62125   }
   62126   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   62127   n = pMem->n;
   62128   if( flags & MEM_Zero ){
   62129     n += pMem->u.nZero;
   62130   }
   62131   assert( n>=0 );
   62132   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   62133 }
   62134 
   62135 /*
   62136 ** Return the length of the data corresponding to the supplied serial-type.
   62137 */
   62138 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   62139   if( serial_type>=12 ){
   62140     return (serial_type-12)/2;
   62141   }else{
   62142     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   62143     return aSize[serial_type];
   62144   }
   62145 }
   62146 
   62147 /*
   62148 ** If we are on an architecture with mixed-endian floating
   62149 ** points (ex: ARM7) then swap the lower 4 bytes with the
   62150 ** upper 4 bytes.  Return the result.
   62151 **
   62152 ** For most architectures, this is a no-op.
   62153 **
   62154 ** (later):  It is reported to me that the mixed-endian problem
   62155 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   62156 ** that early versions of GCC stored the two words of a 64-bit
   62157 ** float in the wrong order.  And that error has been propagated
   62158 ** ever since.  The blame is not necessarily with GCC, though.
   62159 ** GCC might have just copying the problem from a prior compiler.
   62160 ** I am also told that newer versions of GCC that follow a different
   62161 ** ABI get the byte order right.
   62162 **
   62163 ** Developers using SQLite on an ARM7 should compile and run their
   62164 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   62165 ** enabled, some asserts below will ensure that the byte order of
   62166 ** floating point values is correct.
   62167 **
   62168 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   62169 ** and has send his findings to the SQLite developers.  Frank
   62170 ** writes that some Linux kernels offer floating point hardware
   62171 ** emulation that uses only 32-bit mantissas instead of a full
   62172 ** 48-bits as required by the IEEE standard.  (This is the
   62173 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   62174 ** byte swapping becomes very complicated.  To avoid problems,
   62175 ** the necessary byte swapping is carried out using a 64-bit integer
   62176 ** rather than a 64-bit float.  Frank assures us that the code here
   62177 ** works for him.  We, the developers, have no way to independently
   62178 ** verify this, but Frank seems to know what he is talking about
   62179 ** so we trust him.
   62180 */
   62181 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   62182 static u64 floatSwap(u64 in){
   62183   union {
   62184     u64 r;
   62185     u32 i[2];
   62186   } u;
   62187   u32 t;
   62188 
   62189   u.r = in;
   62190   t = u.i[0];
   62191   u.i[0] = u.i[1];
   62192   u.i[1] = t;
   62193   return u.r;
   62194 }
   62195 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   62196 #else
   62197 # define swapMixedEndianFloat(X)
   62198 #endif
   62199 
   62200 /*
   62201 ** Write the serialized data blob for the value stored in pMem into
   62202 ** buf. It is assumed that the caller has allocated sufficient space.
   62203 ** Return the number of bytes written.
   62204 **
   62205 ** nBuf is the amount of space left in buf[].  nBuf must always be
   62206 ** large enough to hold the entire field.  Except, if the field is
   62207 ** a blob with a zero-filled tail, then buf[] might be just the right
   62208 ** size to hold everything except for the zero-filled tail.  If buf[]
   62209 ** is only big enough to hold the non-zero prefix, then only write that
   62210 ** prefix into buf[].  But if buf[] is large enough to hold both the
   62211 ** prefix and the tail then write the prefix and set the tail to all
   62212 ** zeros.
   62213 **
   62214 ** Return the number of bytes actually written into buf[].  The number
   62215 ** of bytes in the zero-filled tail is included in the return value only
   62216 ** if those bytes were zeroed in buf[].
   62217 */
   62218 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
   62219   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
   62220   u32 len;
   62221 
   62222   /* Integer and Real */
   62223   if( serial_type<=7 && serial_type>0 ){
   62224     u64 v;
   62225     u32 i;
   62226     if( serial_type==7 ){
   62227       assert( sizeof(v)==sizeof(pMem->r) );
   62228       memcpy(&v, &pMem->r, sizeof(v));
   62229       swapMixedEndianFloat(v);
   62230     }else{
   62231       v = pMem->u.i;
   62232     }
   62233     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   62234     assert( len<=(u32)nBuf );
   62235     while( i-- ){
   62236       buf[i] = (u8)(v&0xFF);
   62237       v >>= 8;
   62238     }
   62239     return len;
   62240   }
   62241 
   62242   /* String or blob */
   62243   if( serial_type>=12 ){
   62244     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   62245              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   62246     assert( pMem->n<=nBuf );
   62247     len = pMem->n;
   62248     memcpy(buf, pMem->z, len);
   62249     if( pMem->flags & MEM_Zero ){
   62250       len += pMem->u.nZero;
   62251       assert( nBuf>=0 );
   62252       if( len > (u32)nBuf ){
   62253         len = (u32)nBuf;
   62254       }
   62255       memset(&buf[pMem->n], 0, len-pMem->n);
   62256     }
   62257     return len;
   62258   }
   62259 
   62260   /* NULL or constants 0 or 1 */
   62261   return 0;
   62262 }
   62263 
   62264 /*
   62265 ** Deserialize the data blob pointed to by buf as serial type serial_type
   62266 ** and store the result in pMem.  Return the number of bytes read.
   62267 */
   62268 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   62269   const unsigned char *buf,     /* Buffer to deserialize from */
   62270   u32 serial_type,              /* Serial type to deserialize */
   62271   Mem *pMem                     /* Memory cell to write value into */
   62272 ){
   62273   switch( serial_type ){
   62274     case 10:   /* Reserved for future use */
   62275     case 11:   /* Reserved for future use */
   62276     case 0: {  /* NULL */
   62277       pMem->flags = MEM_Null;
   62278       break;
   62279     }
   62280     case 1: { /* 1-byte signed integer */
   62281       pMem->u.i = (signed char)buf[0];
   62282       pMem->flags = MEM_Int;
   62283       return 1;
   62284     }
   62285     case 2: { /* 2-byte signed integer */
   62286       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
   62287       pMem->flags = MEM_Int;
   62288       return 2;
   62289     }
   62290     case 3: { /* 3-byte signed integer */
   62291       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
   62292       pMem->flags = MEM_Int;
   62293       return 3;
   62294     }
   62295     case 4: { /* 4-byte signed integer */
   62296       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   62297       pMem->flags = MEM_Int;
   62298       return 4;
   62299     }
   62300     case 5: { /* 6-byte signed integer */
   62301       u64 x = (((signed char)buf[0])<<8) | buf[1];
   62302       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
   62303       x = (x<<32) | y;
   62304       pMem->u.i = *(i64*)&x;
   62305       pMem->flags = MEM_Int;
   62306       return 6;
   62307     }
   62308     case 6:   /* 8-byte signed integer */
   62309     case 7: { /* IEEE floating point */
   62310       u64 x;
   62311       u32 y;
   62312 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   62313       /* Verify that integers and floating point values use the same
   62314       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   62315       ** defined that 64-bit floating point values really are mixed
   62316       ** endian.
   62317       */
   62318       static const u64 t1 = ((u64)0x3ff00000)<<32;
   62319       static const double r1 = 1.0;
   62320       u64 t2 = t1;
   62321       swapMixedEndianFloat(t2);
   62322       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   62323 #endif
   62324 
   62325       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   62326       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
   62327       x = (x<<32) | y;
   62328       if( serial_type==6 ){
   62329         pMem->u.i = *(i64*)&x;
   62330         pMem->flags = MEM_Int;
   62331       }else{
   62332         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   62333         swapMixedEndianFloat(x);
   62334         memcpy(&pMem->r, &x, sizeof(x));
   62335         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   62336       }
   62337       return 8;
   62338     }
   62339     case 8:    /* Integer 0 */
   62340     case 9: {  /* Integer 1 */
   62341       pMem->u.i = serial_type-8;
   62342       pMem->flags = MEM_Int;
   62343       return 0;
   62344     }
   62345     default: {
   62346       u32 len = (serial_type-12)/2;
   62347       pMem->z = (char *)buf;
   62348       pMem->n = len;
   62349       pMem->xDel = 0;
   62350       if( serial_type&0x01 ){
   62351         pMem->flags = MEM_Str | MEM_Ephem;
   62352       }else{
   62353         pMem->flags = MEM_Blob | MEM_Ephem;
   62354       }
   62355       return len;
   62356     }
   62357   }
   62358   return 0;
   62359 }
   62360 
   62361 /*
   62362 ** This routine is used to allocate sufficient space for an UnpackedRecord
   62363 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
   62364 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
   62365 **
   62366 ** The space is either allocated using sqlite3DbMallocRaw() or from within
   62367 ** the unaligned buffer passed via the second and third arguments (presumably
   62368 ** stack space). If the former, then *ppFree is set to a pointer that should
   62369 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
   62370 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
   62371 ** before returning.
   62372 **
   62373 ** If an OOM error occurs, NULL is returned.
   62374 */
   62375 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
   62376   KeyInfo *pKeyInfo,              /* Description of the record */
   62377   char *pSpace,                   /* Unaligned space available */
   62378   int szSpace,                    /* Size of pSpace[] in bytes */
   62379   char **ppFree                   /* OUT: Caller should free this pointer */
   62380 ){
   62381   UnpackedRecord *p;              /* Unpacked record to return */
   62382   int nOff;                       /* Increment pSpace by nOff to align it */
   62383   int nByte;                      /* Number of bytes required for *p */
   62384 
   62385   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
   62386   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   62387   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   62388   */
   62389   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   62390   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   62391   if( nByte>szSpace+nOff ){
   62392     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   62393     *ppFree = (char *)p;
   62394     if( !p ) return 0;
   62395   }else{
   62396     p = (UnpackedRecord*)&pSpace[nOff];
   62397     *ppFree = 0;
   62398   }
   62399 
   62400   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   62401   p->pKeyInfo = pKeyInfo;
   62402   p->nField = pKeyInfo->nField + 1;
   62403   return p;
   62404 }
   62405 
   62406 /*
   62407 ** Given the nKey-byte encoding of a record in pKey[], populate the
   62408 ** UnpackedRecord structure indicated by the fourth argument with the
   62409 ** contents of the decoded record.
   62410 */
   62411 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   62412   KeyInfo *pKeyInfo,     /* Information about the record format */
   62413   int nKey,              /* Size of the binary record */
   62414   const void *pKey,      /* The binary record */
   62415   UnpackedRecord *p      /* Populate this structure before returning. */
   62416 ){
   62417   const unsigned char *aKey = (const unsigned char *)pKey;
   62418   int d;
   62419   u32 idx;                        /* Offset in aKey[] to read from */
   62420   u16 u;                          /* Unsigned loop counter */
   62421   u32 szHdr;
   62422   Mem *pMem = p->aMem;
   62423 
   62424   p->flags = 0;
   62425   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   62426   idx = getVarint32(aKey, szHdr);
   62427   d = szHdr;
   62428   u = 0;
   62429   while( idx<szHdr && u<p->nField && d<=nKey ){
   62430     u32 serial_type;
   62431 
   62432     idx += getVarint32(&aKey[idx], serial_type);
   62433     pMem->enc = pKeyInfo->enc;
   62434     pMem->db = pKeyInfo->db;
   62435     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
   62436     pMem->zMalloc = 0;
   62437     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   62438     pMem++;
   62439     u++;
   62440   }
   62441   assert( u<=pKeyInfo->nField + 1 );
   62442   p->nField = u;
   62443 }
   62444 
   62445 /*
   62446 ** This function compares the two table rows or index records
   62447 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   62448 ** or positive integer if key1 is less than, equal to or
   62449 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   62450 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   62451 ** key must be a parsed key such as obtained from
   62452 ** sqlite3VdbeParseRecord.
   62453 **
   62454 ** Key1 and Key2 do not have to contain the same number of fields.
   62455 ** The key with fewer fields is usually compares less than the
   62456 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
   62457 ** and the common prefixes are equal, then key1 is less than key2.
   62458 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
   62459 ** equal, then the keys are considered to be equal and
   62460 ** the parts beyond the common prefix are ignored.
   62461 */
   62462 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   62463   int nKey1, const void *pKey1, /* Left key */
   62464   UnpackedRecord *pPKey2        /* Right key */
   62465 ){
   62466   int d1;            /* Offset into aKey[] of next data element */
   62467   u32 idx1;          /* Offset into aKey[] of next header element */
   62468   u32 szHdr1;        /* Number of bytes in header */
   62469   int i = 0;
   62470   int nField;
   62471   int rc = 0;
   62472   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   62473   KeyInfo *pKeyInfo;
   62474   Mem mem1;
   62475 
   62476   pKeyInfo = pPKey2->pKeyInfo;
   62477   mem1.enc = pKeyInfo->enc;
   62478   mem1.db = pKeyInfo->db;
   62479   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   62480   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   62481 
   62482   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   62483   ** We could initialize it, as shown here, to silence those complaints.
   62484   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   62485   ** the unnecessary initialization has a measurable negative performance
   62486   ** impact, since this routine is a very high runner.  And so, we choose
   62487   ** to ignore the compiler warnings and leave this variable uninitialized.
   62488   */
   62489   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   62490 
   62491   idx1 = getVarint32(aKey1, szHdr1);
   62492   d1 = szHdr1;
   62493   nField = pKeyInfo->nField;
   62494   while( idx1<szHdr1 && i<pPKey2->nField ){
   62495     u32 serial_type1;
   62496 
   62497     /* Read the serial types for the next element in each key. */
   62498     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   62499     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
   62500 
   62501     /* Extract the values to be compared.
   62502     */
   62503     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   62504 
   62505     /* Do the comparison
   62506     */
   62507     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
   62508                            i<nField ? pKeyInfo->aColl[i] : 0);
   62509     if( rc!=0 ){
   62510       assert( mem1.zMalloc==0 );  /* See comment below */
   62511 
   62512       /* Invert the result if we are using DESC sort order. */
   62513       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
   62514         rc = -rc;
   62515       }
   62516 
   62517       /* If the PREFIX_SEARCH flag is set and all fields except the final
   62518       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
   62519       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
   62520       ** This is used by the OP_IsUnique opcode.
   62521       */
   62522       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
   62523         assert( idx1==szHdr1 && rc );
   62524         assert( mem1.flags & MEM_Int );
   62525         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
   62526         pPKey2->rowid = mem1.u.i;
   62527       }
   62528 
   62529       return rc;
   62530     }
   62531     i++;
   62532   }
   62533 
   62534   /* No memory allocation is ever used on mem1.  Prove this using
   62535   ** the following assert().  If the assert() fails, it indicates a
   62536   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   62537   */
   62538   assert( mem1.zMalloc==0 );
   62539 
   62540   /* rc==0 here means that one of the keys ran out of fields and
   62541   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
   62542   ** flag is set, then break the tie by treating key2 as larger.
   62543   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
   62544   ** are considered to be equal.  Otherwise, the longer key is the
   62545   ** larger.  As it happens, the pPKey2 will always be the longer
   62546   ** if there is a difference.
   62547   */
   62548   assert( rc==0 );
   62549   if( pPKey2->flags & UNPACKED_INCRKEY ){
   62550     rc = -1;
   62551   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
   62552     /* Leave rc==0 */
   62553   }else if( idx1<szHdr1 ){
   62554     rc = 1;
   62555   }
   62556   return rc;
   62557 }
   62558 
   62559 
   62560 /*
   62561 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   62562 ** Read the rowid (the last field in the record) and store it in *rowid.
   62563 ** Return SQLITE_OK if everything works, or an error code otherwise.
   62564 **
   62565 ** pCur might be pointing to text obtained from a corrupt database file.
   62566 ** So the content cannot be trusted.  Do appropriate checks on the content.
   62567 */
   62568 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   62569   i64 nCellKey = 0;
   62570   int rc;
   62571   u32 szHdr;        /* Size of the header */
   62572   u32 typeRowid;    /* Serial type of the rowid */
   62573   u32 lenRowid;     /* Size of the rowid */
   62574   Mem m, v;
   62575 
   62576   UNUSED_PARAMETER(db);
   62577 
   62578   /* Get the size of the index entry.  Only indices entries of less
   62579   ** than 2GiB are support - anything large must be database corruption.
   62580   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   62581   ** this code can safely assume that nCellKey is 32-bits
   62582   */
   62583   assert( sqlite3BtreeCursorIsValid(pCur) );
   62584   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   62585   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   62586   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   62587 
   62588   /* Read in the complete content of the index entry */
   62589   memset(&m, 0, sizeof(m));
   62590   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
   62591   if( rc ){
   62592     return rc;
   62593   }
   62594 
   62595   /* The index entry must begin with a header size */
   62596   (void)getVarint32((u8*)m.z, szHdr);
   62597   testcase( szHdr==3 );
   62598   testcase( szHdr==m.n );
   62599   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   62600     goto idx_rowid_corruption;
   62601   }
   62602 
   62603   /* The last field of the index should be an integer - the ROWID.
   62604   ** Verify that the last entry really is an integer. */
   62605   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   62606   testcase( typeRowid==1 );
   62607   testcase( typeRowid==2 );
   62608   testcase( typeRowid==3 );
   62609   testcase( typeRowid==4 );
   62610   testcase( typeRowid==5 );
   62611   testcase( typeRowid==6 );
   62612   testcase( typeRowid==8 );
   62613   testcase( typeRowid==9 );
   62614   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   62615     goto idx_rowid_corruption;
   62616   }
   62617   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   62618   testcase( (u32)m.n==szHdr+lenRowid );
   62619   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   62620     goto idx_rowid_corruption;
   62621   }
   62622 
   62623   /* Fetch the integer off the end of the index record */
   62624   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   62625   *rowid = v.u.i;
   62626   sqlite3VdbeMemRelease(&m);
   62627   return SQLITE_OK;
   62628 
   62629   /* Jump here if database corruption is detected after m has been
   62630   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   62631 idx_rowid_corruption:
   62632   testcase( m.zMalloc!=0 );
   62633   sqlite3VdbeMemRelease(&m);
   62634   return SQLITE_CORRUPT_BKPT;
   62635 }
   62636 
   62637 /*
   62638 ** Compare the key of the index entry that cursor pC is pointing to against
   62639 ** the key string in pUnpacked.  Write into *pRes a number
   62640 ** that is negative, zero, or positive if pC is less than, equal to,
   62641 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   62642 **
   62643 ** pUnpacked is either created without a rowid or is truncated so that it
   62644 ** omits the rowid at the end.  The rowid at the end of the index entry
   62645 ** is ignored as well.  Hence, this routine only compares the prefixes
   62646 ** of the keys prior to the final rowid, not the entire key.
   62647 */
   62648 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   62649   VdbeCursor *pC,             /* The cursor to compare against */
   62650   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
   62651   int *res                    /* Write the comparison result here */
   62652 ){
   62653   i64 nCellKey = 0;
   62654   int rc;
   62655   BtCursor *pCur = pC->pCursor;
   62656   Mem m;
   62657 
   62658   assert( sqlite3BtreeCursorIsValid(pCur) );
   62659   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
   62660   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   62661   /* nCellKey will always be between 0 and 0xffffffff because of the say
   62662   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   62663   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   62664     *res = 0;
   62665     return SQLITE_CORRUPT_BKPT;
   62666   }
   62667   memset(&m, 0, sizeof(m));
   62668   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
   62669   if( rc ){
   62670     return rc;
   62671   }
   62672   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
   62673   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
   62674   sqlite3VdbeMemRelease(&m);
   62675   return SQLITE_OK;
   62676 }
   62677 
   62678 /*
   62679 ** This routine sets the value to be returned by subsequent calls to
   62680 ** sqlite3_changes() on the database handle 'db'.
   62681 */
   62682 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   62683   assert( sqlite3_mutex_held(db->mutex) );
   62684   db->nChange = nChange;
   62685   db->nTotalChange += nChange;
   62686 }
   62687 
   62688 /*
   62689 ** Set a flag in the vdbe to update the change counter when it is finalised
   62690 ** or reset.
   62691 */
   62692 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   62693   v->changeCntOn = 1;
   62694 }
   62695 
   62696 /*
   62697 ** Mark every prepared statement associated with a database connection
   62698 ** as expired.
   62699 **
   62700 ** An expired statement means that recompilation of the statement is
   62701 ** recommend.  Statements expire when things happen that make their
   62702 ** programs obsolete.  Removing user-defined functions or collating
   62703 ** sequences, or changing an authorization function are the types of
   62704 ** things that make prepared statements obsolete.
   62705 */
   62706 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   62707   Vdbe *p;
   62708   for(p = db->pVdbe; p; p=p->pNext){
   62709     p->expired = 1;
   62710   }
   62711 }
   62712 
   62713 /*
   62714 ** Return the database associated with the Vdbe.
   62715 */
   62716 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   62717   return v->db;
   62718 }
   62719 
   62720 /*
   62721 ** Return a pointer to an sqlite3_value structure containing the value bound
   62722 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   62723 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   62724 ** constants) to the value before returning it.
   62725 **
   62726 ** The returned value must be freed by the caller using sqlite3ValueFree().
   62727 */
   62728 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
   62729   assert( iVar>0 );
   62730   if( v ){
   62731     Mem *pMem = &v->aVar[iVar-1];
   62732     if( 0==(pMem->flags & MEM_Null) ){
   62733       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   62734       if( pRet ){
   62735         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   62736         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   62737         sqlite3VdbeMemStoreType((Mem *)pRet);
   62738       }
   62739       return pRet;
   62740     }
   62741   }
   62742   return 0;
   62743 }
   62744 
   62745 /*
   62746 ** Configure SQL variable iVar so that binding a new value to it signals
   62747 ** to sqlite3_reoptimize() that re-preparing the statement may result
   62748 ** in a better query plan.
   62749 */
   62750 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   62751   assert( iVar>0 );
   62752   if( iVar>32 ){
   62753     v->expmask = 0xffffffff;
   62754   }else{
   62755     v->expmask |= ((u32)1 << (iVar-1));
   62756   }
   62757 }
   62758 
   62759 /************** End of vdbeaux.c *********************************************/
   62760 /************** Begin file vdbeapi.c *****************************************/
   62761 /*
   62762 ** 2004 May 26
   62763 **
   62764 ** The author disclaims copyright to this source code.  In place of
   62765 ** a legal notice, here is a blessing:
   62766 **
   62767 **    May you do good and not evil.
   62768 **    May you find forgiveness for yourself and forgive others.
   62769 **    May you share freely, never taking more than you give.
   62770 **
   62771 *************************************************************************
   62772 **
   62773 ** This file contains code use to implement APIs that are part of the
   62774 ** VDBE.
   62775 */
   62776 
   62777 #ifndef SQLITE_OMIT_DEPRECATED
   62778 /*
   62779 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   62780 ** to be recompiled.  A statement needs to be recompiled whenever the
   62781 ** execution environment changes in a way that would alter the program
   62782 ** that sqlite3_prepare() generates.  For example, if new functions or
   62783 ** collating sequences are registered or if an authorizer function is
   62784 ** added or changed.
   62785 */
   62786 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   62787   Vdbe *p = (Vdbe*)pStmt;
   62788   return p==0 || p->expired;
   62789 }
   62790 #endif
   62791 
   62792 /*
   62793 ** Check on a Vdbe to make sure it has not been finalized.  Log
   62794 ** an error and return true if it has been finalized (or is otherwise
   62795 ** invalid).  Return false if it is ok.
   62796 */
   62797 static int vdbeSafety(Vdbe *p){
   62798   if( p->db==0 ){
   62799     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   62800     return 1;
   62801   }else{
   62802     return 0;
   62803   }
   62804 }
   62805 static int vdbeSafetyNotNull(Vdbe *p){
   62806   if( p==0 ){
   62807     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   62808     return 1;
   62809   }else{
   62810     return vdbeSafety(p);
   62811   }
   62812 }
   62813 
   62814 /*
   62815 ** The following routine destroys a virtual machine that is created by
   62816 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   62817 ** success/failure code that describes the result of executing the virtual
   62818 ** machine.
   62819 **
   62820 ** This routine sets the error code and string returned by
   62821 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   62822 */
   62823 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   62824   int rc;
   62825   if( pStmt==0 ){
   62826     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   62827     ** pointer is a harmless no-op. */
   62828     rc = SQLITE_OK;
   62829   }else{
   62830     Vdbe *v = (Vdbe*)pStmt;
   62831     sqlite3 *db = v->db;
   62832 #if SQLITE_THREADSAFE
   62833     sqlite3_mutex *mutex;
   62834 #endif
   62835     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   62836 #if SQLITE_THREADSAFE
   62837     mutex = v->db->mutex;
   62838 #endif
   62839     sqlite3_mutex_enter(mutex);
   62840     rc = sqlite3VdbeFinalize(v);
   62841     rc = sqlite3ApiExit(db, rc);
   62842     sqlite3_mutex_leave(mutex);
   62843   }
   62844   return rc;
   62845 }
   62846 
   62847 /*
   62848 ** Terminate the current execution of an SQL statement and reset it
   62849 ** back to its starting state so that it can be reused. A success code from
   62850 ** the prior execution is returned.
   62851 **
   62852 ** This routine sets the error code and string returned by
   62853 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   62854 */
   62855 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   62856   int rc;
   62857   if( pStmt==0 ){
   62858     rc = SQLITE_OK;
   62859   }else{
   62860     Vdbe *v = (Vdbe*)pStmt;
   62861     sqlite3_mutex_enter(v->db->mutex);
   62862     rc = sqlite3VdbeReset(v);
   62863     sqlite3VdbeRewind(v);
   62864     assert( (rc & (v->db->errMask))==rc );
   62865     rc = sqlite3ApiExit(v->db, rc);
   62866     sqlite3_mutex_leave(v->db->mutex);
   62867   }
   62868   return rc;
   62869 }
   62870 
   62871 /*
   62872 ** Set all the parameters in the compiled SQL statement to NULL.
   62873 */
   62874 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   62875   int i;
   62876   int rc = SQLITE_OK;
   62877   Vdbe *p = (Vdbe*)pStmt;
   62878 #if SQLITE_THREADSAFE
   62879   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   62880 #endif
   62881   sqlite3_mutex_enter(mutex);
   62882   for(i=0; i<p->nVar; i++){
   62883     sqlite3VdbeMemRelease(&p->aVar[i]);
   62884     p->aVar[i].flags = MEM_Null;
   62885   }
   62886   if( p->isPrepareV2 && p->expmask ){
   62887     p->expired = 1;
   62888   }
   62889   sqlite3_mutex_leave(mutex);
   62890   return rc;
   62891 }
   62892 
   62893 
   62894 /**************************** sqlite3_value_  *******************************
   62895 ** The following routines extract information from a Mem or sqlite3_value
   62896 ** structure.
   62897 */
   62898 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   62899   Mem *p = (Mem*)pVal;
   62900   if( p->flags & (MEM_Blob|MEM_Str) ){
   62901     sqlite3VdbeMemExpandBlob(p);
   62902     p->flags &= ~MEM_Str;
   62903     p->flags |= MEM_Blob;
   62904     return p->n ? p->z : 0;
   62905   }else{
   62906     return sqlite3_value_text(pVal);
   62907   }
   62908 }
   62909 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   62910   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   62911 }
   62912 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   62913   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   62914 }
   62915 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   62916   return sqlite3VdbeRealValue((Mem*)pVal);
   62917 }
   62918 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   62919   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   62920 }
   62921 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   62922   return sqlite3VdbeIntValue((Mem*)pVal);
   62923 }
   62924 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   62925   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   62926 }
   62927 #ifndef SQLITE_OMIT_UTF16
   62928 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   62929   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   62930 }
   62931 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   62932   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   62933 }
   62934 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   62935   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   62936 }
   62937 #endif /* SQLITE_OMIT_UTF16 */
   62938 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   62939   return pVal->type;
   62940 }
   62941 
   62942 /**************************** sqlite3_result_  *******************************
   62943 ** The following routines are used by user-defined functions to specify
   62944 ** the function result.
   62945 **
   62946 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   62947 ** result as a string or blob but if the string or blob is too large, it
   62948 ** then sets the error code to SQLITE_TOOBIG
   62949 */
   62950 static void setResultStrOrError(
   62951   sqlite3_context *pCtx,  /* Function context */
   62952   const char *z,          /* String pointer */
   62953   int n,                  /* Bytes in string, or negative */
   62954   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   62955   void (*xDel)(void*)     /* Destructor function */
   62956 ){
   62957   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   62958     sqlite3_result_error_toobig(pCtx);
   62959   }
   62960 }
   62961 SQLITE_API void sqlite3_result_blob(
   62962   sqlite3_context *pCtx,
   62963   const void *z,
   62964   int n,
   62965   void (*xDel)(void *)
   62966 ){
   62967   assert( n>=0 );
   62968   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62969   setResultStrOrError(pCtx, z, n, 0, xDel);
   62970 }
   62971 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   62972   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62973   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   62974 }
   62975 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   62976   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62977   pCtx->isError = SQLITE_ERROR;
   62978   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   62979 }
   62980 #ifndef SQLITE_OMIT_UTF16
   62981 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   62982   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62983   pCtx->isError = SQLITE_ERROR;
   62984   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   62985 }
   62986 #endif
   62987 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   62988   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62989   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   62990 }
   62991 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   62992   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62993   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   62994 }
   62995 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   62996   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   62997   sqlite3VdbeMemSetNull(&pCtx->s);
   62998 }
   62999 SQLITE_API void sqlite3_result_text(
   63000   sqlite3_context *pCtx,
   63001   const char *z,
   63002   int n,
   63003   void (*xDel)(void *)
   63004 ){
   63005   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63006   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   63007 }
   63008 #ifndef SQLITE_OMIT_UTF16
   63009 SQLITE_API void sqlite3_result_text16(
   63010   sqlite3_context *pCtx,
   63011   const void *z,
   63012   int n,
   63013   void (*xDel)(void *)
   63014 ){
   63015   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63016   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   63017 }
   63018 SQLITE_API void sqlite3_result_text16be(
   63019   sqlite3_context *pCtx,
   63020   const void *z,
   63021   int n,
   63022   void (*xDel)(void *)
   63023 ){
   63024   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63025   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   63026 }
   63027 SQLITE_API void sqlite3_result_text16le(
   63028   sqlite3_context *pCtx,
   63029   const void *z,
   63030   int n,
   63031   void (*xDel)(void *)
   63032 ){
   63033   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63034   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   63035 }
   63036 #endif /* SQLITE_OMIT_UTF16 */
   63037 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   63038   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63039   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   63040 }
   63041 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   63042   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63043   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   63044 }
   63045 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   63046   pCtx->isError = errCode;
   63047   if( pCtx->s.flags & MEM_Null ){
   63048     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   63049                          SQLITE_UTF8, SQLITE_STATIC);
   63050   }
   63051 }
   63052 
   63053 /* Force an SQLITE_TOOBIG error. */
   63054 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   63055   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63056   pCtx->isError = SQLITE_TOOBIG;
   63057   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   63058                        SQLITE_UTF8, SQLITE_STATIC);
   63059 }
   63060 
   63061 /* An SQLITE_NOMEM error. */
   63062 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   63063   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63064   sqlite3VdbeMemSetNull(&pCtx->s);
   63065   pCtx->isError = SQLITE_NOMEM;
   63066   pCtx->s.db->mallocFailed = 1;
   63067 }
   63068 
   63069 /*
   63070 ** This function is called after a transaction has been committed. It
   63071 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   63072 */
   63073 static int doWalCallbacks(sqlite3 *db){
   63074   int rc = SQLITE_OK;
   63075 #ifndef SQLITE_OMIT_WAL
   63076   int i;
   63077   for(i=0; i<db->nDb; i++){
   63078     Btree *pBt = db->aDb[i].pBt;
   63079     if( pBt ){
   63080       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   63081       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   63082         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
   63083       }
   63084     }
   63085   }
   63086 #endif
   63087   return rc;
   63088 }
   63089 
   63090 /*
   63091 ** Execute the statement pStmt, either until a row of data is ready, the
   63092 ** statement is completely executed or an error occurs.
   63093 **
   63094 ** This routine implements the bulk of the logic behind the sqlite_step()
   63095 ** API.  The only thing omitted is the automatic recompile if a
   63096 ** schema change has occurred.  That detail is handled by the
   63097 ** outer sqlite3_step() wrapper procedure.
   63098 */
   63099 static int sqlite3Step(Vdbe *p){
   63100   sqlite3 *db;
   63101   int rc;
   63102 
   63103   assert(p);
   63104   if( p->magic!=VDBE_MAGIC_RUN ){
   63105     /* We used to require that sqlite3_reset() be called before retrying
   63106     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
   63107     ** with version 3.7.0, we changed this so that sqlite3_reset() would
   63108     ** be called automatically instead of throwing the SQLITE_MISUSE error.
   63109     ** This "automatic-reset" change is not technically an incompatibility,
   63110     ** since any application that receives an SQLITE_MISUSE is broken by
   63111     ** definition.
   63112     **
   63113     ** Nevertheless, some published applications that were originally written
   63114     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
   63115     ** returns, and those were broken by the automatic-reset change.  As a
   63116     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
   63117     ** legacy behavior of returning SQLITE_MISUSE for cases where the
   63118     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
   63119     ** or SQLITE_BUSY error.
   63120     */
   63121 #ifdef SQLITE_OMIT_AUTORESET
   63122     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
   63123       sqlite3_reset((sqlite3_stmt*)p);
   63124     }else{
   63125       return SQLITE_MISUSE_BKPT;
   63126     }
   63127 #else
   63128     sqlite3_reset((sqlite3_stmt*)p);
   63129 #endif
   63130   }
   63131 
   63132   /* Check that malloc() has not failed. If it has, return early. */
   63133   db = p->db;
   63134   if( db->mallocFailed ){
   63135     p->rc = SQLITE_NOMEM;
   63136     return SQLITE_NOMEM;
   63137   }
   63138 
   63139   if( p->pc<=0 && p->expired ){
   63140     p->rc = SQLITE_SCHEMA;
   63141     rc = SQLITE_ERROR;
   63142     goto end_of_step;
   63143   }
   63144   if( p->pc<0 ){
   63145     /* If there are no other statements currently running, then
   63146     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   63147     ** from interrupting a statement that has not yet started.
   63148     */
   63149     if( db->activeVdbeCnt==0 ){
   63150       db->u1.isInterrupted = 0;
   63151     }
   63152 
   63153     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
   63154 
   63155 #ifndef SQLITE_OMIT_TRACE
   63156     if( db->xProfile && !db->init.busy ){
   63157       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   63158     }
   63159 #endif
   63160 
   63161     db->activeVdbeCnt++;
   63162     if( p->readOnly==0 ) db->writeVdbeCnt++;
   63163     p->pc = 0;
   63164   }
   63165 #ifndef SQLITE_OMIT_EXPLAIN
   63166   if( p->explain ){
   63167     rc = sqlite3VdbeList(p);
   63168   }else
   63169 #endif /* SQLITE_OMIT_EXPLAIN */
   63170   {
   63171     db->vdbeExecCnt++;
   63172     rc = sqlite3VdbeExec(p);
   63173     db->vdbeExecCnt--;
   63174   }
   63175 
   63176 #ifndef SQLITE_OMIT_TRACE
   63177   /* Invoke the profile callback if there is one
   63178   */
   63179   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   63180     sqlite3_int64 iNow;
   63181     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   63182     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
   63183   }
   63184 #endif
   63185 
   63186   if( rc==SQLITE_DONE ){
   63187     assert( p->rc==SQLITE_OK );
   63188     p->rc = doWalCallbacks(db);
   63189     if( p->rc!=SQLITE_OK ){
   63190       rc = SQLITE_ERROR;
   63191     }
   63192   }
   63193 
   63194   db->errCode = rc;
   63195   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   63196     p->rc = SQLITE_NOMEM;
   63197   }
   63198 end_of_step:
   63199   /* At this point local variable rc holds the value that should be
   63200   ** returned if this statement was compiled using the legacy
   63201   ** sqlite3_prepare() interface. According to the docs, this can only
   63202   ** be one of the values in the first assert() below. Variable p->rc
   63203   ** contains the value that would be returned if sqlite3_finalize()
   63204   ** were called on statement p.
   63205   */
   63206   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   63207        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   63208   );
   63209   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   63210   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   63211     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   63212     ** error has occured, then return the error code in p->rc to the
   63213     ** caller. Set the error code in the database handle to the same value.
   63214     */
   63215     rc = sqlite3VdbeTransferError(p);
   63216   }
   63217   return (rc&db->errMask);
   63218 }
   63219 
   63220 /*
   63221 ** The maximum number of times that a statement will try to reparse
   63222 ** itself before giving up and returning SQLITE_SCHEMA.
   63223 */
   63224 #ifndef SQLITE_MAX_SCHEMA_RETRY
   63225 # define SQLITE_MAX_SCHEMA_RETRY 5
   63226 #endif
   63227 
   63228 /*
   63229 ** This is the top-level implementation of sqlite3_step().  Call
   63230 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   63231 ** call sqlite3Reprepare() and try again.
   63232 */
   63233 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   63234   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   63235   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   63236   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   63237   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   63238   sqlite3 *db;             /* The database connection */
   63239 
   63240   if( vdbeSafetyNotNull(v) ){
   63241     return SQLITE_MISUSE_BKPT;
   63242   }
   63243   db = v->db;
   63244   sqlite3_mutex_enter(db->mutex);
   63245   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   63246          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
   63247          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   63248     sqlite3_reset(pStmt);
   63249     assert( v->expired==0 );
   63250   }
   63251   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
   63252     /* This case occurs after failing to recompile an sql statement.
   63253     ** The error message from the SQL compiler has already been loaded
   63254     ** into the database handle. This block copies the error message
   63255     ** from the database handle into the statement and sets the statement
   63256     ** program counter to 0 to ensure that when the statement is
   63257     ** finalized or reset the parser error message is available via
   63258     ** sqlite3_errmsg() and sqlite3_errcode().
   63259     */
   63260     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   63261     sqlite3DbFree(db, v->zErrMsg);
   63262     if( !db->mallocFailed ){
   63263       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   63264       v->rc = rc2;
   63265     } else {
   63266       v->zErrMsg = 0;
   63267       v->rc = rc = SQLITE_NOMEM;
   63268     }
   63269   }
   63270   rc = sqlite3ApiExit(db, rc);
   63271   sqlite3_mutex_leave(db->mutex);
   63272   return rc;
   63273 }
   63274 
   63275 /*
   63276 ** Extract the user data from a sqlite3_context structure and return a
   63277 ** pointer to it.
   63278 */
   63279 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   63280   assert( p && p->pFunc );
   63281   return p->pFunc->pUserData;
   63282 }
   63283 
   63284 /*
   63285 ** Extract the user data from a sqlite3_context structure and return a
   63286 ** pointer to it.
   63287 **
   63288 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   63289 ** returns a copy of the pointer to the database connection (the 1st
   63290 ** parameter) of the sqlite3_create_function() and
   63291 ** sqlite3_create_function16() routines that originally registered the
   63292 ** application defined function.
   63293 */
   63294 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   63295   assert( p && p->pFunc );
   63296   return p->s.db;
   63297 }
   63298 
   63299 /*
   63300 ** The following is the implementation of an SQL function that always
   63301 ** fails with an error message stating that the function is used in the
   63302 ** wrong context.  The sqlite3_overload_function() API might construct
   63303 ** SQL function that use this routine so that the functions will exist
   63304 ** for name resolution but are actually overloaded by the xFindFunction
   63305 ** method of virtual tables.
   63306 */
   63307 SQLITE_PRIVATE void sqlite3InvalidFunction(
   63308   sqlite3_context *context,  /* The function calling context */
   63309   int NotUsed,               /* Number of arguments to the function */
   63310   sqlite3_value **NotUsed2   /* Value of each argument */
   63311 ){
   63312   const char *zName = context->pFunc->zName;
   63313   char *zErr;
   63314   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   63315   zErr = sqlite3_mprintf(
   63316       "unable to use function %s in the requested context", zName);
   63317   sqlite3_result_error(context, zErr, -1);
   63318   sqlite3_free(zErr);
   63319 }
   63320 
   63321 /*
   63322 ** Allocate or return the aggregate context for a user function.  A new
   63323 ** context is allocated on the first call.  Subsequent calls return the
   63324 ** same context that was returned on prior calls.
   63325 */
   63326 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   63327   Mem *pMem;
   63328   assert( p && p->pFunc && p->pFunc->xStep );
   63329   assert( sqlite3_mutex_held(p->s.db->mutex) );
   63330   pMem = p->pMem;
   63331   testcase( nByte<0 );
   63332   if( (pMem->flags & MEM_Agg)==0 ){
   63333     if( nByte<=0 ){
   63334       sqlite3VdbeMemReleaseExternal(pMem);
   63335       pMem->flags = MEM_Null;
   63336       pMem->z = 0;
   63337     }else{
   63338       sqlite3VdbeMemGrow(pMem, nByte, 0);
   63339       pMem->flags = MEM_Agg;
   63340       pMem->u.pDef = p->pFunc;
   63341       if( pMem->z ){
   63342         memset(pMem->z, 0, nByte);
   63343       }
   63344     }
   63345   }
   63346   return (void*)pMem->z;
   63347 }
   63348 
   63349 /*
   63350 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   63351 ** the user-function defined by pCtx.
   63352 */
   63353 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   63354   VdbeFunc *pVdbeFunc;
   63355 
   63356   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63357   pVdbeFunc = pCtx->pVdbeFunc;
   63358   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
   63359     return 0;
   63360   }
   63361   return pVdbeFunc->apAux[iArg].pAux;
   63362 }
   63363 
   63364 /*
   63365 ** Set the auxilary data pointer and delete function, for the iArg'th
   63366 ** argument to the user-function defined by pCtx. Any previous value is
   63367 ** deleted by calling the delete function specified when it was set.
   63368 */
   63369 SQLITE_API void sqlite3_set_auxdata(
   63370   sqlite3_context *pCtx,
   63371   int iArg,
   63372   void *pAux,
   63373   void (*xDelete)(void*)
   63374 ){
   63375   struct AuxData *pAuxData;
   63376   VdbeFunc *pVdbeFunc;
   63377   if( iArg<0 ) goto failed;
   63378 
   63379   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   63380   pVdbeFunc = pCtx->pVdbeFunc;
   63381   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
   63382     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
   63383     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
   63384     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
   63385     if( !pVdbeFunc ){
   63386       goto failed;
   63387     }
   63388     pCtx->pVdbeFunc = pVdbeFunc;
   63389     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
   63390     pVdbeFunc->nAux = iArg+1;
   63391     pVdbeFunc->pFunc = pCtx->pFunc;
   63392   }
   63393 
   63394   pAuxData = &pVdbeFunc->apAux[iArg];
   63395   if( pAuxData->pAux && pAuxData->xDelete ){
   63396     pAuxData->xDelete(pAuxData->pAux);
   63397   }
   63398   pAuxData->pAux = pAux;
   63399   pAuxData->xDelete = xDelete;
   63400   return;
   63401 
   63402 failed:
   63403   if( xDelete ){
   63404     xDelete(pAux);
   63405   }
   63406 }
   63407 
   63408 #ifndef SQLITE_OMIT_DEPRECATED
   63409 /*
   63410 ** Return the number of times the Step function of a aggregate has been
   63411 ** called.
   63412 **
   63413 ** This function is deprecated.  Do not use it for new code.  It is
   63414 ** provide only to avoid breaking legacy code.  New aggregate function
   63415 ** implementations should keep their own counts within their aggregate
   63416 ** context.
   63417 */
   63418 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   63419   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   63420   return p->pMem->n;
   63421 }
   63422 #endif
   63423 
   63424 /*
   63425 ** Return the number of columns in the result set for the statement pStmt.
   63426 */
   63427 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   63428   Vdbe *pVm = (Vdbe *)pStmt;
   63429   return pVm ? pVm->nResColumn : 0;
   63430 }
   63431 
   63432 /*
   63433 ** Return the number of values available from the current row of the
   63434 ** currently executing statement pStmt.
   63435 */
   63436 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   63437   Vdbe *pVm = (Vdbe *)pStmt;
   63438   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   63439   return pVm->nResColumn;
   63440 }
   63441 
   63442 
   63443 /*
   63444 ** Check to see if column iCol of the given statement is valid.  If
   63445 ** it is, return a pointer to the Mem for the value of that column.
   63446 ** If iCol is not valid, return a pointer to a Mem which has a value
   63447 ** of NULL.
   63448 */
   63449 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   63450   Vdbe *pVm;
   63451   Mem *pOut;
   63452 
   63453   pVm = (Vdbe *)pStmt;
   63454   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   63455     sqlite3_mutex_enter(pVm->db->mutex);
   63456     pOut = &pVm->pResultSet[i];
   63457   }else{
   63458     /* If the value passed as the second argument is out of range, return
   63459     ** a pointer to the following static Mem object which contains the
   63460     ** value SQL NULL. Even though the Mem structure contains an element
   63461     ** of type i64, on certain architectures (x86) with certain compiler
   63462     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   63463     ** instead of an 8-byte one. This all works fine, except that when
   63464     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   63465     ** that a Mem structure is located on an 8-byte boundary. To prevent
   63466     ** these assert()s from failing, when building with SQLITE_DEBUG defined
   63467     ** using gcc, we force nullMem to be 8-byte aligned using the magical
   63468     ** __attribute__((aligned(8))) macro.  */
   63469     static const Mem nullMem
   63470 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   63471       __attribute__((aligned(8)))
   63472 #endif
   63473       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
   63474 #ifdef SQLITE_DEBUG
   63475          0, 0,  /* pScopyFrom, pFiller */
   63476 #endif
   63477          0, 0 };
   63478 
   63479     if( pVm && ALWAYS(pVm->db) ){
   63480       sqlite3_mutex_enter(pVm->db->mutex);
   63481       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   63482     }
   63483     pOut = (Mem*)&nullMem;
   63484   }
   63485   return pOut;
   63486 }
   63487 
   63488 /*
   63489 ** This function is called after invoking an sqlite3_value_XXX function on a
   63490 ** column value (i.e. a value returned by evaluating an SQL expression in the
   63491 ** select list of a SELECT statement) that may cause a malloc() failure. If
   63492 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   63493 ** code of statement pStmt set to SQLITE_NOMEM.
   63494 **
   63495 ** Specifically, this is called from within:
   63496 **
   63497 **     sqlite3_column_int()
   63498 **     sqlite3_column_int64()
   63499 **     sqlite3_column_text()
   63500 **     sqlite3_column_text16()
   63501 **     sqlite3_column_real()
   63502 **     sqlite3_column_bytes()
   63503 **     sqlite3_column_bytes16()
   63504 **     sqiite3_column_blob()
   63505 */
   63506 static void columnMallocFailure(sqlite3_stmt *pStmt)
   63507 {
   63508   /* If malloc() failed during an encoding conversion within an
   63509   ** sqlite3_column_XXX API, then set the return code of the statement to
   63510   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   63511   ** and _finalize() will return NOMEM.
   63512   */
   63513   Vdbe *p = (Vdbe *)pStmt;
   63514   if( p ){
   63515     p->rc = sqlite3ApiExit(p->db, p->rc);
   63516     sqlite3_mutex_leave(p->db->mutex);
   63517   }
   63518 }
   63519 
   63520 /**************************** sqlite3_column_  *******************************
   63521 ** The following routines are used to access elements of the current row
   63522 ** in the result set.
   63523 */
   63524 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   63525   const void *val;
   63526   val = sqlite3_value_blob( columnMem(pStmt,i) );
   63527   /* Even though there is no encoding conversion, value_blob() might
   63528   ** need to call malloc() to expand the result of a zeroblob()
   63529   ** expression.
   63530   */
   63531   columnMallocFailure(pStmt);
   63532   return val;
   63533 }
   63534 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   63535   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   63536   columnMallocFailure(pStmt);
   63537   return val;
   63538 }
   63539 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   63540   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   63541   columnMallocFailure(pStmt);
   63542   return val;
   63543 }
   63544 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   63545   double val = sqlite3_value_double( columnMem(pStmt,i) );
   63546   columnMallocFailure(pStmt);
   63547   return val;
   63548 }
   63549 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   63550   int val = sqlite3_value_int( columnMem(pStmt,i) );
   63551   columnMallocFailure(pStmt);
   63552   return val;
   63553 }
   63554 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   63555   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   63556   columnMallocFailure(pStmt);
   63557   return val;
   63558 }
   63559 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   63560   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   63561   columnMallocFailure(pStmt);
   63562   return val;
   63563 }
   63564 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   63565   Mem *pOut = columnMem(pStmt, i);
   63566   if( pOut->flags&MEM_Static ){
   63567     pOut->flags &= ~MEM_Static;
   63568     pOut->flags |= MEM_Ephem;
   63569   }
   63570   columnMallocFailure(pStmt);
   63571   return (sqlite3_value *)pOut;
   63572 }
   63573 #ifndef SQLITE_OMIT_UTF16
   63574 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   63575   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   63576   columnMallocFailure(pStmt);
   63577   return val;
   63578 }
   63579 #endif /* SQLITE_OMIT_UTF16 */
   63580 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   63581   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   63582   columnMallocFailure(pStmt);
   63583   return iType;
   63584 }
   63585 
   63586 /* The following function is experimental and subject to change or
   63587 ** removal */
   63588 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
   63589 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
   63590 **}
   63591 */
   63592 
   63593 /*
   63594 ** Convert the N-th element of pStmt->pColName[] into a string using
   63595 ** xFunc() then return that string.  If N is out of range, return 0.
   63596 **
   63597 ** There are up to 5 names for each column.  useType determines which
   63598 ** name is returned.  Here are the names:
   63599 **
   63600 **    0      The column name as it should be displayed for output
   63601 **    1      The datatype name for the column
   63602 **    2      The name of the database that the column derives from
   63603 **    3      The name of the table that the column derives from
   63604 **    4      The name of the table column that the result column derives from
   63605 **
   63606 ** If the result is not a simple column reference (if it is an expression
   63607 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   63608 */
   63609 static const void *columnName(
   63610   sqlite3_stmt *pStmt,
   63611   int N,
   63612   const void *(*xFunc)(Mem*),
   63613   int useType
   63614 ){
   63615   const void *ret = 0;
   63616   Vdbe *p = (Vdbe *)pStmt;
   63617   int n;
   63618   sqlite3 *db = p->db;
   63619 
   63620   assert( db!=0 );
   63621   n = sqlite3_column_count(pStmt);
   63622   if( N<n && N>=0 ){
   63623     N += useType*n;
   63624     sqlite3_mutex_enter(db->mutex);
   63625     assert( db->mallocFailed==0 );
   63626     ret = xFunc(&p->aColName[N]);
   63627      /* A malloc may have failed inside of the xFunc() call. If this
   63628     ** is the case, clear the mallocFailed flag and return NULL.
   63629     */
   63630     if( db->mallocFailed ){
   63631       db->mallocFailed = 0;
   63632       ret = 0;
   63633     }
   63634     sqlite3_mutex_leave(db->mutex);
   63635   }
   63636   return ret;
   63637 }
   63638 
   63639 /*
   63640 ** Return the name of the Nth column of the result set returned by SQL
   63641 ** statement pStmt.
   63642 */
   63643 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   63644   return columnName(
   63645       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   63646 }
   63647 #ifndef SQLITE_OMIT_UTF16
   63648 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   63649   return columnName(
   63650       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   63651 }
   63652 #endif
   63653 
   63654 /*
   63655 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   63656 ** not define OMIT_DECLTYPE.
   63657 */
   63658 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   63659 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   63660          and SQLITE_ENABLE_COLUMN_METADATA"
   63661 #endif
   63662 
   63663 #ifndef SQLITE_OMIT_DECLTYPE
   63664 /*
   63665 ** Return the column declaration type (if applicable) of the 'i'th column
   63666 ** of the result set of SQL statement pStmt.
   63667 */
   63668 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   63669   return columnName(
   63670       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   63671 }
   63672 #ifndef SQLITE_OMIT_UTF16
   63673 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   63674   return columnName(
   63675       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   63676 }
   63677 #endif /* SQLITE_OMIT_UTF16 */
   63678 #endif /* SQLITE_OMIT_DECLTYPE */
   63679 
   63680 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   63681 /*
   63682 ** Return the name of the database from which a result column derives.
   63683 ** NULL is returned if the result column is an expression or constant or
   63684 ** anything else which is not an unabiguous reference to a database column.
   63685 */
   63686 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   63687   return columnName(
   63688       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   63689 }
   63690 #ifndef SQLITE_OMIT_UTF16
   63691 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   63692   return columnName(
   63693       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   63694 }
   63695 #endif /* SQLITE_OMIT_UTF16 */
   63696 
   63697 /*
   63698 ** Return the name of the table from which a result column derives.
   63699 ** NULL is returned if the result column is an expression or constant or
   63700 ** anything else which is not an unabiguous reference to a database column.
   63701 */
   63702 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   63703   return columnName(
   63704       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   63705 }
   63706 #ifndef SQLITE_OMIT_UTF16
   63707 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   63708   return columnName(
   63709       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   63710 }
   63711 #endif /* SQLITE_OMIT_UTF16 */
   63712 
   63713 /*
   63714 ** Return the name of the table column from which a result column derives.
   63715 ** NULL is returned if the result column is an expression or constant or
   63716 ** anything else which is not an unabiguous reference to a database column.
   63717 */
   63718 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   63719   return columnName(
   63720       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   63721 }
   63722 #ifndef SQLITE_OMIT_UTF16
   63723 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   63724   return columnName(
   63725       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   63726 }
   63727 #endif /* SQLITE_OMIT_UTF16 */
   63728 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   63729 
   63730 
   63731 /******************************* sqlite3_bind_  ***************************
   63732 **
   63733 ** Routines used to attach values to wildcards in a compiled SQL statement.
   63734 */
   63735 /*
   63736 ** Unbind the value bound to variable i in virtual machine p. This is the
   63737 ** the same as binding a NULL value to the column. If the "i" parameter is
   63738 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   63739 **
   63740 ** A successful evaluation of this routine acquires the mutex on p.
   63741 ** the mutex is released if any kind of error occurs.
   63742 **
   63743 ** The error code stored in database p->db is overwritten with the return
   63744 ** value in any case.
   63745 */
   63746 static int vdbeUnbind(Vdbe *p, int i){
   63747   Mem *pVar;
   63748   if( vdbeSafetyNotNull(p) ){
   63749     return SQLITE_MISUSE_BKPT;
   63750   }
   63751   sqlite3_mutex_enter(p->db->mutex);
   63752   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   63753     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   63754     sqlite3_mutex_leave(p->db->mutex);
   63755     sqlite3_log(SQLITE_MISUSE,
   63756         "bind on a busy prepared statement: [%s]", p->zSql);
   63757     return SQLITE_MISUSE_BKPT;
   63758   }
   63759   if( i<1 || i>p->nVar ){
   63760     sqlite3Error(p->db, SQLITE_RANGE, 0);
   63761     sqlite3_mutex_leave(p->db->mutex);
   63762     return SQLITE_RANGE;
   63763   }
   63764   i--;
   63765   pVar = &p->aVar[i];
   63766   sqlite3VdbeMemRelease(pVar);
   63767   pVar->flags = MEM_Null;
   63768   sqlite3Error(p->db, SQLITE_OK, 0);
   63769 
   63770   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   63771   ** binding a new value to this variable invalidates the current query plan.
   63772   **
   63773   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   63774   ** parameter in the WHERE clause might influence the choice of query plan
   63775   ** for a statement, then the statement will be automatically recompiled,
   63776   ** as if there had been a schema change, on the first sqlite3_step() call
   63777   ** following any change to the bindings of that parameter.
   63778   */
   63779   if( p->isPrepareV2 &&
   63780      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   63781   ){
   63782     p->expired = 1;
   63783   }
   63784   return SQLITE_OK;
   63785 }
   63786 
   63787 /*
   63788 ** Bind a text or BLOB value.
   63789 */
   63790 static int bindText(
   63791   sqlite3_stmt *pStmt,   /* The statement to bind against */
   63792   int i,                 /* Index of the parameter to bind */
   63793   const void *zData,     /* Pointer to the data to be bound */
   63794   int nData,             /* Number of bytes of data to be bound */
   63795   void (*xDel)(void*),   /* Destructor for the data */
   63796   u8 encoding            /* Encoding for the data */
   63797 ){
   63798   Vdbe *p = (Vdbe *)pStmt;
   63799   Mem *pVar;
   63800   int rc;
   63801 
   63802   rc = vdbeUnbind(p, i);
   63803   if( rc==SQLITE_OK ){
   63804     if( zData!=0 ){
   63805       pVar = &p->aVar[i-1];
   63806       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   63807       if( rc==SQLITE_OK && encoding!=0 ){
   63808         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   63809       }
   63810       sqlite3Error(p->db, rc, 0);
   63811       rc = sqlite3ApiExit(p->db, rc);
   63812     }
   63813     sqlite3_mutex_leave(p->db->mutex);
   63814   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   63815     xDel((void*)zData);
   63816   }
   63817   return rc;
   63818 }
   63819 
   63820 
   63821 /*
   63822 ** Bind a blob value to an SQL statement variable.
   63823 */
   63824 SQLITE_API int sqlite3_bind_blob(
   63825   sqlite3_stmt *pStmt,
   63826   int i,
   63827   const void *zData,
   63828   int nData,
   63829   void (*xDel)(void*)
   63830 ){
   63831   return bindText(pStmt, i, zData, nData, xDel, 0);
   63832 }
   63833 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   63834   int rc;
   63835   Vdbe *p = (Vdbe *)pStmt;
   63836   rc = vdbeUnbind(p, i);
   63837   if( rc==SQLITE_OK ){
   63838     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   63839     sqlite3_mutex_leave(p->db->mutex);
   63840   }
   63841   return rc;
   63842 }
   63843 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   63844   return sqlite3_bind_int64(p, i, (i64)iValue);
   63845 }
   63846 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   63847   int rc;
   63848   Vdbe *p = (Vdbe *)pStmt;
   63849   rc = vdbeUnbind(p, i);
   63850   if( rc==SQLITE_OK ){
   63851     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   63852     sqlite3_mutex_leave(p->db->mutex);
   63853   }
   63854   return rc;
   63855 }
   63856 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   63857   int rc;
   63858   Vdbe *p = (Vdbe*)pStmt;
   63859   rc = vdbeUnbind(p, i);
   63860   if( rc==SQLITE_OK ){
   63861     sqlite3_mutex_leave(p->db->mutex);
   63862   }
   63863   return rc;
   63864 }
   63865 SQLITE_API int sqlite3_bind_text(
   63866   sqlite3_stmt *pStmt,
   63867   int i,
   63868   const char *zData,
   63869   int nData,
   63870   void (*xDel)(void*)
   63871 ){
   63872   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   63873 }
   63874 #ifndef SQLITE_OMIT_UTF16
   63875 SQLITE_API int sqlite3_bind_text16(
   63876   sqlite3_stmt *pStmt,
   63877   int i,
   63878   const void *zData,
   63879   int nData,
   63880   void (*xDel)(void*)
   63881 ){
   63882   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   63883 }
   63884 #endif /* SQLITE_OMIT_UTF16 */
   63885 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   63886   int rc;
   63887   switch( pValue->type ){
   63888     case SQLITE_INTEGER: {
   63889       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   63890       break;
   63891     }
   63892     case SQLITE_FLOAT: {
   63893       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   63894       break;
   63895     }
   63896     case SQLITE_BLOB: {
   63897       if( pValue->flags & MEM_Zero ){
   63898         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   63899       }else{
   63900         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   63901       }
   63902       break;
   63903     }
   63904     case SQLITE_TEXT: {
   63905       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   63906                               pValue->enc);
   63907       break;
   63908     }
   63909     default: {
   63910       rc = sqlite3_bind_null(pStmt, i);
   63911       break;
   63912     }
   63913   }
   63914   return rc;
   63915 }
   63916 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   63917   int rc;
   63918   Vdbe *p = (Vdbe *)pStmt;
   63919   rc = vdbeUnbind(p, i);
   63920   if( rc==SQLITE_OK ){
   63921     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   63922     sqlite3_mutex_leave(p->db->mutex);
   63923   }
   63924   return rc;
   63925 }
   63926 
   63927 /*
   63928 ** Return the number of wildcards that can be potentially bound to.
   63929 ** This routine is added to support DBD::SQLite.
   63930 */
   63931 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   63932   Vdbe *p = (Vdbe*)pStmt;
   63933   return p ? p->nVar : 0;
   63934 }
   63935 
   63936 /*
   63937 ** Return the name of a wildcard parameter.  Return NULL if the index
   63938 ** is out of range or if the wildcard is unnamed.
   63939 **
   63940 ** The result is always UTF-8.
   63941 */
   63942 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   63943   Vdbe *p = (Vdbe*)pStmt;
   63944   if( p==0 || i<1 || i>p->nzVar ){
   63945     return 0;
   63946   }
   63947   return p->azVar[i-1];
   63948 }
   63949 
   63950 /*
   63951 ** Given a wildcard parameter name, return the index of the variable
   63952 ** with that name.  If there is no variable with the given name,
   63953 ** return 0.
   63954 */
   63955 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   63956   int i;
   63957   if( p==0 ){
   63958     return 0;
   63959   }
   63960   if( zName ){
   63961     for(i=0; i<p->nzVar; i++){
   63962       const char *z = p->azVar[i];
   63963       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
   63964         return i+1;
   63965       }
   63966     }
   63967   }
   63968   return 0;
   63969 }
   63970 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   63971   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   63972 }
   63973 
   63974 /*
   63975 ** Transfer all bindings from the first statement over to the second.
   63976 */
   63977 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   63978   Vdbe *pFrom = (Vdbe*)pFromStmt;
   63979   Vdbe *pTo = (Vdbe*)pToStmt;
   63980   int i;
   63981   assert( pTo->db==pFrom->db );
   63982   assert( pTo->nVar==pFrom->nVar );
   63983   sqlite3_mutex_enter(pTo->db->mutex);
   63984   for(i=0; i<pFrom->nVar; i++){
   63985     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   63986   }
   63987   sqlite3_mutex_leave(pTo->db->mutex);
   63988   return SQLITE_OK;
   63989 }
   63990 
   63991 #ifndef SQLITE_OMIT_DEPRECATED
   63992 /*
   63993 ** Deprecated external interface.  Internal/core SQLite code
   63994 ** should call sqlite3TransferBindings.
   63995 **
   63996 ** Is is misuse to call this routine with statements from different
   63997 ** database connections.  But as this is a deprecated interface, we
   63998 ** will not bother to check for that condition.
   63999 **
   64000 ** If the two statements contain a different number of bindings, then
   64001 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   64002 ** SQLITE_OK is returned.
   64003 */
   64004 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   64005   Vdbe *pFrom = (Vdbe*)pFromStmt;
   64006   Vdbe *pTo = (Vdbe*)pToStmt;
   64007   if( pFrom->nVar!=pTo->nVar ){
   64008     return SQLITE_ERROR;
   64009   }
   64010   if( pTo->isPrepareV2 && pTo->expmask ){
   64011     pTo->expired = 1;
   64012   }
   64013   if( pFrom->isPrepareV2 && pFrom->expmask ){
   64014     pFrom->expired = 1;
   64015   }
   64016   return sqlite3TransferBindings(pFromStmt, pToStmt);
   64017 }
   64018 #endif
   64019 
   64020 /*
   64021 ** Return the sqlite3* database handle to which the prepared statement given
   64022 ** in the argument belongs.  This is the same database handle that was
   64023 ** the first argument to the sqlite3_prepare() that was used to create
   64024 ** the statement in the first place.
   64025 */
   64026 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   64027   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   64028 }
   64029 
   64030 /*
   64031 ** Return true if the prepared statement is guaranteed to not modify the
   64032 ** database.
   64033 */
   64034 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   64035   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   64036 }
   64037 
   64038 /*
   64039 ** Return true if the prepared statement is in need of being reset.
   64040 */
   64041 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
   64042   Vdbe *v = (Vdbe*)pStmt;
   64043   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
   64044 }
   64045 
   64046 /*
   64047 ** Return a pointer to the next prepared statement after pStmt associated
   64048 ** with database connection pDb.  If pStmt is NULL, return the first
   64049 ** prepared statement for the database connection.  Return NULL if there
   64050 ** are no more.
   64051 */
   64052 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   64053   sqlite3_stmt *pNext;
   64054   sqlite3_mutex_enter(pDb->mutex);
   64055   if( pStmt==0 ){
   64056     pNext = (sqlite3_stmt*)pDb->pVdbe;
   64057   }else{
   64058     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   64059   }
   64060   sqlite3_mutex_leave(pDb->mutex);
   64061   return pNext;
   64062 }
   64063 
   64064 /*
   64065 ** Return the value of a status counter for a prepared statement
   64066 */
   64067 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   64068   Vdbe *pVdbe = (Vdbe*)pStmt;
   64069   int v = pVdbe->aCounter[op-1];
   64070   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
   64071   return v;
   64072 }
   64073 
   64074 /************** End of vdbeapi.c *********************************************/
   64075 /************** Begin file vdbetrace.c ***************************************/
   64076 /*
   64077 ** 2009 November 25
   64078 **
   64079 ** The author disclaims copyright to this source code.  In place of
   64080 ** a legal notice, here is a blessing:
   64081 **
   64082 **    May you do good and not evil.
   64083 **    May you find forgiveness for yourself and forgive others.
   64084 **    May you share freely, never taking more than you give.
   64085 **
   64086 *************************************************************************
   64087 **
   64088 ** This file contains code used to insert the values of host parameters
   64089 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   64090 **
   64091 ** The Vdbe parse-tree explainer is also found here.
   64092 */
   64093 
   64094 #ifndef SQLITE_OMIT_TRACE
   64095 
   64096 /*
   64097 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   64098 ** bytes in this text up to but excluding the first character in
   64099 ** a host parameter.  If the text contains no host parameters, return
   64100 ** the total number of bytes in the text.
   64101 */
   64102 static int findNextHostParameter(const char *zSql, int *pnToken){
   64103   int tokenType;
   64104   int nTotal = 0;
   64105   int n;
   64106 
   64107   *pnToken = 0;
   64108   while( zSql[0] ){
   64109     n = sqlite3GetToken((u8*)zSql, &tokenType);
   64110     assert( n>0 && tokenType!=TK_ILLEGAL );
   64111     if( tokenType==TK_VARIABLE ){
   64112       *pnToken = n;
   64113       break;
   64114     }
   64115     nTotal += n;
   64116     zSql += n;
   64117   }
   64118   return nTotal;
   64119 }
   64120 
   64121 /*
   64122 ** This function returns a pointer to a nul-terminated string in memory
   64123 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
   64124 ** string contains a copy of zRawSql but with host parameters expanded to
   64125 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
   64126 ** then the returned string holds a copy of zRawSql with "-- " prepended
   64127 ** to each line of text.
   64128 **
   64129 ** The calling function is responsible for making sure the memory returned
   64130 ** is eventually freed.
   64131 **
   64132 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   64133 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   64134 ** string literals, quoted identifier names, and comments.  For text forms,
   64135 ** the host parameter index is found by scanning the perpared
   64136 ** statement for the corresponding OP_Variable opcode.  Once the host
   64137 ** parameter index is known, locate the value in p->aVar[].  Then render
   64138 ** the value as a literal in place of the host parameter name.
   64139 */
   64140 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   64141   Vdbe *p,                 /* The prepared statement being evaluated */
   64142   const char *zRawSql      /* Raw text of the SQL statement */
   64143 ){
   64144   sqlite3 *db;             /* The database connection */
   64145   int idx = 0;             /* Index of a host parameter */
   64146   int nextIndex = 1;       /* Index of next ? host parameter */
   64147   int n;                   /* Length of a token prefix */
   64148   int nToken;              /* Length of the parameter token */
   64149   int i;                   /* Loop counter */
   64150   Mem *pVar;               /* Value of a host parameter */
   64151   StrAccum out;            /* Accumulate the output here */
   64152   char zBase[100];         /* Initial working space */
   64153 
   64154   db = p->db;
   64155   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   64156                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   64157   out.db = db;
   64158   if( db->vdbeExecCnt>1 ){
   64159     while( *zRawSql ){
   64160       const char *zStart = zRawSql;
   64161       while( *(zRawSql++)!='\n' && *zRawSql );
   64162       sqlite3StrAccumAppend(&out, "-- ", 3);
   64163       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
   64164     }
   64165   }else{
   64166     while( zRawSql[0] ){
   64167       n = findNextHostParameter(zRawSql, &nToken);
   64168       assert( n>0 );
   64169       sqlite3StrAccumAppend(&out, zRawSql, n);
   64170       zRawSql += n;
   64171       assert( zRawSql[0] || nToken==0 );
   64172       if( nToken==0 ) break;
   64173       if( zRawSql[0]=='?' ){
   64174         if( nToken>1 ){
   64175           assert( sqlite3Isdigit(zRawSql[1]) );
   64176           sqlite3GetInt32(&zRawSql[1], &idx);
   64177         }else{
   64178           idx = nextIndex;
   64179         }
   64180       }else{
   64181         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   64182         testcase( zRawSql[0]==':' );
   64183         testcase( zRawSql[0]=='$' );
   64184         testcase( zRawSql[0]=='@' );
   64185         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   64186         assert( idx>0 );
   64187       }
   64188       zRawSql += nToken;
   64189       nextIndex = idx + 1;
   64190       assert( idx>0 && idx<=p->nVar );
   64191       pVar = &p->aVar[idx-1];
   64192       if( pVar->flags & MEM_Null ){
   64193         sqlite3StrAccumAppend(&out, "NULL", 4);
   64194       }else if( pVar->flags & MEM_Int ){
   64195         sqlite3XPrintf(&out, "%lld", pVar->u.i);
   64196       }else if( pVar->flags & MEM_Real ){
   64197         sqlite3XPrintf(&out, "%!.15g", pVar->r);
   64198       }else if( pVar->flags & MEM_Str ){
   64199 #ifndef SQLITE_OMIT_UTF16
   64200         u8 enc = ENC(db);
   64201         if( enc!=SQLITE_UTF8 ){
   64202           Mem utf8;
   64203           memset(&utf8, 0, sizeof(utf8));
   64204           utf8.db = db;
   64205           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   64206           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   64207           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
   64208           sqlite3VdbeMemRelease(&utf8);
   64209         }else
   64210 #endif
   64211         {
   64212           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
   64213         }
   64214       }else if( pVar->flags & MEM_Zero ){
   64215         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
   64216       }else{
   64217         assert( pVar->flags & MEM_Blob );
   64218         sqlite3StrAccumAppend(&out, "x'", 2);
   64219         for(i=0; i<pVar->n; i++){
   64220           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
   64221         }
   64222         sqlite3StrAccumAppend(&out, "'", 1);
   64223       }
   64224     }
   64225   }
   64226   return sqlite3StrAccumFinish(&out);
   64227 }
   64228 
   64229 #endif /* #ifndef SQLITE_OMIT_TRACE */
   64230 
   64231 /*****************************************************************************
   64232 ** The following code implements the data-structure explaining logic
   64233 ** for the Vdbe.
   64234 */
   64235 
   64236 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   64237 
   64238 /*
   64239 ** Allocate a new Explain object
   64240 */
   64241 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
   64242   if( pVdbe ){
   64243     sqlite3BeginBenignMalloc();
   64244     Explain *p = sqlite3_malloc( sizeof(Explain) );
   64245     if( p ){
   64246       memset(p, 0, sizeof(*p));
   64247       p->pVdbe = pVdbe;
   64248       sqlite3_free(pVdbe->pExplain);
   64249       pVdbe->pExplain = p;
   64250       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
   64251                           SQLITE_MAX_LENGTH);
   64252       p->str.useMalloc = 2;
   64253     }else{
   64254       sqlite3EndBenignMalloc();
   64255     }
   64256   }
   64257 }
   64258 
   64259 /*
   64260 ** Return true if the Explain ends with a new-line.
   64261 */
   64262 static int endsWithNL(Explain *p){
   64263   return p && p->str.zText && p->str.nChar
   64264            && p->str.zText[p->str.nChar-1]=='\n';
   64265 }
   64266 
   64267 /*
   64268 ** Append text to the indentation
   64269 */
   64270 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
   64271   Explain *p;
   64272   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   64273     va_list ap;
   64274     if( p->nIndent && endsWithNL(p) ){
   64275       int n = p->nIndent;
   64276       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
   64277       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
   64278     }
   64279     va_start(ap, zFormat);
   64280     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
   64281     va_end(ap);
   64282   }
   64283 }
   64284 
   64285 /*
   64286 ** Append a '\n' if there is not already one.
   64287 */
   64288 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
   64289   Explain *p;
   64290   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
   64291     sqlite3StrAccumAppend(&p->str, "\n", 1);
   64292   }
   64293 }
   64294 
   64295 /*
   64296 ** Push a new indentation level.  Subsequent lines will be indented
   64297 ** so that they begin at the current cursor position.
   64298 */
   64299 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
   64300   Explain *p;
   64301   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
   64302     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
   64303       const char *z = p->str.zText;
   64304       int i = p->str.nChar-1;
   64305       int x;
   64306       while( i>=0 && z[i]!='\n' ){ i--; }
   64307       x = (p->str.nChar - 1) - i;
   64308       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
   64309         x = p->aIndent[p->nIndent-1];
   64310       }
   64311       p->aIndent[p->nIndent] = x;
   64312     }
   64313     p->nIndent++;
   64314   }
   64315 }
   64316 
   64317 /*
   64318 ** Pop the indentation stack by one level.
   64319 */
   64320 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
   64321   if( p && p->pExplain ) p->pExplain->nIndent--;
   64322 }
   64323 
   64324 /*
   64325 ** Free the indentation structure
   64326 */
   64327 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
   64328   if( pVdbe && pVdbe->pExplain ){
   64329     sqlite3_free(pVdbe->zExplain);
   64330     sqlite3ExplainNL(pVdbe);
   64331     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
   64332     sqlite3_free(pVdbe->pExplain);
   64333     pVdbe->pExplain = 0;
   64334     sqlite3EndBenignMalloc();
   64335   }
   64336 }
   64337 
   64338 /*
   64339 ** Return the explanation of a virtual machine.
   64340 */
   64341 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
   64342   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
   64343 }
   64344 #endif /* defined(SQLITE_DEBUG) */
   64345 
   64346 /************** End of vdbetrace.c *******************************************/
   64347 /************** Begin file vdbe.c ********************************************/
   64348 /*
   64349 ** 2001 September 15
   64350 **
   64351 ** The author disclaims copyright to this source code.  In place of
   64352 ** a legal notice, here is a blessing:
   64353 **
   64354 **    May you do good and not evil.
   64355 **    May you find forgiveness for yourself and forgive others.
   64356 **    May you share freely, never taking more than you give.
   64357 **
   64358 *************************************************************************
   64359 ** The code in this file implements execution method of the
   64360 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
   64361 ** handles housekeeping details such as creating and deleting
   64362 ** VDBE instances.  This file is solely interested in executing
   64363 ** the VDBE program.
   64364 **
   64365 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
   64366 ** to a VDBE.
   64367 **
   64368 ** The SQL parser generates a program which is then executed by
   64369 ** the VDBE to do the work of the SQL statement.  VDBE programs are
   64370 ** similar in form to assembly language.  The program consists of
   64371 ** a linear sequence of operations.  Each operation has an opcode
   64372 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
   64373 ** is a null-terminated string.  Operand P5 is an unsigned character.
   64374 ** Few opcodes use all 5 operands.
   64375 **
   64376 ** Computation results are stored on a set of registers numbered beginning
   64377 ** with 1 and going up to Vdbe.nMem.  Each register can store
   64378 ** either an integer, a null-terminated string, a floating point
   64379 ** number, or the SQL "NULL" value.  An implicit conversion from one
   64380 ** type to the other occurs as necessary.
   64381 **
   64382 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
   64383 ** function which does the work of interpreting a VDBE program.
   64384 ** But other routines are also provided to help in building up
   64385 ** a program instruction by instruction.
   64386 **
   64387 ** Various scripts scan this source file in order to generate HTML
   64388 ** documentation, headers files, or other derived files.  The formatting
   64389 ** of the code in this file is, therefore, important.  See other comments
   64390 ** in this file for details.  If in doubt, do not deviate from existing
   64391 ** commenting and indentation practices when changing or adding code.
   64392 */
   64393 
   64394 /*
   64395 ** Invoke this macro on memory cells just prior to changing the
   64396 ** value of the cell.  This macro verifies that shallow copies are
   64397 ** not misused.
   64398 */
   64399 #ifdef SQLITE_DEBUG
   64400 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
   64401 #else
   64402 # define memAboutToChange(P,M)
   64403 #endif
   64404 
   64405 /*
   64406 ** The following global variable is incremented every time a cursor
   64407 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   64408 ** procedures use this information to make sure that indices are
   64409 ** working correctly.  This variable has no function other than to
   64410 ** help verify the correct operation of the library.
   64411 */
   64412 #ifdef SQLITE_TEST
   64413 SQLITE_API int sqlite3_search_count = 0;
   64414 #endif
   64415 
   64416 /*
   64417 ** When this global variable is positive, it gets decremented once before
   64418 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
   64419 ** field of the sqlite3 structure is set in order to simulate an interrupt.
   64420 **
   64421 ** This facility is used for testing purposes only.  It does not function
   64422 ** in an ordinary build.
   64423 */
   64424 #ifdef SQLITE_TEST
   64425 SQLITE_API int sqlite3_interrupt_count = 0;
   64426 #endif
   64427 
   64428 /*
   64429 ** The next global variable is incremented each type the OP_Sort opcode
   64430 ** is executed.  The test procedures use this information to make sure that
   64431 ** sorting is occurring or not occurring at appropriate times.   This variable
   64432 ** has no function other than to help verify the correct operation of the
   64433 ** library.
   64434 */
   64435 #ifdef SQLITE_TEST
   64436 SQLITE_API int sqlite3_sort_count = 0;
   64437 #endif
   64438 
   64439 /*
   64440 ** The next global variable records the size of the largest MEM_Blob
   64441 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   64442 ** use this information to make sure that the zero-blob functionality
   64443 ** is working correctly.   This variable has no function other than to
   64444 ** help verify the correct operation of the library.
   64445 */
   64446 #ifdef SQLITE_TEST
   64447 SQLITE_API int sqlite3_max_blobsize = 0;
   64448 static void updateMaxBlobsize(Mem *p){
   64449   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   64450     sqlite3_max_blobsize = p->n;
   64451   }
   64452 }
   64453 #endif
   64454 
   64455 /*
   64456 ** The next global variable is incremented each type the OP_Found opcode
   64457 ** is executed. This is used to test whether or not the foreign key
   64458 ** operation implemented using OP_FkIsZero is working. This variable
   64459 ** has no function other than to help verify the correct operation of the
   64460 ** library.
   64461 */
   64462 #ifdef SQLITE_TEST
   64463 SQLITE_API int sqlite3_found_count = 0;
   64464 #endif
   64465 
   64466 /*
   64467 ** Test a register to see if it exceeds the current maximum blob size.
   64468 ** If it does, record the new maximum blob size.
   64469 */
   64470 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   64471 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   64472 #else
   64473 # define UPDATE_MAX_BLOBSIZE(P)
   64474 #endif
   64475 
   64476 /*
   64477 ** Convert the given register into a string if it isn't one
   64478 ** already. Return non-zero if a malloc() fails.
   64479 */
   64480 #define Stringify(P, enc) \
   64481    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   64482      { goto no_mem; }
   64483 
   64484 /*
   64485 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   64486 ** a pointer to a dynamically allocated string where some other entity
   64487 ** is responsible for deallocating that string.  Because the register
   64488 ** does not control the string, it might be deleted without the register
   64489 ** knowing it.
   64490 **
   64491 ** This routine converts an ephemeral string into a dynamically allocated
   64492 ** string that the register itself controls.  In other words, it
   64493 ** converts an MEM_Ephem string into an MEM_Dyn string.
   64494 */
   64495 #define Deephemeralize(P) \
   64496    if( ((P)->flags&MEM_Ephem)!=0 \
   64497        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   64498 
   64499 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   64500 #ifdef SQLITE_OMIT_MERGE_SORT
   64501 # define isSorter(x) 0
   64502 #else
   64503 # define isSorter(x) ((x)->pSorter!=0)
   64504 #endif
   64505 
   64506 /*
   64507 ** Argument pMem points at a register that will be passed to a
   64508 ** user-defined function or returned to the user as the result of a query.
   64509 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
   64510 ** routines.
   64511 */
   64512 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
   64513   int flags = pMem->flags;
   64514   if( flags & MEM_Null ){
   64515     pMem->type = SQLITE_NULL;
   64516   }
   64517   else if( flags & MEM_Int ){
   64518     pMem->type = SQLITE_INTEGER;
   64519   }
   64520   else if( flags & MEM_Real ){
   64521     pMem->type = SQLITE_FLOAT;
   64522   }
   64523   else if( flags & MEM_Str ){
   64524     pMem->type = SQLITE_TEXT;
   64525   }else{
   64526     pMem->type = SQLITE_BLOB;
   64527   }
   64528 }
   64529 
   64530 /*
   64531 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   64532 ** if we run out of memory.
   64533 */
   64534 static VdbeCursor *allocateCursor(
   64535   Vdbe *p,              /* The virtual machine */
   64536   int iCur,             /* Index of the new VdbeCursor */
   64537   int nField,           /* Number of fields in the table or index */
   64538   int iDb,              /* Database the cursor belongs to, or -1 */
   64539   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   64540 ){
   64541   /* Find the memory cell that will be used to store the blob of memory
   64542   ** required for this VdbeCursor structure. It is convenient to use a
   64543   ** vdbe memory cell to manage the memory allocation required for a
   64544   ** VdbeCursor structure for the following reasons:
   64545   **
   64546   **   * Sometimes cursor numbers are used for a couple of different
   64547   **     purposes in a vdbe program. The different uses might require
   64548   **     different sized allocations. Memory cells provide growable
   64549   **     allocations.
   64550   **
   64551   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   64552   **     be freed lazily via the sqlite3_release_memory() API. This
   64553   **     minimizes the number of malloc calls made by the system.
   64554   **
   64555   ** Memory cells for cursors are allocated at the top of the address
   64556   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   64557   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   64558   */
   64559   Mem *pMem = &p->aMem[p->nMem-iCur];
   64560 
   64561   int nByte;
   64562   VdbeCursor *pCx = 0;
   64563   nByte =
   64564       ROUND8(sizeof(VdbeCursor)) +
   64565       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
   64566       2*nField*sizeof(u32);
   64567 
   64568   assert( iCur<p->nCursor );
   64569   if( p->apCsr[iCur] ){
   64570     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   64571     p->apCsr[iCur] = 0;
   64572   }
   64573   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   64574     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   64575     memset(pCx, 0, sizeof(VdbeCursor));
   64576     pCx->iDb = iDb;
   64577     pCx->nField = nField;
   64578     if( nField ){
   64579       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
   64580     }
   64581     if( isBtreeCursor ){
   64582       pCx->pCursor = (BtCursor*)
   64583           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
   64584       sqlite3BtreeCursorZero(pCx->pCursor);
   64585     }
   64586   }
   64587   return pCx;
   64588 }
   64589 
   64590 /*
   64591 ** Try to convert a value into a numeric representation if we can
   64592 ** do so without loss of information.  In other words, if the string
   64593 ** looks like a number, convert it into a number.  If it does not
   64594 ** look like a number, leave it alone.
   64595 */
   64596 static void applyNumericAffinity(Mem *pRec){
   64597   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
   64598     double rValue;
   64599     i64 iValue;
   64600     u8 enc = pRec->enc;
   64601     if( (pRec->flags&MEM_Str)==0 ) return;
   64602     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   64603     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   64604       pRec->u.i = iValue;
   64605       pRec->flags |= MEM_Int;
   64606     }else{
   64607       pRec->r = rValue;
   64608       pRec->flags |= MEM_Real;
   64609     }
   64610   }
   64611 }
   64612 
   64613 /*
   64614 ** Processing is determine by the affinity parameter:
   64615 **
   64616 ** SQLITE_AFF_INTEGER:
   64617 ** SQLITE_AFF_REAL:
   64618 ** SQLITE_AFF_NUMERIC:
   64619 **    Try to convert pRec to an integer representation or a
   64620 **    floating-point representation if an integer representation
   64621 **    is not possible.  Note that the integer representation is
   64622 **    always preferred, even if the affinity is REAL, because
   64623 **    an integer representation is more space efficient on disk.
   64624 **
   64625 ** SQLITE_AFF_TEXT:
   64626 **    Convert pRec to a text representation.
   64627 **
   64628 ** SQLITE_AFF_NONE:
   64629 **    No-op.  pRec is unchanged.
   64630 */
   64631 static void applyAffinity(
   64632   Mem *pRec,          /* The value to apply affinity to */
   64633   char affinity,      /* The affinity to be applied */
   64634   u8 enc              /* Use this text encoding */
   64635 ){
   64636   if( affinity==SQLITE_AFF_TEXT ){
   64637     /* Only attempt the conversion to TEXT if there is an integer or real
   64638     ** representation (blob and NULL do not get converted) but no string
   64639     ** representation.
   64640     */
   64641     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   64642       sqlite3VdbeMemStringify(pRec, enc);
   64643     }
   64644     pRec->flags &= ~(MEM_Real|MEM_Int);
   64645   }else if( affinity!=SQLITE_AFF_NONE ){
   64646     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   64647              || affinity==SQLITE_AFF_NUMERIC );
   64648     applyNumericAffinity(pRec);
   64649     if( pRec->flags & MEM_Real ){
   64650       sqlite3VdbeIntegerAffinity(pRec);
   64651     }
   64652   }
   64653 }
   64654 
   64655 /*
   64656 ** Try to convert the type of a function argument or a result column
   64657 ** into a numeric representation.  Use either INTEGER or REAL whichever
   64658 ** is appropriate.  But only do the conversion if it is possible without
   64659 ** loss of information and return the revised type of the argument.
   64660 */
   64661 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   64662   Mem *pMem = (Mem*)pVal;
   64663   if( pMem->type==SQLITE_TEXT ){
   64664     applyNumericAffinity(pMem);
   64665     sqlite3VdbeMemStoreType(pMem);
   64666   }
   64667   return pMem->type;
   64668 }
   64669 
   64670 /*
   64671 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   64672 ** not the internal Mem* type.
   64673 */
   64674 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   64675   sqlite3_value *pVal,
   64676   u8 affinity,
   64677   u8 enc
   64678 ){
   64679   applyAffinity((Mem *)pVal, affinity, enc);
   64680 }
   64681 
   64682 #ifdef SQLITE_DEBUG
   64683 /*
   64684 ** Write a nice string representation of the contents of cell pMem
   64685 ** into buffer zBuf, length nBuf.
   64686 */
   64687 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   64688   char *zCsr = zBuf;
   64689   int f = pMem->flags;
   64690 
   64691   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   64692 
   64693   if( f&MEM_Blob ){
   64694     int i;
   64695     char c;
   64696     if( f & MEM_Dyn ){
   64697       c = 'z';
   64698       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   64699     }else if( f & MEM_Static ){
   64700       c = 't';
   64701       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   64702     }else if( f & MEM_Ephem ){
   64703       c = 'e';
   64704       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   64705     }else{
   64706       c = 's';
   64707     }
   64708 
   64709     sqlite3_snprintf(100, zCsr, "%c", c);
   64710     zCsr += sqlite3Strlen30(zCsr);
   64711     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   64712     zCsr += sqlite3Strlen30(zCsr);
   64713     for(i=0; i<16 && i<pMem->n; i++){
   64714       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   64715       zCsr += sqlite3Strlen30(zCsr);
   64716     }
   64717     for(i=0; i<16 && i<pMem->n; i++){
   64718       char z = pMem->z[i];
   64719       if( z<32 || z>126 ) *zCsr++ = '.';
   64720       else *zCsr++ = z;
   64721     }
   64722 
   64723     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   64724     zCsr += sqlite3Strlen30(zCsr);
   64725     if( f & MEM_Zero ){
   64726       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   64727       zCsr += sqlite3Strlen30(zCsr);
   64728     }
   64729     *zCsr = '\0';
   64730   }else if( f & MEM_Str ){
   64731     int j, k;
   64732     zBuf[0] = ' ';
   64733     if( f & MEM_Dyn ){
   64734       zBuf[1] = 'z';
   64735       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   64736     }else if( f & MEM_Static ){
   64737       zBuf[1] = 't';
   64738       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   64739     }else if( f & MEM_Ephem ){
   64740       zBuf[1] = 'e';
   64741       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   64742     }else{
   64743       zBuf[1] = 's';
   64744     }
   64745     k = 2;
   64746     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   64747     k += sqlite3Strlen30(&zBuf[k]);
   64748     zBuf[k++] = '[';
   64749     for(j=0; j<15 && j<pMem->n; j++){
   64750       u8 c = pMem->z[j];
   64751       if( c>=0x20 && c<0x7f ){
   64752         zBuf[k++] = c;
   64753       }else{
   64754         zBuf[k++] = '.';
   64755       }
   64756     }
   64757     zBuf[k++] = ']';
   64758     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   64759     k += sqlite3Strlen30(&zBuf[k]);
   64760     zBuf[k++] = 0;
   64761   }
   64762 }
   64763 #endif
   64764 
   64765 #ifdef SQLITE_DEBUG
   64766 /*
   64767 ** Print the value of a register for tracing purposes:
   64768 */
   64769 static void memTracePrint(FILE *out, Mem *p){
   64770   if( p->flags & MEM_Null ){
   64771     fprintf(out, " NULL");
   64772   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   64773     fprintf(out, " si:%lld", p->u.i);
   64774   }else if( p->flags & MEM_Int ){
   64775     fprintf(out, " i:%lld", p->u.i);
   64776 #ifndef SQLITE_OMIT_FLOATING_POINT
   64777   }else if( p->flags & MEM_Real ){
   64778     fprintf(out, " r:%g", p->r);
   64779 #endif
   64780   }else if( p->flags & MEM_RowSet ){
   64781     fprintf(out, " (rowset)");
   64782   }else{
   64783     char zBuf[200];
   64784     sqlite3VdbeMemPrettyPrint(p, zBuf);
   64785     fprintf(out, " ");
   64786     fprintf(out, "%s", zBuf);
   64787   }
   64788 }
   64789 static void registerTrace(FILE *out, int iReg, Mem *p){
   64790   fprintf(out, "REG[%d] = ", iReg);
   64791   memTracePrint(out, p);
   64792   fprintf(out, "\n");
   64793 }
   64794 #endif
   64795 
   64796 #ifdef SQLITE_DEBUG
   64797 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
   64798 #else
   64799 #  define REGISTER_TRACE(R,M)
   64800 #endif
   64801 
   64802 
   64803 #ifdef VDBE_PROFILE
   64804 
   64805 /*
   64806 ** hwtime.h contains inline assembler code for implementing
   64807 ** high-performance timing routines.
   64808 */
   64809 /************** Include hwtime.h in the middle of vdbe.c *********************/
   64810 /************** Begin file hwtime.h ******************************************/
   64811 /*
   64812 ** 2008 May 27
   64813 **
   64814 ** The author disclaims copyright to this source code.  In place of
   64815 ** a legal notice, here is a blessing:
   64816 **
   64817 **    May you do good and not evil.
   64818 **    May you find forgiveness for yourself and forgive others.
   64819 **    May you share freely, never taking more than you give.
   64820 **
   64821 ******************************************************************************
   64822 **
   64823 ** This file contains inline asm code for retrieving "high-performance"
   64824 ** counters for x86 class CPUs.
   64825 */
   64826 #ifndef _HWTIME_H_
   64827 #define _HWTIME_H_
   64828 
   64829 /*
   64830 ** The following routine only works on pentium-class (or newer) processors.
   64831 ** It uses the RDTSC opcode to read the cycle count value out of the
   64832 ** processor and returns that value.  This can be used for high-res
   64833 ** profiling.
   64834 */
   64835 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   64836       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   64837 
   64838   #if defined(__GNUC__)
   64839 
   64840   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64841      unsigned int lo, hi;
   64842      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   64843      return (sqlite_uint64)hi << 32 | lo;
   64844   }
   64845 
   64846   #elif defined(_MSC_VER)
   64847 
   64848   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   64849      __asm {
   64850         rdtsc
   64851         ret       ; return value at EDX:EAX
   64852      }
   64853   }
   64854 
   64855   #endif
   64856 
   64857 #elif (defined(__GNUC__) && defined(__x86_64__))
   64858 
   64859   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64860       unsigned long val;
   64861       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   64862       return val;
   64863   }
   64864 
   64865 #elif (defined(__GNUC__) && defined(__ppc__))
   64866 
   64867   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   64868       unsigned long long retval;
   64869       unsigned long junk;
   64870       __asm__ __volatile__ ("\n\
   64871           1:      mftbu   %1\n\
   64872                   mftb    %L0\n\
   64873                   mftbu   %0\n\
   64874                   cmpw    %0,%1\n\
   64875                   bne     1b"
   64876                   : "=r" (retval), "=r" (junk));
   64877       return retval;
   64878   }
   64879 
   64880 #else
   64881 
   64882   #error Need implementation of sqlite3Hwtime() for your platform.
   64883 
   64884   /*
   64885   ** To compile without implementing sqlite3Hwtime() for your platform,
   64886   ** you can remove the above #error and use the following
   64887   ** stub function.  You will lose timing support for many
   64888   ** of the debugging and testing utilities, but it should at
   64889   ** least compile and run.
   64890   */
   64891 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   64892 
   64893 #endif
   64894 
   64895 #endif /* !defined(_HWTIME_H_) */
   64896 
   64897 /************** End of hwtime.h **********************************************/
   64898 /************** Continuing where we left off in vdbe.c ***********************/
   64899 
   64900 #endif
   64901 
   64902 /*
   64903 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
   64904 ** sqlite3_interrupt() routine has been called.  If it has been, then
   64905 ** processing of the VDBE program is interrupted.
   64906 **
   64907 ** This macro added to every instruction that does a jump in order to
   64908 ** implement a loop.  This test used to be on every single instruction,
   64909 ** but that meant we more testing than we needed.  By only testing the
   64910 ** flag on jump instructions, we get a (small) speed improvement.
   64911 */
   64912 #define CHECK_FOR_INTERRUPT \
   64913    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   64914 
   64915 
   64916 #ifndef NDEBUG
   64917 /*
   64918 ** This function is only called from within an assert() expression. It
   64919 ** checks that the sqlite3.nTransaction variable is correctly set to
   64920 ** the number of non-transaction savepoints currently in the
   64921 ** linked list starting at sqlite3.pSavepoint.
   64922 **
   64923 ** Usage:
   64924 **
   64925 **     assert( checkSavepointCount(db) );
   64926 */
   64927 static int checkSavepointCount(sqlite3 *db){
   64928   int n = 0;
   64929   Savepoint *p;
   64930   for(p=db->pSavepoint; p; p=p->pNext) n++;
   64931   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   64932   return 1;
   64933 }
   64934 #endif
   64935 
   64936 /*
   64937 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   64938 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   64939 ** in memory obtained from sqlite3DbMalloc).
   64940 */
   64941 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
   64942   sqlite3 *db = p->db;
   64943   sqlite3DbFree(db, p->zErrMsg);
   64944   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   64945   sqlite3_free(pVtab->zErrMsg);
   64946   pVtab->zErrMsg = 0;
   64947 }
   64948 
   64949 
   64950 /*
   64951 ** Execute as much of a VDBE program as we can then return.
   64952 **
   64953 ** sqlite3VdbeMakeReady() must be called before this routine in order to
   64954 ** close the program with a final OP_Halt and to set up the callbacks
   64955 ** and the error message pointer.
   64956 **
   64957 ** Whenever a row or result data is available, this routine will either
   64958 ** invoke the result callback (if there is one) or return with
   64959 ** SQLITE_ROW.
   64960 **
   64961 ** If an attempt is made to open a locked database, then this routine
   64962 ** will either invoke the busy callback (if there is one) or it will
   64963 ** return SQLITE_BUSY.
   64964 **
   64965 ** If an error occurs, an error message is written to memory obtained
   64966 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
   64967 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
   64968 **
   64969 ** If the callback ever returns non-zero, then the program exits
   64970 ** immediately.  There will be no error message but the p->rc field is
   64971 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
   64972 **
   64973 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
   64974 ** routine to return SQLITE_ERROR.
   64975 **
   64976 ** Other fatal errors return SQLITE_ERROR.
   64977 **
   64978 ** After this routine has finished, sqlite3VdbeFinalize() should be
   64979 ** used to clean up the mess that was left behind.
   64980 */
   64981 SQLITE_PRIVATE int sqlite3VdbeExec(
   64982   Vdbe *p                    /* The VDBE */
   64983 ){
   64984   int pc=0;                  /* The program counter */
   64985   Op *aOp = p->aOp;          /* Copy of p->aOp */
   64986   Op *pOp;                   /* Current operation */
   64987   int rc = SQLITE_OK;        /* Value to return */
   64988   sqlite3 *db = p->db;       /* The database */
   64989   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   64990   u8 encoding = ENC(db);     /* The database encoding */
   64991 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   64992   int checkProgress;         /* True if progress callbacks are enabled */
   64993   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
   64994 #endif
   64995   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   64996   Mem *pIn1 = 0;             /* 1st input operand */
   64997   Mem *pIn2 = 0;             /* 2nd input operand */
   64998   Mem *pIn3 = 0;             /* 3rd input operand */
   64999   Mem *pOut = 0;             /* Output operand */
   65000   int iCompare = 0;          /* Result of last OP_Compare operation */
   65001   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   65002   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
   65003 #ifdef VDBE_PROFILE
   65004   u64 start;                 /* CPU clock count at start of opcode */
   65005   int origPc;                /* Program counter at start of opcode */
   65006 #endif
   65007   /********************************************************************
   65008   ** Automatically generated code
   65009   **
   65010   ** The following union is automatically generated by the
   65011   ** vdbe-compress.tcl script.  The purpose of this union is to
   65012   ** reduce the amount of stack space required by this function.
   65013   ** See comments in the vdbe-compress.tcl script for details.
   65014   */
   65015   union vdbeExecUnion {
   65016     struct OP_Yield_stack_vars {
   65017       int pcDest;
   65018     } aa;
   65019     struct OP_Null_stack_vars {
   65020       int cnt;
   65021     } ab;
   65022     struct OP_Variable_stack_vars {
   65023       Mem *pVar;       /* Value being transferred */
   65024     } ac;
   65025     struct OP_Move_stack_vars {
   65026       char *zMalloc;   /* Holding variable for allocated memory */
   65027       int n;           /* Number of registers left to copy */
   65028       int p1;          /* Register to copy from */
   65029       int p2;          /* Register to copy to */
   65030     } ad;
   65031     struct OP_ResultRow_stack_vars {
   65032       Mem *pMem;
   65033       int i;
   65034     } ae;
   65035     struct OP_Concat_stack_vars {
   65036       i64 nByte;
   65037     } af;
   65038     struct OP_Remainder_stack_vars {
   65039       int flags;      /* Combined MEM_* flags from both inputs */
   65040       i64 iA;         /* Integer value of left operand */
   65041       i64 iB;         /* Integer value of right operand */
   65042       double rA;      /* Real value of left operand */
   65043       double rB;      /* Real value of right operand */
   65044     } ag;
   65045     struct OP_Function_stack_vars {
   65046       int i;
   65047       Mem *pArg;
   65048       sqlite3_context ctx;
   65049       sqlite3_value **apVal;
   65050       int n;
   65051     } ah;
   65052     struct OP_ShiftRight_stack_vars {
   65053       i64 iA;
   65054       u64 uA;
   65055       i64 iB;
   65056       u8 op;
   65057     } ai;
   65058     struct OP_Ge_stack_vars {
   65059       int res;            /* Result of the comparison of pIn1 against pIn3 */
   65060       char affinity;      /* Affinity to use for comparison */
   65061       u16 flags1;         /* Copy of initial value of pIn1->flags */
   65062       u16 flags3;         /* Copy of initial value of pIn3->flags */
   65063     } aj;
   65064     struct OP_Compare_stack_vars {
   65065       int n;
   65066       int i;
   65067       int p1;
   65068       int p2;
   65069       const KeyInfo *pKeyInfo;
   65070       int idx;
   65071       CollSeq *pColl;    /* Collating sequence to use on this term */
   65072       int bRev;          /* True for DESCENDING sort order */
   65073     } ak;
   65074     struct OP_Or_stack_vars {
   65075       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   65076       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   65077     } al;
   65078     struct OP_IfNot_stack_vars {
   65079       int c;
   65080     } am;
   65081     struct OP_Column_stack_vars {
   65082       u32 payloadSize;   /* Number of bytes in the record */
   65083       i64 payloadSize64; /* Number of bytes in the record */
   65084       int p1;            /* P1 value of the opcode */
   65085       int p2;            /* column number to retrieve */
   65086       VdbeCursor *pC;    /* The VDBE cursor */
   65087       char *zRec;        /* Pointer to complete record-data */
   65088       BtCursor *pCrsr;   /* The BTree cursor */
   65089       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   65090       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   65091       int nField;        /* number of fields in the record */
   65092       int len;           /* The length of the serialized data for the column */
   65093       int i;             /* Loop counter */
   65094       char *zData;       /* Part of the record being decoded */
   65095       Mem *pDest;        /* Where to write the extracted value */
   65096       Mem sMem;          /* For storing the record being decoded */
   65097       u8 *zIdx;          /* Index into header */
   65098       u8 *zEndHdr;       /* Pointer to first byte after the header */
   65099       u32 offset;        /* Offset into the data */
   65100       u32 szField;       /* Number of bytes in the content of a field */
   65101       int szHdr;         /* Size of the header size field at start of record */
   65102       int avail;         /* Number of bytes of available data */
   65103       u32 t;             /* A type code from the record header */
   65104       Mem *pReg;         /* PseudoTable input register */
   65105     } an;
   65106     struct OP_Affinity_stack_vars {
   65107       const char *zAffinity;   /* The affinity to be applied */
   65108       char cAff;               /* A single character of affinity */
   65109     } ao;
   65110     struct OP_MakeRecord_stack_vars {
   65111       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   65112       Mem *pRec;             /* The new record */
   65113       u64 nData;             /* Number of bytes of data space */
   65114       int nHdr;              /* Number of bytes of header space */
   65115       i64 nByte;             /* Data space required for this record */
   65116       int nZero;             /* Number of zero bytes at the end of the record */
   65117       int nVarint;           /* Number of bytes in a varint */
   65118       u32 serial_type;       /* Type field */
   65119       Mem *pData0;           /* First field to be combined into the record */
   65120       Mem *pLast;            /* Last field of the record */
   65121       int nField;            /* Number of fields in the record */
   65122       char *zAffinity;       /* The affinity string for the record */
   65123       int file_format;       /* File format to use for encoding */
   65124       int i;                 /* Space used in zNewRecord[] */
   65125       int len;               /* Length of a field */
   65126     } ap;
   65127     struct OP_Count_stack_vars {
   65128       i64 nEntry;
   65129       BtCursor *pCrsr;
   65130     } aq;
   65131     struct OP_Savepoint_stack_vars {
   65132       int p1;                         /* Value of P1 operand */
   65133       char *zName;                    /* Name of savepoint */
   65134       int nName;
   65135       Savepoint *pNew;
   65136       Savepoint *pSavepoint;
   65137       Savepoint *pTmp;
   65138       int iSavepoint;
   65139       int ii;
   65140     } ar;
   65141     struct OP_AutoCommit_stack_vars {
   65142       int desiredAutoCommit;
   65143       int iRollback;
   65144       int turnOnAC;
   65145     } as;
   65146     struct OP_Transaction_stack_vars {
   65147       Btree *pBt;
   65148     } at;
   65149     struct OP_ReadCookie_stack_vars {
   65150       int iMeta;
   65151       int iDb;
   65152       int iCookie;
   65153     } au;
   65154     struct OP_SetCookie_stack_vars {
   65155       Db *pDb;
   65156     } av;
   65157     struct OP_VerifyCookie_stack_vars {
   65158       int iMeta;
   65159       int iGen;
   65160       Btree *pBt;
   65161     } aw;
   65162     struct OP_OpenWrite_stack_vars {
   65163       int nField;
   65164       KeyInfo *pKeyInfo;
   65165       int p2;
   65166       int iDb;
   65167       int wrFlag;
   65168       Btree *pX;
   65169       VdbeCursor *pCur;
   65170       Db *pDb;
   65171     } ax;
   65172     struct OP_OpenEphemeral_stack_vars {
   65173       VdbeCursor *pCx;
   65174     } ay;
   65175     struct OP_SorterOpen_stack_vars {
   65176       VdbeCursor *pCx;
   65177     } az;
   65178     struct OP_OpenPseudo_stack_vars {
   65179       VdbeCursor *pCx;
   65180     } ba;
   65181     struct OP_SeekGt_stack_vars {
   65182       int res;
   65183       int oc;
   65184       VdbeCursor *pC;
   65185       UnpackedRecord r;
   65186       int nField;
   65187       i64 iKey;      /* The rowid we are to seek to */
   65188     } bb;
   65189     struct OP_Seek_stack_vars {
   65190       VdbeCursor *pC;
   65191     } bc;
   65192     struct OP_Found_stack_vars {
   65193       int alreadyExists;
   65194       VdbeCursor *pC;
   65195       int res;
   65196       char *pFree;
   65197       UnpackedRecord *pIdxKey;
   65198       UnpackedRecord r;
   65199       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   65200     } bd;
   65201     struct OP_IsUnique_stack_vars {
   65202       u16 ii;
   65203       VdbeCursor *pCx;
   65204       BtCursor *pCrsr;
   65205       u16 nField;
   65206       Mem *aMx;
   65207       UnpackedRecord r;                  /* B-Tree index search key */
   65208       i64 R;                             /* Rowid stored in register P3 */
   65209     } be;
   65210     struct OP_NotExists_stack_vars {
   65211       VdbeCursor *pC;
   65212       BtCursor *pCrsr;
   65213       int res;
   65214       u64 iKey;
   65215     } bf;
   65216     struct OP_NewRowid_stack_vars {
   65217       i64 v;                 /* The new rowid */
   65218       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   65219       int res;               /* Result of an sqlite3BtreeLast() */
   65220       int cnt;               /* Counter to limit the number of searches */
   65221       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   65222       VdbeFrame *pFrame;     /* Root frame of VDBE */
   65223     } bg;
   65224     struct OP_InsertInt_stack_vars {
   65225       Mem *pData;       /* MEM cell holding data for the record to be inserted */
   65226       Mem *pKey;        /* MEM cell holding key  for the record */
   65227       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   65228       VdbeCursor *pC;   /* Cursor to table into which insert is written */
   65229       int nZero;        /* Number of zero-bytes to append */
   65230       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   65231       const char *zDb;  /* database name - used by the update hook */
   65232       const char *zTbl; /* Table name - used by the opdate hook */
   65233       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   65234     } bh;
   65235     struct OP_Delete_stack_vars {
   65236       i64 iKey;
   65237       VdbeCursor *pC;
   65238     } bi;
   65239     struct OP_SorterCompare_stack_vars {
   65240       VdbeCursor *pC;
   65241       int res;
   65242     } bj;
   65243     struct OP_SorterData_stack_vars {
   65244       VdbeCursor *pC;
   65245     } bk;
   65246     struct OP_RowData_stack_vars {
   65247       VdbeCursor *pC;
   65248       BtCursor *pCrsr;
   65249       u32 n;
   65250       i64 n64;
   65251     } bl;
   65252     struct OP_Rowid_stack_vars {
   65253       VdbeCursor *pC;
   65254       i64 v;
   65255       sqlite3_vtab *pVtab;
   65256       const sqlite3_module *pModule;
   65257     } bm;
   65258     struct OP_NullRow_stack_vars {
   65259       VdbeCursor *pC;
   65260     } bn;
   65261     struct OP_Last_stack_vars {
   65262       VdbeCursor *pC;
   65263       BtCursor *pCrsr;
   65264       int res;
   65265     } bo;
   65266     struct OP_Rewind_stack_vars {
   65267       VdbeCursor *pC;
   65268       BtCursor *pCrsr;
   65269       int res;
   65270     } bp;
   65271     struct OP_Next_stack_vars {
   65272       VdbeCursor *pC;
   65273       int res;
   65274     } bq;
   65275     struct OP_IdxInsert_stack_vars {
   65276       VdbeCursor *pC;
   65277       BtCursor *pCrsr;
   65278       int nKey;
   65279       const char *zKey;
   65280     } br;
   65281     struct OP_IdxDelete_stack_vars {
   65282       VdbeCursor *pC;
   65283       BtCursor *pCrsr;
   65284       int res;
   65285       UnpackedRecord r;
   65286     } bs;
   65287     struct OP_IdxRowid_stack_vars {
   65288       BtCursor *pCrsr;
   65289       VdbeCursor *pC;
   65290       i64 rowid;
   65291     } bt;
   65292     struct OP_IdxGE_stack_vars {
   65293       VdbeCursor *pC;
   65294       int res;
   65295       UnpackedRecord r;
   65296     } bu;
   65297     struct OP_Destroy_stack_vars {
   65298       int iMoved;
   65299       int iCnt;
   65300       Vdbe *pVdbe;
   65301       int iDb;
   65302     } bv;
   65303     struct OP_Clear_stack_vars {
   65304       int nChange;
   65305     } bw;
   65306     struct OP_CreateTable_stack_vars {
   65307       int pgno;
   65308       int flags;
   65309       Db *pDb;
   65310     } bx;
   65311     struct OP_ParseSchema_stack_vars {
   65312       int iDb;
   65313       const char *zMaster;
   65314       char *zSql;
   65315       InitData initData;
   65316     } by;
   65317     struct OP_IntegrityCk_stack_vars {
   65318       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   65319       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   65320       int j;          /* Loop counter */
   65321       int nErr;       /* Number of errors reported */
   65322       char *z;        /* Text of the error report */
   65323       Mem *pnErr;     /* Register keeping track of errors remaining */
   65324     } bz;
   65325     struct OP_RowSetRead_stack_vars {
   65326       i64 val;
   65327     } ca;
   65328     struct OP_RowSetTest_stack_vars {
   65329       int iSet;
   65330       int exists;
   65331     } cb;
   65332     struct OP_Program_stack_vars {
   65333       int nMem;               /* Number of memory registers for sub-program */
   65334       int nByte;              /* Bytes of runtime space required for sub-program */
   65335       Mem *pRt;               /* Register to allocate runtime space */
   65336       Mem *pMem;              /* Used to iterate through memory cells */
   65337       Mem *pEnd;              /* Last memory cell in new array */
   65338       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   65339       SubProgram *pProgram;   /* Sub-program to execute */
   65340       void *t;                /* Token identifying trigger */
   65341     } cc;
   65342     struct OP_Param_stack_vars {
   65343       VdbeFrame *pFrame;
   65344       Mem *pIn;
   65345     } cd;
   65346     struct OP_MemMax_stack_vars {
   65347       Mem *pIn1;
   65348       VdbeFrame *pFrame;
   65349     } ce;
   65350     struct OP_AggStep_stack_vars {
   65351       int n;
   65352       int i;
   65353       Mem *pMem;
   65354       Mem *pRec;
   65355       sqlite3_context ctx;
   65356       sqlite3_value **apVal;
   65357     } cf;
   65358     struct OP_AggFinal_stack_vars {
   65359       Mem *pMem;
   65360     } cg;
   65361     struct OP_Checkpoint_stack_vars {
   65362       int i;                          /* Loop counter */
   65363       int aRes[3];                    /* Results */
   65364       Mem *pMem;                      /* Write results here */
   65365     } ch;
   65366     struct OP_JournalMode_stack_vars {
   65367       Btree *pBt;                     /* Btree to change journal mode of */
   65368       Pager *pPager;                  /* Pager associated with pBt */
   65369       int eNew;                       /* New journal mode */
   65370       int eOld;                       /* The old journal mode */
   65371       const char *zFilename;          /* Name of database file for pPager */
   65372     } ci;
   65373     struct OP_IncrVacuum_stack_vars {
   65374       Btree *pBt;
   65375     } cj;
   65376     struct OP_VBegin_stack_vars {
   65377       VTable *pVTab;
   65378     } ck;
   65379     struct OP_VOpen_stack_vars {
   65380       VdbeCursor *pCur;
   65381       sqlite3_vtab_cursor *pVtabCursor;
   65382       sqlite3_vtab *pVtab;
   65383       sqlite3_module *pModule;
   65384     } cl;
   65385     struct OP_VFilter_stack_vars {
   65386       int nArg;
   65387       int iQuery;
   65388       const sqlite3_module *pModule;
   65389       Mem *pQuery;
   65390       Mem *pArgc;
   65391       sqlite3_vtab_cursor *pVtabCursor;
   65392       sqlite3_vtab *pVtab;
   65393       VdbeCursor *pCur;
   65394       int res;
   65395       int i;
   65396       Mem **apArg;
   65397     } cm;
   65398     struct OP_VColumn_stack_vars {
   65399       sqlite3_vtab *pVtab;
   65400       const sqlite3_module *pModule;
   65401       Mem *pDest;
   65402       sqlite3_context sContext;
   65403     } cn;
   65404     struct OP_VNext_stack_vars {
   65405       sqlite3_vtab *pVtab;
   65406       const sqlite3_module *pModule;
   65407       int res;
   65408       VdbeCursor *pCur;
   65409     } co;
   65410     struct OP_VRename_stack_vars {
   65411       sqlite3_vtab *pVtab;
   65412       Mem *pName;
   65413     } cp;
   65414     struct OP_VUpdate_stack_vars {
   65415       sqlite3_vtab *pVtab;
   65416       sqlite3_module *pModule;
   65417       int nArg;
   65418       int i;
   65419       sqlite_int64 rowid;
   65420       Mem **apArg;
   65421       Mem *pX;
   65422     } cq;
   65423     struct OP_Trace_stack_vars {
   65424       char *zTrace;
   65425       char *z;
   65426     } cr;
   65427   } u;
   65428   /* End automatically generated code
   65429   ********************************************************************/
   65430 
   65431   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   65432   sqlite3VdbeEnter(p);
   65433   if( p->rc==SQLITE_NOMEM ){
   65434     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   65435     ** sqlite3_column_text16() failed.  */
   65436     goto no_mem;
   65437   }
   65438   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   65439   p->rc = SQLITE_OK;
   65440   assert( p->explain==0 );
   65441   p->pResultSet = 0;
   65442   db->busyHandler.nBusy = 0;
   65443   CHECK_FOR_INTERRUPT;
   65444   sqlite3VdbeIOTraceSql(p);
   65445 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   65446   checkProgress = db->xProgress!=0;
   65447 #endif
   65448 #ifdef SQLITE_DEBUG
   65449   sqlite3BeginBenignMalloc();
   65450   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
   65451     int i;
   65452     printf("VDBE Program Listing:\n");
   65453     sqlite3VdbePrintSql(p);
   65454     for(i=0; i<p->nOp; i++){
   65455       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   65456     }
   65457   }
   65458   sqlite3EndBenignMalloc();
   65459 #endif
   65460   for(pc=p->pc; rc==SQLITE_OK; pc++){
   65461     assert( pc>=0 && pc<p->nOp );
   65462     if( db->mallocFailed ) goto no_mem;
   65463 #ifdef VDBE_PROFILE
   65464     origPc = pc;
   65465     start = sqlite3Hwtime();
   65466 #endif
   65467     pOp = &aOp[pc];
   65468 
   65469     /* Only allow tracing if SQLITE_DEBUG is defined.
   65470     */
   65471 #ifdef SQLITE_DEBUG
   65472     if( p->trace ){
   65473       if( pc==0 ){
   65474         printf("VDBE Execution Trace:\n");
   65475         sqlite3VdbePrintSql(p);
   65476       }
   65477       sqlite3VdbePrintOp(p->trace, pc, pOp);
   65478     }
   65479 #endif
   65480 
   65481 
   65482     /* Check to see if we need to simulate an interrupt.  This only happens
   65483     ** if we have a special test build.
   65484     */
   65485 #ifdef SQLITE_TEST
   65486     if( sqlite3_interrupt_count>0 ){
   65487       sqlite3_interrupt_count--;
   65488       if( sqlite3_interrupt_count==0 ){
   65489         sqlite3_interrupt(db);
   65490       }
   65491     }
   65492 #endif
   65493 
   65494 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   65495     /* Call the progress callback if it is configured and the required number
   65496     ** of VDBE ops have been executed (either since this invocation of
   65497     ** sqlite3VdbeExec() or since last time the progress callback was called).
   65498     ** If the progress callback returns non-zero, exit the virtual machine with
   65499     ** a return code SQLITE_ABORT.
   65500     */
   65501     if( checkProgress ){
   65502       if( db->nProgressOps==nProgressOps ){
   65503         int prc;
   65504         prc = db->xProgress(db->pProgressArg);
   65505         if( prc!=0 ){
   65506           rc = SQLITE_INTERRUPT;
   65507           goto vdbe_error_halt;
   65508         }
   65509         nProgressOps = 0;
   65510       }
   65511       nProgressOps++;
   65512     }
   65513 #endif
   65514 
   65515     /* On any opcode with the "out2-prerelase" tag, free any
   65516     ** external allocations out of mem[p2] and set mem[p2] to be
   65517     ** an undefined integer.  Opcodes will either fill in the integer
   65518     ** value or convert mem[p2] to a different type.
   65519     */
   65520     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   65521     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   65522       assert( pOp->p2>0 );
   65523       assert( pOp->p2<=p->nMem );
   65524       pOut = &aMem[pOp->p2];
   65525       memAboutToChange(p, pOut);
   65526       VdbeMemRelease(pOut);
   65527       pOut->flags = MEM_Int;
   65528     }
   65529 
   65530     /* Sanity checking on other operands */
   65531 #ifdef SQLITE_DEBUG
   65532     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   65533       assert( pOp->p1>0 );
   65534       assert( pOp->p1<=p->nMem );
   65535       assert( memIsValid(&aMem[pOp->p1]) );
   65536       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   65537     }
   65538     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   65539       assert( pOp->p2>0 );
   65540       assert( pOp->p2<=p->nMem );
   65541       assert( memIsValid(&aMem[pOp->p2]) );
   65542       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   65543     }
   65544     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   65545       assert( pOp->p3>0 );
   65546       assert( pOp->p3<=p->nMem );
   65547       assert( memIsValid(&aMem[pOp->p3]) );
   65548       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   65549     }
   65550     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   65551       assert( pOp->p2>0 );
   65552       assert( pOp->p2<=p->nMem );
   65553       memAboutToChange(p, &aMem[pOp->p2]);
   65554     }
   65555     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   65556       assert( pOp->p3>0 );
   65557       assert( pOp->p3<=p->nMem );
   65558       memAboutToChange(p, &aMem[pOp->p3]);
   65559     }
   65560 #endif
   65561 
   65562     switch( pOp->opcode ){
   65563 
   65564 /*****************************************************************************
   65565 ** What follows is a massive switch statement where each case implements a
   65566 ** separate instruction in the virtual machine.  If we follow the usual
   65567 ** indentation conventions, each case should be indented by 6 spaces.  But
   65568 ** that is a lot of wasted space on the left margin.  So the code within
   65569 ** the switch statement will break with convention and be flush-left. Another
   65570 ** big comment (similar to this one) will mark the point in the code where
   65571 ** we transition back to normal indentation.
   65572 **
   65573 ** The formatting of each case is important.  The makefile for SQLite
   65574 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   65575 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   65576 ** will be filled with #defines that give unique integer values to each
   65577 ** opcode and the opcodes.c file is filled with an array of strings where
   65578 ** each string is the symbolic name for the corresponding opcode.  If the
   65579 ** case statement is followed by a comment of the form "/# same as ... #/"
   65580 ** that comment is used to determine the particular value of the opcode.
   65581 **
   65582 ** Other keywords in the comment that follows each case are used to
   65583 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   65584 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   65585 ** the mkopcodeh.awk script for additional information.
   65586 **
   65587 ** Documentation about VDBE opcodes is generated by scanning this file
   65588 ** for lines of that contain "Opcode:".  That line and all subsequent
   65589 ** comment lines are used in the generation of the opcode.html documentation
   65590 ** file.
   65591 **
   65592 ** SUMMARY:
   65593 **
   65594 **     Formatting is important to scripts that scan this file.
   65595 **     Do not deviate from the formatting style currently in use.
   65596 **
   65597 *****************************************************************************/
   65598 
   65599 /* Opcode:  Goto * P2 * * *
   65600 **
   65601 ** An unconditional jump to address P2.
   65602 ** The next instruction executed will be
   65603 ** the one at index P2 from the beginning of
   65604 ** the program.
   65605 */
   65606 case OP_Goto: {             /* jump */
   65607   CHECK_FOR_INTERRUPT;
   65608   pc = pOp->p2 - 1;
   65609   break;
   65610 }
   65611 
   65612 /* Opcode:  Gosub P1 P2 * * *
   65613 **
   65614 ** Write the current address onto register P1
   65615 ** and then jump to address P2.
   65616 */
   65617 case OP_Gosub: {            /* jump */
   65618   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   65619   pIn1 = &aMem[pOp->p1];
   65620   assert( (pIn1->flags & MEM_Dyn)==0 );
   65621   memAboutToChange(p, pIn1);
   65622   pIn1->flags = MEM_Int;
   65623   pIn1->u.i = pc;
   65624   REGISTER_TRACE(pOp->p1, pIn1);
   65625   pc = pOp->p2 - 1;
   65626   break;
   65627 }
   65628 
   65629 /* Opcode:  Return P1 * * * *
   65630 **
   65631 ** Jump to the next instruction after the address in register P1.
   65632 */
   65633 case OP_Return: {           /* in1 */
   65634   pIn1 = &aMem[pOp->p1];
   65635   assert( pIn1->flags & MEM_Int );
   65636   pc = (int)pIn1->u.i;
   65637   break;
   65638 }
   65639 
   65640 /* Opcode:  Yield P1 * * * *
   65641 **
   65642 ** Swap the program counter with the value in register P1.
   65643 */
   65644 case OP_Yield: {            /* in1 */
   65645 #if 0  /* local variables moved into u.aa */
   65646   int pcDest;
   65647 #endif /* local variables moved into u.aa */
   65648   pIn1 = &aMem[pOp->p1];
   65649   assert( (pIn1->flags & MEM_Dyn)==0 );
   65650   pIn1->flags = MEM_Int;
   65651   u.aa.pcDest = (int)pIn1->u.i;
   65652   pIn1->u.i = pc;
   65653   REGISTER_TRACE(pOp->p1, pIn1);
   65654   pc = u.aa.pcDest;
   65655   break;
   65656 }
   65657 
   65658 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
   65659 **
   65660 ** Check the value in register P3.  If it is NULL then Halt using
   65661 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   65662 ** value in register P3 is not NULL, then this routine is a no-op.
   65663 */
   65664 case OP_HaltIfNull: {      /* in3 */
   65665   pIn3 = &aMem[pOp->p3];
   65666   if( (pIn3->flags & MEM_Null)==0 ) break;
   65667   /* Fall through into OP_Halt */
   65668 }
   65669 
   65670 /* Opcode:  Halt P1 P2 * P4 *
   65671 **
   65672 ** Exit immediately.  All open cursors, etc are closed
   65673 ** automatically.
   65674 **
   65675 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   65676 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   65677 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   65678 ** whether or not to rollback the current transaction.  Do not rollback
   65679 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   65680 ** then back out all changes that have occurred during this execution of the
   65681 ** VDBE, but do not rollback the transaction.
   65682 **
   65683 ** If P4 is not null then it is an error message string.
   65684 **
   65685 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   65686 ** every program.  So a jump past the last instruction of the program
   65687 ** is the same as executing Halt.
   65688 */
   65689 case OP_Halt: {
   65690   if( pOp->p1==SQLITE_OK && p->pFrame ){
   65691     /* Halt the sub-program. Return control to the parent frame. */
   65692     VdbeFrame *pFrame = p->pFrame;
   65693     p->pFrame = pFrame->pParent;
   65694     p->nFrame--;
   65695     sqlite3VdbeSetChanges(db, p->nChange);
   65696     pc = sqlite3VdbeFrameRestore(pFrame);
   65697     lastRowid = db->lastRowid;
   65698     if( pOp->p2==OE_Ignore ){
   65699       /* Instruction pc is the OP_Program that invoked the sub-program
   65700       ** currently being halted. If the p2 instruction of this OP_Halt
   65701       ** instruction is set to OE_Ignore, then the sub-program is throwing
   65702       ** an IGNORE exception. In this case jump to the address specified
   65703       ** as the p2 of the calling OP_Program.  */
   65704       pc = p->aOp[pc].p2-1;
   65705     }
   65706     aOp = p->aOp;
   65707     aMem = p->aMem;
   65708     break;
   65709   }
   65710 
   65711   p->rc = pOp->p1;
   65712   p->errorAction = (u8)pOp->p2;
   65713   p->pc = pc;
   65714   if( pOp->p4.z ){
   65715     assert( p->rc!=SQLITE_OK );
   65716     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   65717     testcase( sqlite3GlobalConfig.xLog!=0 );
   65718     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
   65719   }else if( p->rc ){
   65720     testcase( sqlite3GlobalConfig.xLog!=0 );
   65721     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
   65722   }
   65723   rc = sqlite3VdbeHalt(p);
   65724   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   65725   if( rc==SQLITE_BUSY ){
   65726     p->rc = rc = SQLITE_BUSY;
   65727   }else{
   65728     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
   65729     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
   65730     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   65731   }
   65732   goto vdbe_return;
   65733 }
   65734 
   65735 /* Opcode: Integer P1 P2 * * *
   65736 **
   65737 ** The 32-bit integer value P1 is written into register P2.
   65738 */
   65739 case OP_Integer: {         /* out2-prerelease */
   65740   pOut->u.i = pOp->p1;
   65741   break;
   65742 }
   65743 
   65744 /* Opcode: Int64 * P2 * P4 *
   65745 **
   65746 ** P4 is a pointer to a 64-bit integer value.
   65747 ** Write that value into register P2.
   65748 */
   65749 case OP_Int64: {           /* out2-prerelease */
   65750   assert( pOp->p4.pI64!=0 );
   65751   pOut->u.i = *pOp->p4.pI64;
   65752   break;
   65753 }
   65754 
   65755 #ifndef SQLITE_OMIT_FLOATING_POINT
   65756 /* Opcode: Real * P2 * P4 *
   65757 **
   65758 ** P4 is a pointer to a 64-bit floating point value.
   65759 ** Write that value into register P2.
   65760 */
   65761 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   65762   pOut->flags = MEM_Real;
   65763   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   65764   pOut->r = *pOp->p4.pReal;
   65765   break;
   65766 }
   65767 #endif
   65768 
   65769 /* Opcode: String8 * P2 * P4 *
   65770 **
   65771 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   65772 ** into an OP_String before it is executed for the first time.
   65773 */
   65774 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   65775   assert( pOp->p4.z!=0 );
   65776   pOp->opcode = OP_String;
   65777   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   65778 
   65779 #ifndef SQLITE_OMIT_UTF16
   65780   if( encoding!=SQLITE_UTF8 ){
   65781     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   65782     if( rc==SQLITE_TOOBIG ) goto too_big;
   65783     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   65784     assert( pOut->zMalloc==pOut->z );
   65785     assert( pOut->flags & MEM_Dyn );
   65786     pOut->zMalloc = 0;
   65787     pOut->flags |= MEM_Static;
   65788     pOut->flags &= ~MEM_Dyn;
   65789     if( pOp->p4type==P4_DYNAMIC ){
   65790       sqlite3DbFree(db, pOp->p4.z);
   65791     }
   65792     pOp->p4type = P4_DYNAMIC;
   65793     pOp->p4.z = pOut->z;
   65794     pOp->p1 = pOut->n;
   65795   }
   65796 #endif
   65797   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   65798     goto too_big;
   65799   }
   65800   /* Fall through to the next case, OP_String */
   65801 }
   65802 
   65803 /* Opcode: String P1 P2 * P4 *
   65804 **
   65805 ** The string value P4 of length P1 (bytes) is stored in register P2.
   65806 */
   65807 case OP_String: {          /* out2-prerelease */
   65808   assert( pOp->p4.z!=0 );
   65809   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   65810   pOut->z = pOp->p4.z;
   65811   pOut->n = pOp->p1;
   65812   pOut->enc = encoding;
   65813   UPDATE_MAX_BLOBSIZE(pOut);
   65814   break;
   65815 }
   65816 
   65817 /* Opcode: Null * P2 P3 * *
   65818 **
   65819 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
   65820 ** NULL into register P3 and ever register in between P2 and P3.  If P3
   65821 ** is less than P2 (typically P3 is zero) then only register P2 is
   65822 ** set to NULL
   65823 */
   65824 case OP_Null: {           /* out2-prerelease */
   65825 #if 0  /* local variables moved into u.ab */
   65826   int cnt;
   65827 #endif /* local variables moved into u.ab */
   65828   u.ab.cnt = pOp->p3-pOp->p2;
   65829   assert( pOp->p3<=p->nMem );
   65830   pOut->flags = MEM_Null;
   65831   while( u.ab.cnt>0 ){
   65832     pOut++;
   65833     memAboutToChange(p, pOut);
   65834     VdbeMemRelease(pOut);
   65835     pOut->flags = MEM_Null;
   65836     u.ab.cnt--;
   65837   }
   65838   break;
   65839 }
   65840 
   65841 
   65842 /* Opcode: Blob P1 P2 * P4
   65843 **
   65844 ** P4 points to a blob of data P1 bytes long.  Store this
   65845 ** blob in register P2.
   65846 */
   65847 case OP_Blob: {                /* out2-prerelease */
   65848   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   65849   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   65850   pOut->enc = encoding;
   65851   UPDATE_MAX_BLOBSIZE(pOut);
   65852   break;
   65853 }
   65854 
   65855 /* Opcode: Variable P1 P2 * P4 *
   65856 **
   65857 ** Transfer the values of bound parameter P1 into register P2
   65858 **
   65859 ** If the parameter is named, then its name appears in P4 and P3==1.
   65860 ** The P4 value is used by sqlite3_bind_parameter_name().
   65861 */
   65862 case OP_Variable: {            /* out2-prerelease */
   65863 #if 0  /* local variables moved into u.ac */
   65864   Mem *pVar;       /* Value being transferred */
   65865 #endif /* local variables moved into u.ac */
   65866 
   65867   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   65868   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
   65869   u.ac.pVar = &p->aVar[pOp->p1 - 1];
   65870   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
   65871     goto too_big;
   65872   }
   65873   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
   65874   UPDATE_MAX_BLOBSIZE(pOut);
   65875   break;
   65876 }
   65877 
   65878 /* Opcode: Move P1 P2 P3 * *
   65879 **
   65880 ** Move the values in register P1..P1+P3-1 over into
   65881 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
   65882 ** left holding a NULL.  It is an error for register ranges
   65883 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
   65884 */
   65885 case OP_Move: {
   65886 #if 0  /* local variables moved into u.ad */
   65887   char *zMalloc;   /* Holding variable for allocated memory */
   65888   int n;           /* Number of registers left to copy */
   65889   int p1;          /* Register to copy from */
   65890   int p2;          /* Register to copy to */
   65891 #endif /* local variables moved into u.ad */
   65892 
   65893   u.ad.n = pOp->p3;
   65894   u.ad.p1 = pOp->p1;
   65895   u.ad.p2 = pOp->p2;
   65896   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
   65897   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
   65898 
   65899   pIn1 = &aMem[u.ad.p1];
   65900   pOut = &aMem[u.ad.p2];
   65901   while( u.ad.n-- ){
   65902     assert( pOut<=&aMem[p->nMem] );
   65903     assert( pIn1<=&aMem[p->nMem] );
   65904     assert( memIsValid(pIn1) );
   65905     memAboutToChange(p, pOut);
   65906     u.ad.zMalloc = pOut->zMalloc;
   65907     pOut->zMalloc = 0;
   65908     sqlite3VdbeMemMove(pOut, pIn1);
   65909 #ifdef SQLITE_DEBUG
   65910     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
   65911       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
   65912     }
   65913 #endif
   65914     pIn1->zMalloc = u.ad.zMalloc;
   65915     REGISTER_TRACE(u.ad.p2++, pOut);
   65916     pIn1++;
   65917     pOut++;
   65918   }
   65919   break;
   65920 }
   65921 
   65922 /* Opcode: Copy P1 P2 * * *
   65923 **
   65924 ** Make a copy of register P1 into register P2.
   65925 **
   65926 ** This instruction makes a deep copy of the value.  A duplicate
   65927 ** is made of any string or blob constant.  See also OP_SCopy.
   65928 */
   65929 case OP_Copy: {             /* in1, out2 */
   65930   pIn1 = &aMem[pOp->p1];
   65931   pOut = &aMem[pOp->p2];
   65932   assert( pOut!=pIn1 );
   65933   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   65934   Deephemeralize(pOut);
   65935   REGISTER_TRACE(pOp->p2, pOut);
   65936   break;
   65937 }
   65938 
   65939 /* Opcode: SCopy P1 P2 * * *
   65940 **
   65941 ** Make a shallow copy of register P1 into register P2.
   65942 **
   65943 ** This instruction makes a shallow copy of the value.  If the value
   65944 ** is a string or blob, then the copy is only a pointer to the
   65945 ** original and hence if the original changes so will the copy.
   65946 ** Worse, if the original is deallocated, the copy becomes invalid.
   65947 ** Thus the program must guarantee that the original will not change
   65948 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   65949 ** copy.
   65950 */
   65951 case OP_SCopy: {            /* in1, out2 */
   65952   pIn1 = &aMem[pOp->p1];
   65953   pOut = &aMem[pOp->p2];
   65954   assert( pOut!=pIn1 );
   65955   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   65956 #ifdef SQLITE_DEBUG
   65957   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   65958 #endif
   65959   REGISTER_TRACE(pOp->p2, pOut);
   65960   break;
   65961 }
   65962 
   65963 /* Opcode: ResultRow P1 P2 * * *
   65964 **
   65965 ** The registers P1 through P1+P2-1 contain a single row of
   65966 ** results. This opcode causes the sqlite3_step() call to terminate
   65967 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   65968 ** structure to provide access to the top P1 values as the result
   65969 ** row.
   65970 */
   65971 case OP_ResultRow: {
   65972 #if 0  /* local variables moved into u.ae */
   65973   Mem *pMem;
   65974   int i;
   65975 #endif /* local variables moved into u.ae */
   65976   assert( p->nResColumn==pOp->p2 );
   65977   assert( pOp->p1>0 );
   65978   assert( pOp->p1+pOp->p2<=p->nMem+1 );
   65979 
   65980   /* If this statement has violated immediate foreign key constraints, do
   65981   ** not return the number of rows modified. And do not RELEASE the statement
   65982   ** transaction. It needs to be rolled back.  */
   65983   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   65984     assert( db->flags&SQLITE_CountRows );
   65985     assert( p->usesStmtJournal );
   65986     break;
   65987   }
   65988 
   65989   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   65990   ** DML statements invoke this opcode to return the number of rows
   65991   ** modified to the user. This is the only way that a VM that
   65992   ** opens a statement transaction may invoke this opcode.
   65993   **
   65994   ** In case this is such a statement, close any statement transaction
   65995   ** opened by this VM before returning control to the user. This is to
   65996   ** ensure that statement-transactions are always nested, not overlapping.
   65997   ** If the open statement-transaction is not closed here, then the user
   65998   ** may step another VM that opens its own statement transaction. This
   65999   ** may lead to overlapping statement transactions.
   66000   **
   66001   ** The statement transaction is never a top-level transaction.  Hence
   66002   ** the RELEASE call below can never fail.
   66003   */
   66004   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   66005   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   66006   if( NEVER(rc!=SQLITE_OK) ){
   66007     break;
   66008   }
   66009 
   66010   /* Invalidate all ephemeral cursor row caches */
   66011   p->cacheCtr = (p->cacheCtr + 2)|1;
   66012 
   66013   /* Make sure the results of the current row are \000 terminated
   66014   ** and have an assigned type.  The results are de-ephemeralized as
   66015   ** a side effect.
   66016   */
   66017   u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
   66018   for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
   66019     assert( memIsValid(&u.ae.pMem[u.ae.i]) );
   66020     Deephemeralize(&u.ae.pMem[u.ae.i]);
   66021     assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
   66022             || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
   66023     sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
   66024     sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
   66025     REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
   66026   }
   66027   if( db->mallocFailed ) goto no_mem;
   66028 
   66029   /* Return SQLITE_ROW
   66030   */
   66031   p->pc = pc + 1;
   66032   rc = SQLITE_ROW;
   66033   goto vdbe_return;
   66034 }
   66035 
   66036 /* Opcode: Concat P1 P2 P3 * *
   66037 **
   66038 ** Add the text in register P1 onto the end of the text in
   66039 ** register P2 and store the result in register P3.
   66040 ** If either the P1 or P2 text are NULL then store NULL in P3.
   66041 **
   66042 **   P3 = P2 || P1
   66043 **
   66044 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   66045 ** if P3 is the same register as P2, the implementation is able
   66046 ** to avoid a memcpy().
   66047 */
   66048 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   66049 #if 0  /* local variables moved into u.af */
   66050   i64 nByte;
   66051 #endif /* local variables moved into u.af */
   66052 
   66053   pIn1 = &aMem[pOp->p1];
   66054   pIn2 = &aMem[pOp->p2];
   66055   pOut = &aMem[pOp->p3];
   66056   assert( pIn1!=pOut );
   66057   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   66058     sqlite3VdbeMemSetNull(pOut);
   66059     break;
   66060   }
   66061   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   66062   Stringify(pIn1, encoding);
   66063   Stringify(pIn2, encoding);
   66064   u.af.nByte = pIn1->n + pIn2->n;
   66065   if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   66066     goto too_big;
   66067   }
   66068   MemSetTypeFlag(pOut, MEM_Str);
   66069   if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
   66070     goto no_mem;
   66071   }
   66072   if( pOut!=pIn2 ){
   66073     memcpy(pOut->z, pIn2->z, pIn2->n);
   66074   }
   66075   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   66076   pOut->z[u.af.nByte] = 0;
   66077   pOut->z[u.af.nByte+1] = 0;
   66078   pOut->flags |= MEM_Term;
   66079   pOut->n = (int)u.af.nByte;
   66080   pOut->enc = encoding;
   66081   UPDATE_MAX_BLOBSIZE(pOut);
   66082   break;
   66083 }
   66084 
   66085 /* Opcode: Add P1 P2 P3 * *
   66086 **
   66087 ** Add the value in register P1 to the value in register P2
   66088 ** and store the result in register P3.
   66089 ** If either input is NULL, the result is NULL.
   66090 */
   66091 /* Opcode: Multiply P1 P2 P3 * *
   66092 **
   66093 **
   66094 ** Multiply the value in register P1 by the value in register P2
   66095 ** and store the result in register P3.
   66096 ** If either input is NULL, the result is NULL.
   66097 */
   66098 /* Opcode: Subtract P1 P2 P3 * *
   66099 **
   66100 ** Subtract the value in register P1 from the value in register P2
   66101 ** and store the result in register P3.
   66102 ** If either input is NULL, the result is NULL.
   66103 */
   66104 /* Opcode: Divide P1 P2 P3 * *
   66105 **
   66106 ** Divide the value in register P1 by the value in register P2
   66107 ** and store the result in register P3 (P3=P2/P1). If the value in
   66108 ** register P1 is zero, then the result is NULL. If either input is
   66109 ** NULL, the result is NULL.
   66110 */
   66111 /* Opcode: Remainder P1 P2 P3 * *
   66112 **
   66113 ** Compute the remainder after integer division of the value in
   66114 ** register P1 by the value in register P2 and store the result in P3.
   66115 ** If the value in register P2 is zero the result is NULL.
   66116 ** If either operand is NULL, the result is NULL.
   66117 */
   66118 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   66119 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   66120 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   66121 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   66122 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   66123 #if 0  /* local variables moved into u.ag */
   66124   int flags;      /* Combined MEM_* flags from both inputs */
   66125   i64 iA;         /* Integer value of left operand */
   66126   i64 iB;         /* Integer value of right operand */
   66127   double rA;      /* Real value of left operand */
   66128   double rB;      /* Real value of right operand */
   66129 #endif /* local variables moved into u.ag */
   66130 
   66131   pIn1 = &aMem[pOp->p1];
   66132   applyNumericAffinity(pIn1);
   66133   pIn2 = &aMem[pOp->p2];
   66134   applyNumericAffinity(pIn2);
   66135   pOut = &aMem[pOp->p3];
   66136   u.ag.flags = pIn1->flags | pIn2->flags;
   66137   if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   66138   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
   66139     u.ag.iA = pIn1->u.i;
   66140     u.ag.iB = pIn2->u.i;
   66141     switch( pOp->opcode ){
   66142       case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66143       case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66144       case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
   66145       case OP_Divide: {
   66146         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66147         if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
   66148         u.ag.iB /= u.ag.iA;
   66149         break;
   66150       }
   66151       default: {
   66152         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66153         if( u.ag.iA==-1 ) u.ag.iA = 1;
   66154         u.ag.iB %= u.ag.iA;
   66155         break;
   66156       }
   66157     }
   66158     pOut->u.i = u.ag.iB;
   66159     MemSetTypeFlag(pOut, MEM_Int);
   66160   }else{
   66161 fp_math:
   66162     u.ag.rA = sqlite3VdbeRealValue(pIn1);
   66163     u.ag.rB = sqlite3VdbeRealValue(pIn2);
   66164     switch( pOp->opcode ){
   66165       case OP_Add:         u.ag.rB += u.ag.rA;       break;
   66166       case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
   66167       case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
   66168       case OP_Divide: {
   66169         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   66170         if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
   66171         u.ag.rB /= u.ag.rA;
   66172         break;
   66173       }
   66174       default: {
   66175         u.ag.iA = (i64)u.ag.rA;
   66176         u.ag.iB = (i64)u.ag.rB;
   66177         if( u.ag.iA==0 ) goto arithmetic_result_is_null;
   66178         if( u.ag.iA==-1 ) u.ag.iA = 1;
   66179         u.ag.rB = (double)(u.ag.iB % u.ag.iA);
   66180         break;
   66181       }
   66182     }
   66183 #ifdef SQLITE_OMIT_FLOATING_POINT
   66184     pOut->u.i = u.ag.rB;
   66185     MemSetTypeFlag(pOut, MEM_Int);
   66186 #else
   66187     if( sqlite3IsNaN(u.ag.rB) ){
   66188       goto arithmetic_result_is_null;
   66189     }
   66190     pOut->r = u.ag.rB;
   66191     MemSetTypeFlag(pOut, MEM_Real);
   66192     if( (u.ag.flags & MEM_Real)==0 ){
   66193       sqlite3VdbeIntegerAffinity(pOut);
   66194     }
   66195 #endif
   66196   }
   66197   break;
   66198 
   66199 arithmetic_result_is_null:
   66200   sqlite3VdbeMemSetNull(pOut);
   66201   break;
   66202 }
   66203 
   66204 /* Opcode: CollSeq P1 * * P4
   66205 **
   66206 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   66207 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   66208 ** be returned. This is used by the built-in min(), max() and nullif()
   66209 ** functions.
   66210 **
   66211 ** If P1 is not zero, then it is a register that a subsequent min() or
   66212 ** max() aggregate will set to 1 if the current row is not the minimum or
   66213 ** maximum.  The P1 register is initialized to 0 by this instruction.
   66214 **
   66215 ** The interface used by the implementation of the aforementioned functions
   66216 ** to retrieve the collation sequence set by this opcode is not available
   66217 ** publicly, only to user functions defined in func.c.
   66218 */
   66219 case OP_CollSeq: {
   66220   assert( pOp->p4type==P4_COLLSEQ );
   66221   if( pOp->p1 ){
   66222     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
   66223   }
   66224   break;
   66225 }
   66226 
   66227 /* Opcode: Function P1 P2 P3 P4 P5
   66228 **
   66229 ** Invoke a user function (P4 is a pointer to a Function structure that
   66230 ** defines the function) with P5 arguments taken from register P2 and
   66231 ** successors.  The result of the function is stored in register P3.
   66232 ** Register P3 must not be one of the function inputs.
   66233 **
   66234 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   66235 ** function was determined to be constant at compile time. If the first
   66236 ** argument was constant then bit 0 of P1 is set. This is used to determine
   66237 ** whether meta data associated with a user function argument using the
   66238 ** sqlite3_set_auxdata() API may be safely retained until the next
   66239 ** invocation of this opcode.
   66240 **
   66241 ** See also: AggStep and AggFinal
   66242 */
   66243 case OP_Function: {
   66244 #if 0  /* local variables moved into u.ah */
   66245   int i;
   66246   Mem *pArg;
   66247   sqlite3_context ctx;
   66248   sqlite3_value **apVal;
   66249   int n;
   66250 #endif /* local variables moved into u.ah */
   66251 
   66252   u.ah.n = pOp->p5;
   66253   u.ah.apVal = p->apArg;
   66254   assert( u.ah.apVal || u.ah.n==0 );
   66255   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   66256   pOut = &aMem[pOp->p3];
   66257   memAboutToChange(p, pOut);
   66258 
   66259   assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
   66260   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
   66261   u.ah.pArg = &aMem[pOp->p2];
   66262   for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
   66263     assert( memIsValid(u.ah.pArg) );
   66264     u.ah.apVal[u.ah.i] = u.ah.pArg;
   66265     Deephemeralize(u.ah.pArg);
   66266     sqlite3VdbeMemStoreType(u.ah.pArg);
   66267     REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
   66268   }
   66269 
   66270   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
   66271   if( pOp->p4type==P4_FUNCDEF ){
   66272     u.ah.ctx.pFunc = pOp->p4.pFunc;
   66273     u.ah.ctx.pVdbeFunc = 0;
   66274   }else{
   66275     u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
   66276     u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
   66277   }
   66278 
   66279   u.ah.ctx.s.flags = MEM_Null;
   66280   u.ah.ctx.s.db = db;
   66281   u.ah.ctx.s.xDel = 0;
   66282   u.ah.ctx.s.zMalloc = 0;
   66283 
   66284   /* The output cell may already have a buffer allocated. Move
   66285   ** the pointer to u.ah.ctx.s so in case the user-function can use
   66286   ** the already allocated buffer instead of allocating a new one.
   66287   */
   66288   sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
   66289   MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
   66290 
   66291   u.ah.ctx.isError = 0;
   66292   if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   66293     assert( pOp>aOp );
   66294     assert( pOp[-1].p4type==P4_COLLSEQ );
   66295     assert( pOp[-1].opcode==OP_CollSeq );
   66296     u.ah.ctx.pColl = pOp[-1].p4.pColl;
   66297   }
   66298   db->lastRowid = lastRowid;
   66299   (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
   66300   lastRowid = db->lastRowid;
   66301 
   66302   /* If any auxiliary data functions have been called by this user function,
   66303   ** immediately call the destructor for any non-static values.
   66304   */
   66305   if( u.ah.ctx.pVdbeFunc ){
   66306     sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
   66307     pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
   66308     pOp->p4type = P4_VDBEFUNC;
   66309   }
   66310 
   66311   if( db->mallocFailed ){
   66312     /* Even though a malloc() has failed, the implementation of the
   66313     ** user function may have called an sqlite3_result_XXX() function
   66314     ** to return a value. The following call releases any resources
   66315     ** associated with such a value.
   66316     */
   66317     sqlite3VdbeMemRelease(&u.ah.ctx.s);
   66318     goto no_mem;
   66319   }
   66320 
   66321   /* If the function returned an error, throw an exception */
   66322   if( u.ah.ctx.isError ){
   66323     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
   66324     rc = u.ah.ctx.isError;
   66325   }
   66326 
   66327   /* Copy the result of the function into register P3 */
   66328   sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
   66329   sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
   66330   if( sqlite3VdbeMemTooBig(pOut) ){
   66331     goto too_big;
   66332   }
   66333 
   66334 #if 0
   66335   /* The app-defined function has done something that as caused this
   66336   ** statement to expire.  (Perhaps the function called sqlite3_exec()
   66337   ** with a CREATE TABLE statement.)
   66338   */
   66339   if( p->expired ) rc = SQLITE_ABORT;
   66340 #endif
   66341 
   66342   REGISTER_TRACE(pOp->p3, pOut);
   66343   UPDATE_MAX_BLOBSIZE(pOut);
   66344   break;
   66345 }
   66346 
   66347 /* Opcode: BitAnd P1 P2 P3 * *
   66348 **
   66349 ** Take the bit-wise AND of the values in register P1 and P2 and
   66350 ** store the result in register P3.
   66351 ** If either input is NULL, the result is NULL.
   66352 */
   66353 /* Opcode: BitOr P1 P2 P3 * *
   66354 **
   66355 ** Take the bit-wise OR of the values in register P1 and P2 and
   66356 ** store the result in register P3.
   66357 ** If either input is NULL, the result is NULL.
   66358 */
   66359 /* Opcode: ShiftLeft P1 P2 P3 * *
   66360 **
   66361 ** Shift the integer value in register P2 to the left by the
   66362 ** number of bits specified by the integer in register P1.
   66363 ** Store the result in register P3.
   66364 ** If either input is NULL, the result is NULL.
   66365 */
   66366 /* Opcode: ShiftRight P1 P2 P3 * *
   66367 **
   66368 ** Shift the integer value in register P2 to the right by the
   66369 ** number of bits specified by the integer in register P1.
   66370 ** Store the result in register P3.
   66371 ** If either input is NULL, the result is NULL.
   66372 */
   66373 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   66374 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   66375 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   66376 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   66377 #if 0  /* local variables moved into u.ai */
   66378   i64 iA;
   66379   u64 uA;
   66380   i64 iB;
   66381   u8 op;
   66382 #endif /* local variables moved into u.ai */
   66383 
   66384   pIn1 = &aMem[pOp->p1];
   66385   pIn2 = &aMem[pOp->p2];
   66386   pOut = &aMem[pOp->p3];
   66387   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   66388     sqlite3VdbeMemSetNull(pOut);
   66389     break;
   66390   }
   66391   u.ai.iA = sqlite3VdbeIntValue(pIn2);
   66392   u.ai.iB = sqlite3VdbeIntValue(pIn1);
   66393   u.ai.op = pOp->opcode;
   66394   if( u.ai.op==OP_BitAnd ){
   66395     u.ai.iA &= u.ai.iB;
   66396   }else if( u.ai.op==OP_BitOr ){
   66397     u.ai.iA |= u.ai.iB;
   66398   }else if( u.ai.iB!=0 ){
   66399     assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
   66400 
   66401     /* If shifting by a negative amount, shift in the other direction */
   66402     if( u.ai.iB<0 ){
   66403       assert( OP_ShiftRight==OP_ShiftLeft+1 );
   66404       u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
   66405       u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
   66406     }
   66407 
   66408     if( u.ai.iB>=64 ){
   66409       u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
   66410     }else{
   66411       memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
   66412       if( u.ai.op==OP_ShiftLeft ){
   66413         u.ai.uA <<= u.ai.iB;
   66414       }else{
   66415         u.ai.uA >>= u.ai.iB;
   66416         /* Sign-extend on a right shift of a negative number */
   66417         if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
   66418       }
   66419       memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
   66420     }
   66421   }
   66422   pOut->u.i = u.ai.iA;
   66423   MemSetTypeFlag(pOut, MEM_Int);
   66424   break;
   66425 }
   66426 
   66427 /* Opcode: AddImm  P1 P2 * * *
   66428 **
   66429 ** Add the constant P2 to the value in register P1.
   66430 ** The result is always an integer.
   66431 **
   66432 ** To force any register to be an integer, just add 0.
   66433 */
   66434 case OP_AddImm: {            /* in1 */
   66435   pIn1 = &aMem[pOp->p1];
   66436   memAboutToChange(p, pIn1);
   66437   sqlite3VdbeMemIntegerify(pIn1);
   66438   pIn1->u.i += pOp->p2;
   66439   break;
   66440 }
   66441 
   66442 /* Opcode: MustBeInt P1 P2 * * *
   66443 **
   66444 ** Force the value in register P1 to be an integer.  If the value
   66445 ** in P1 is not an integer and cannot be converted into an integer
   66446 ** without data loss, then jump immediately to P2, or if P2==0
   66447 ** raise an SQLITE_MISMATCH exception.
   66448 */
   66449 case OP_MustBeInt: {            /* jump, in1 */
   66450   pIn1 = &aMem[pOp->p1];
   66451   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   66452   if( (pIn1->flags & MEM_Int)==0 ){
   66453     if( pOp->p2==0 ){
   66454       rc = SQLITE_MISMATCH;
   66455       goto abort_due_to_error;
   66456     }else{
   66457       pc = pOp->p2 - 1;
   66458     }
   66459   }else{
   66460     MemSetTypeFlag(pIn1, MEM_Int);
   66461   }
   66462   break;
   66463 }
   66464 
   66465 #ifndef SQLITE_OMIT_FLOATING_POINT
   66466 /* Opcode: RealAffinity P1 * * * *
   66467 **
   66468 ** If register P1 holds an integer convert it to a real value.
   66469 **
   66470 ** This opcode is used when extracting information from a column that
   66471 ** has REAL affinity.  Such column values may still be stored as
   66472 ** integers, for space efficiency, but after extraction we want them
   66473 ** to have only a real value.
   66474 */
   66475 case OP_RealAffinity: {                  /* in1 */
   66476   pIn1 = &aMem[pOp->p1];
   66477   if( pIn1->flags & MEM_Int ){
   66478     sqlite3VdbeMemRealify(pIn1);
   66479   }
   66480   break;
   66481 }
   66482 #endif
   66483 
   66484 #ifndef SQLITE_OMIT_CAST
   66485 /* Opcode: ToText P1 * * * *
   66486 **
   66487 ** Force the value in register P1 to be text.
   66488 ** If the value is numeric, convert it to a string using the
   66489 ** equivalent of printf().  Blob values are unchanged and
   66490 ** are afterwards simply interpreted as text.
   66491 **
   66492 ** A NULL value is not changed by this routine.  It remains NULL.
   66493 */
   66494 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   66495   pIn1 = &aMem[pOp->p1];
   66496   memAboutToChange(p, pIn1);
   66497   if( pIn1->flags & MEM_Null ) break;
   66498   assert( MEM_Str==(MEM_Blob>>3) );
   66499   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   66500   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   66501   rc = ExpandBlob(pIn1);
   66502   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   66503   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   66504   UPDATE_MAX_BLOBSIZE(pIn1);
   66505   break;
   66506 }
   66507 
   66508 /* Opcode: ToBlob P1 * * * *
   66509 **
   66510 ** Force the value in register P1 to be a BLOB.
   66511 ** If the value is numeric, convert it to a string first.
   66512 ** Strings are simply reinterpreted as blobs with no change
   66513 ** to the underlying data.
   66514 **
   66515 ** A NULL value is not changed by this routine.  It remains NULL.
   66516 */
   66517 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   66518   pIn1 = &aMem[pOp->p1];
   66519   if( pIn1->flags & MEM_Null ) break;
   66520   if( (pIn1->flags & MEM_Blob)==0 ){
   66521     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   66522     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   66523     MemSetTypeFlag(pIn1, MEM_Blob);
   66524   }else{
   66525     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   66526   }
   66527   UPDATE_MAX_BLOBSIZE(pIn1);
   66528   break;
   66529 }
   66530 
   66531 /* Opcode: ToNumeric P1 * * * *
   66532 **
   66533 ** Force the value in register P1 to be numeric (either an
   66534 ** integer or a floating-point number.)
   66535 ** If the value is text or blob, try to convert it to an using the
   66536 ** equivalent of atoi() or atof() and store 0 if no such conversion
   66537 ** is possible.
   66538 **
   66539 ** A NULL value is not changed by this routine.  It remains NULL.
   66540 */
   66541 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   66542   pIn1 = &aMem[pOp->p1];
   66543   sqlite3VdbeMemNumerify(pIn1);
   66544   break;
   66545 }
   66546 #endif /* SQLITE_OMIT_CAST */
   66547 
   66548 /* Opcode: ToInt P1 * * * *
   66549 **
   66550 ** Force the value in register P1 to be an integer.  If
   66551 ** The value is currently a real number, drop its fractional part.
   66552 ** If the value is text or blob, try to convert it to an integer using the
   66553 ** equivalent of atoi() and store 0 if no such conversion is possible.
   66554 **
   66555 ** A NULL value is not changed by this routine.  It remains NULL.
   66556 */
   66557 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   66558   pIn1 = &aMem[pOp->p1];
   66559   if( (pIn1->flags & MEM_Null)==0 ){
   66560     sqlite3VdbeMemIntegerify(pIn1);
   66561   }
   66562   break;
   66563 }
   66564 
   66565 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
   66566 /* Opcode: ToReal P1 * * * *
   66567 **
   66568 ** Force the value in register P1 to be a floating point number.
   66569 ** If The value is currently an integer, convert it.
   66570 ** If the value is text or blob, try to convert it to an integer using the
   66571 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   66572 **
   66573 ** A NULL value is not changed by this routine.  It remains NULL.
   66574 */
   66575 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   66576   pIn1 = &aMem[pOp->p1];
   66577   memAboutToChange(p, pIn1);
   66578   if( (pIn1->flags & MEM_Null)==0 ){
   66579     sqlite3VdbeMemRealify(pIn1);
   66580   }
   66581   break;
   66582 }
   66583 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
   66584 
   66585 /* Opcode: Lt P1 P2 P3 P4 P5
   66586 **
   66587 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   66588 ** jump to address P2.
   66589 **
   66590 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   66591 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   66592 ** bit is clear then fall through if either operand is NULL.
   66593 **
   66594 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   66595 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   66596 ** to coerce both inputs according to this affinity before the
   66597 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   66598 ** affinity is used. Note that the affinity conversions are stored
   66599 ** back into the input registers P1 and P3.  So this opcode can cause
   66600 ** persistent changes to registers P1 and P3.
   66601 **
   66602 ** Once any conversions have taken place, and neither value is NULL,
   66603 ** the values are compared. If both values are blobs then memcmp() is
   66604 ** used to determine the results of the comparison.  If both values
   66605 ** are text, then the appropriate collating function specified in
   66606 ** P4 is  used to do the comparison.  If P4 is not specified then
   66607 ** memcmp() is used to compare text string.  If both values are
   66608 ** numeric, then a numeric comparison is used. If the two values
   66609 ** are of different types, then numbers are considered less than
   66610 ** strings and strings are considered less than blobs.
   66611 **
   66612 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   66613 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   66614 */
   66615 /* Opcode: Ne P1 P2 P3 P4 P5
   66616 **
   66617 ** This works just like the Lt opcode except that the jump is taken if
   66618 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   66619 ** additional information.
   66620 **
   66621 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   66622 ** true or false and is never NULL.  If both operands are NULL then the result
   66623 ** of comparison is false.  If either operand is NULL then the result is true.
   66624 ** If neither operand is NULL the result is the same as it would be if
   66625 ** the SQLITE_NULLEQ flag were omitted from P5.
   66626 */
   66627 /* Opcode: Eq P1 P2 P3 P4 P5
   66628 **
   66629 ** This works just like the Lt opcode except that the jump is taken if
   66630 ** the operands in registers P1 and P3 are equal.
   66631 ** See the Lt opcode for additional information.
   66632 **
   66633 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   66634 ** true or false and is never NULL.  If both operands are NULL then the result
   66635 ** of comparison is true.  If either operand is NULL then the result is false.
   66636 ** If neither operand is NULL the result is the same as it would be if
   66637 ** the SQLITE_NULLEQ flag were omitted from P5.
   66638 */
   66639 /* Opcode: Le P1 P2 P3 P4 P5
   66640 **
   66641 ** This works just like the Lt opcode except that the jump is taken if
   66642 ** the content of register P3 is less than or equal to the content of
   66643 ** register P1.  See the Lt opcode for additional information.
   66644 */
   66645 /* Opcode: Gt P1 P2 P3 P4 P5
   66646 **
   66647 ** This works just like the Lt opcode except that the jump is taken if
   66648 ** the content of register P3 is greater than the content of
   66649 ** register P1.  See the Lt opcode for additional information.
   66650 */
   66651 /* Opcode: Ge P1 P2 P3 P4 P5
   66652 **
   66653 ** This works just like the Lt opcode except that the jump is taken if
   66654 ** the content of register P3 is greater than or equal to the content of
   66655 ** register P1.  See the Lt opcode for additional information.
   66656 */
   66657 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   66658 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   66659 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   66660 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   66661 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   66662 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   66663 #if 0  /* local variables moved into u.aj */
   66664   int res;            /* Result of the comparison of pIn1 against pIn3 */
   66665   char affinity;      /* Affinity to use for comparison */
   66666   u16 flags1;         /* Copy of initial value of pIn1->flags */
   66667   u16 flags3;         /* Copy of initial value of pIn3->flags */
   66668 #endif /* local variables moved into u.aj */
   66669 
   66670   pIn1 = &aMem[pOp->p1];
   66671   pIn3 = &aMem[pOp->p3];
   66672   u.aj.flags1 = pIn1->flags;
   66673   u.aj.flags3 = pIn3->flags;
   66674   if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
   66675     /* One or both operands are NULL */
   66676     if( pOp->p5 & SQLITE_NULLEQ ){
   66677       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   66678       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   66679       ** or not both operands are null.
   66680       */
   66681       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   66682       u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
   66683     }else{
   66684       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   66685       ** then the result is always NULL.
   66686       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   66687       */
   66688       if( pOp->p5 & SQLITE_STOREP2 ){
   66689         pOut = &aMem[pOp->p2];
   66690         MemSetTypeFlag(pOut, MEM_Null);
   66691         REGISTER_TRACE(pOp->p2, pOut);
   66692       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
   66693         pc = pOp->p2-1;
   66694       }
   66695       break;
   66696     }
   66697   }else{
   66698     /* Neither operand is NULL.  Do a comparison. */
   66699     u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
   66700     if( u.aj.affinity ){
   66701       applyAffinity(pIn1, u.aj.affinity, encoding);
   66702       applyAffinity(pIn3, u.aj.affinity, encoding);
   66703       if( db->mallocFailed ) goto no_mem;
   66704     }
   66705 
   66706     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   66707     ExpandBlob(pIn1);
   66708     ExpandBlob(pIn3);
   66709     u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   66710   }
   66711   switch( pOp->opcode ){
   66712     case OP_Eq:    u.aj.res = u.aj.res==0;     break;
   66713     case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
   66714     case OP_Lt:    u.aj.res = u.aj.res<0;      break;
   66715     case OP_Le:    u.aj.res = u.aj.res<=0;     break;
   66716     case OP_Gt:    u.aj.res = u.aj.res>0;      break;
   66717     default:       u.aj.res = u.aj.res>=0;     break;
   66718   }
   66719 
   66720   if( pOp->p5 & SQLITE_STOREP2 ){
   66721     pOut = &aMem[pOp->p2];
   66722     memAboutToChange(p, pOut);
   66723     MemSetTypeFlag(pOut, MEM_Int);
   66724     pOut->u.i = u.aj.res;
   66725     REGISTER_TRACE(pOp->p2, pOut);
   66726   }else if( u.aj.res ){
   66727     pc = pOp->p2-1;
   66728   }
   66729 
   66730   /* Undo any changes made by applyAffinity() to the input registers. */
   66731   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
   66732   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
   66733   break;
   66734 }
   66735 
   66736 /* Opcode: Permutation * * * P4 *
   66737 **
   66738 ** Set the permutation used by the OP_Compare operator to be the array
   66739 ** of integers in P4.
   66740 **
   66741 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
   66742 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
   66743 ** immediately prior to the OP_Compare.
   66744 */
   66745 case OP_Permutation: {
   66746   assert( pOp->p4type==P4_INTARRAY );
   66747   assert( pOp->p4.ai );
   66748   aPermute = pOp->p4.ai;
   66749   break;
   66750 }
   66751 
   66752 /* Opcode: Compare P1 P2 P3 P4 *
   66753 **
   66754 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   66755 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   66756 ** the comparison for use by the next OP_Jump instruct.
   66757 **
   66758 ** P4 is a KeyInfo structure that defines collating sequences and sort
   66759 ** orders for the comparison.  The permutation applies to registers
   66760 ** only.  The KeyInfo elements are used sequentially.
   66761 **
   66762 ** The comparison is a sort comparison, so NULLs compare equal,
   66763 ** NULLs are less than numbers, numbers are less than strings,
   66764 ** and strings are less than blobs.
   66765 */
   66766 case OP_Compare: {
   66767 #if 0  /* local variables moved into u.ak */
   66768   int n;
   66769   int i;
   66770   int p1;
   66771   int p2;
   66772   const KeyInfo *pKeyInfo;
   66773   int idx;
   66774   CollSeq *pColl;    /* Collating sequence to use on this term */
   66775   int bRev;          /* True for DESCENDING sort order */
   66776 #endif /* local variables moved into u.ak */
   66777 
   66778   u.ak.n = pOp->p3;
   66779   u.ak.pKeyInfo = pOp->p4.pKeyInfo;
   66780   assert( u.ak.n>0 );
   66781   assert( u.ak.pKeyInfo!=0 );
   66782   u.ak.p1 = pOp->p1;
   66783   u.ak.p2 = pOp->p2;
   66784 #if SQLITE_DEBUG
   66785   if( aPermute ){
   66786     int k, mx = 0;
   66787     for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   66788     assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
   66789     assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
   66790   }else{
   66791     assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
   66792     assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
   66793   }
   66794 #endif /* SQLITE_DEBUG */
   66795   for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
   66796     u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
   66797     assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
   66798     assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
   66799     REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
   66800     REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
   66801     assert( u.ak.i<u.ak.pKeyInfo->nField );
   66802     u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
   66803     u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
   66804     iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
   66805     if( iCompare ){
   66806       if( u.ak.bRev ) iCompare = -iCompare;
   66807       break;
   66808     }
   66809   }
   66810   aPermute = 0;
   66811   break;
   66812 }
   66813 
   66814 /* Opcode: Jump P1 P2 P3 * *
   66815 **
   66816 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   66817 ** in the most recent OP_Compare instruction the P1 vector was less than
   66818 ** equal to, or greater than the P2 vector, respectively.
   66819 */
   66820 case OP_Jump: {             /* jump */
   66821   if( iCompare<0 ){
   66822     pc = pOp->p1 - 1;
   66823   }else if( iCompare==0 ){
   66824     pc = pOp->p2 - 1;
   66825   }else{
   66826     pc = pOp->p3 - 1;
   66827   }
   66828   break;
   66829 }
   66830 
   66831 /* Opcode: And P1 P2 P3 * *
   66832 **
   66833 ** Take the logical AND of the values in registers P1 and P2 and
   66834 ** write the result into register P3.
   66835 **
   66836 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   66837 ** the other input is NULL.  A NULL and true or two NULLs give
   66838 ** a NULL output.
   66839 */
   66840 /* Opcode: Or P1 P2 P3 * *
   66841 **
   66842 ** Take the logical OR of the values in register P1 and P2 and
   66843 ** store the answer in register P3.
   66844 **
   66845 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   66846 ** even if the other input is NULL.  A NULL and false or two NULLs
   66847 ** give a NULL output.
   66848 */
   66849 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   66850 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   66851 #if 0  /* local variables moved into u.al */
   66852   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   66853   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   66854 #endif /* local variables moved into u.al */
   66855 
   66856   pIn1 = &aMem[pOp->p1];
   66857   if( pIn1->flags & MEM_Null ){
   66858     u.al.v1 = 2;
   66859   }else{
   66860     u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
   66861   }
   66862   pIn2 = &aMem[pOp->p2];
   66863   if( pIn2->flags & MEM_Null ){
   66864     u.al.v2 = 2;
   66865   }else{
   66866     u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
   66867   }
   66868   if( pOp->opcode==OP_And ){
   66869     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   66870     u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
   66871   }else{
   66872     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   66873     u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
   66874   }
   66875   pOut = &aMem[pOp->p3];
   66876   if( u.al.v1==2 ){
   66877     MemSetTypeFlag(pOut, MEM_Null);
   66878   }else{
   66879     pOut->u.i = u.al.v1;
   66880     MemSetTypeFlag(pOut, MEM_Int);
   66881   }
   66882   break;
   66883 }
   66884 
   66885 /* Opcode: Not P1 P2 * * *
   66886 **
   66887 ** Interpret the value in register P1 as a boolean value.  Store the
   66888 ** boolean complement in register P2.  If the value in register P1 is
   66889 ** NULL, then a NULL is stored in P2.
   66890 */
   66891 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   66892   pIn1 = &aMem[pOp->p1];
   66893   pOut = &aMem[pOp->p2];
   66894   if( pIn1->flags & MEM_Null ){
   66895     sqlite3VdbeMemSetNull(pOut);
   66896   }else{
   66897     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   66898   }
   66899   break;
   66900 }
   66901 
   66902 /* Opcode: BitNot P1 P2 * * *
   66903 **
   66904 ** Interpret the content of register P1 as an integer.  Store the
   66905 ** ones-complement of the P1 value into register P2.  If P1 holds
   66906 ** a NULL then store a NULL in P2.
   66907 */
   66908 case OP_BitNot: {             /* same as TK_BITNOT, 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: Once P1 P2 * * *
   66920 **
   66921 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
   66922 ** set the flag and fall through to the next instruction.
   66923 **
   66924 ** See also: JumpOnce
   66925 */
   66926 case OP_Once: {             /* jump */
   66927   assert( pOp->p1<p->nOnceFlag );
   66928   if( p->aOnceFlag[pOp->p1] ){
   66929     pc = pOp->p2-1;
   66930   }else{
   66931     p->aOnceFlag[pOp->p1] = 1;
   66932   }
   66933   break;
   66934 }
   66935 
   66936 /* Opcode: If P1 P2 P3 * *
   66937 **
   66938 ** Jump to P2 if the value in register P1 is true.  The value
   66939 ** is considered true if it is numeric and non-zero.  If the value
   66940 ** in P1 is NULL then take the jump if P3 is non-zero.
   66941 */
   66942 /* Opcode: IfNot P1 P2 P3 * *
   66943 **
   66944 ** Jump to P2 if the value in register P1 is False.  The value
   66945 ** is considered false if it has a numeric value of zero.  If the value
   66946 ** in P1 is NULL then take the jump if P3 is zero.
   66947 */
   66948 case OP_If:                 /* jump, in1 */
   66949 case OP_IfNot: {            /* jump, in1 */
   66950 #if 0  /* local variables moved into u.am */
   66951   int c;
   66952 #endif /* local variables moved into u.am */
   66953   pIn1 = &aMem[pOp->p1];
   66954   if( pIn1->flags & MEM_Null ){
   66955     u.am.c = pOp->p3;
   66956   }else{
   66957 #ifdef SQLITE_OMIT_FLOATING_POINT
   66958     u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
   66959 #else
   66960     u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
   66961 #endif
   66962     if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
   66963   }
   66964   if( u.am.c ){
   66965     pc = pOp->p2-1;
   66966   }
   66967   break;
   66968 }
   66969 
   66970 /* Opcode: IsNull P1 P2 * * *
   66971 **
   66972 ** Jump to P2 if the value in register P1 is NULL.
   66973 */
   66974 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   66975   pIn1 = &aMem[pOp->p1];
   66976   if( (pIn1->flags & MEM_Null)!=0 ){
   66977     pc = pOp->p2 - 1;
   66978   }
   66979   break;
   66980 }
   66981 
   66982 /* Opcode: NotNull P1 P2 * * *
   66983 **
   66984 ** Jump to P2 if the value in register P1 is not NULL.
   66985 */
   66986 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   66987   pIn1 = &aMem[pOp->p1];
   66988   if( (pIn1->flags & MEM_Null)==0 ){
   66989     pc = pOp->p2 - 1;
   66990   }
   66991   break;
   66992 }
   66993 
   66994 /* Opcode: Column P1 P2 P3 P4 P5
   66995 **
   66996 ** Interpret the data that cursor P1 points to as a structure built using
   66997 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   66998 ** information about the format of the data.)  Extract the P2-th column
   66999 ** from this record.  If there are less that (P2+1)
   67000 ** values in the record, extract a NULL.
   67001 **
   67002 ** The value extracted is stored in register P3.
   67003 **
   67004 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   67005 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   67006 ** the result.
   67007 **
   67008 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   67009 ** then the cache of the cursor is reset prior to extracting the column.
   67010 ** The first OP_Column against a pseudo-table after the value of the content
   67011 ** register has changed should have this bit set.
   67012 */
   67013 case OP_Column: {
   67014 #if 0  /* local variables moved into u.an */
   67015   u32 payloadSize;   /* Number of bytes in the record */
   67016   i64 payloadSize64; /* Number of bytes in the record */
   67017   int p1;            /* P1 value of the opcode */
   67018   int p2;            /* column number to retrieve */
   67019   VdbeCursor *pC;    /* The VDBE cursor */
   67020   char *zRec;        /* Pointer to complete record-data */
   67021   BtCursor *pCrsr;   /* The BTree cursor */
   67022   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   67023   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   67024   int nField;        /* number of fields in the record */
   67025   int len;           /* The length of the serialized data for the column */
   67026   int i;             /* Loop counter */
   67027   char *zData;       /* Part of the record being decoded */
   67028   Mem *pDest;        /* Where to write the extracted value */
   67029   Mem sMem;          /* For storing the record being decoded */
   67030   u8 *zIdx;          /* Index into header */
   67031   u8 *zEndHdr;       /* Pointer to first byte after the header */
   67032   u32 offset;        /* Offset into the data */
   67033   u32 szField;       /* Number of bytes in the content of a field */
   67034   int szHdr;         /* Size of the header size field at start of record */
   67035   int avail;         /* Number of bytes of available data */
   67036   u32 t;             /* A type code from the record header */
   67037   Mem *pReg;         /* PseudoTable input register */
   67038 #endif /* local variables moved into u.an */
   67039 
   67040 
   67041   u.an.p1 = pOp->p1;
   67042   u.an.p2 = pOp->p2;
   67043   u.an.pC = 0;
   67044   memset(&u.an.sMem, 0, sizeof(u.an.sMem));
   67045   assert( u.an.p1<p->nCursor );
   67046   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   67047   u.an.pDest = &aMem[pOp->p3];
   67048   memAboutToChange(p, u.an.pDest);
   67049   u.an.zRec = 0;
   67050 
   67051   /* This block sets the variable u.an.payloadSize to be the total number of
   67052   ** bytes in the record.
   67053   **
   67054   ** u.an.zRec is set to be the complete text of the record if it is available.
   67055   ** The complete record text is always available for pseudo-tables
   67056   ** If the record is stored in a cursor, the complete record text
   67057   ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
   67058   ** If the data is unavailable,  u.an.zRec is set to NULL.
   67059   **
   67060   ** We also compute the number of columns in the record.  For cursors,
   67061   ** the number of columns is stored in the VdbeCursor.nField element.
   67062   */
   67063   u.an.pC = p->apCsr[u.an.p1];
   67064   assert( u.an.pC!=0 );
   67065 #ifndef SQLITE_OMIT_VIRTUALTABLE
   67066   assert( u.an.pC->pVtabCursor==0 );
   67067 #endif
   67068   u.an.pCrsr = u.an.pC->pCursor;
   67069   if( u.an.pCrsr!=0 ){
   67070     /* The record is stored in a B-Tree */
   67071     rc = sqlite3VdbeCursorMoveto(u.an.pC);
   67072     if( rc ) goto abort_due_to_error;
   67073     if( u.an.pC->nullRow ){
   67074       u.an.payloadSize = 0;
   67075     }else if( u.an.pC->cacheStatus==p->cacheCtr ){
   67076       u.an.payloadSize = u.an.pC->payloadSize;
   67077       u.an.zRec = (char*)u.an.pC->aRow;
   67078     }else if( u.an.pC->isIndex ){
   67079       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
   67080       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
   67081       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
   67082       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   67083       ** payload size, so it is impossible for u.an.payloadSize64 to be
   67084       ** larger than 32 bits. */
   67085       assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
   67086       u.an.payloadSize = (u32)u.an.payloadSize64;
   67087     }else{
   67088       assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
   67089       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
   67090       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   67091     }
   67092   }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
   67093     u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
   67094     assert( u.an.pReg->flags & MEM_Blob );
   67095     assert( memIsValid(u.an.pReg) );
   67096     u.an.payloadSize = u.an.pReg->n;
   67097     u.an.zRec = u.an.pReg->z;
   67098     u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
   67099     assert( u.an.payloadSize==0 || u.an.zRec!=0 );
   67100   }else{
   67101     /* Consider the row to be NULL */
   67102     u.an.payloadSize = 0;
   67103   }
   67104 
   67105   /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
   67106   ** nullRow or because of a corrupt database. */
   67107   if( u.an.payloadSize==0 ){
   67108     MemSetTypeFlag(u.an.pDest, MEM_Null);
   67109     goto op_column_out;
   67110   }
   67111   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
   67112   if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   67113     goto too_big;
   67114   }
   67115 
   67116   u.an.nField = u.an.pC->nField;
   67117   assert( u.an.p2<u.an.nField );
   67118 
   67119   /* Read and parse the table header.  Store the results of the parse
   67120   ** into the record header cache fields of the cursor.
   67121   */
   67122   u.an.aType = u.an.pC->aType;
   67123   if( u.an.pC->cacheStatus==p->cacheCtr ){
   67124     u.an.aOffset = u.an.pC->aOffset;
   67125   }else{
   67126     assert(u.an.aType);
   67127     u.an.avail = 0;
   67128     u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
   67129     u.an.pC->payloadSize = u.an.payloadSize;
   67130     u.an.pC->cacheStatus = p->cacheCtr;
   67131 
   67132     /* Figure out how many bytes are in the header */
   67133     if( u.an.zRec ){
   67134       u.an.zData = u.an.zRec;
   67135     }else{
   67136       if( u.an.pC->isIndex ){
   67137         u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
   67138       }else{
   67139         u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
   67140       }
   67141       /* If KeyFetch()/DataFetch() managed to get the entire payload,
   67142       ** save the payload in the u.an.pC->aRow cache.  That will save us from
   67143       ** having to make additional calls to fetch the content portion of
   67144       ** the record.
   67145       */
   67146       assert( u.an.avail>=0 );
   67147       if( u.an.payloadSize <= (u32)u.an.avail ){
   67148         u.an.zRec = u.an.zData;
   67149         u.an.pC->aRow = (u8*)u.an.zData;
   67150       }else{
   67151         u.an.pC->aRow = 0;
   67152       }
   67153     }
   67154     /* The following assert is true in all cases accept when
   67155     ** the database file has been corrupted externally.
   67156     **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
   67157     u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
   67158 
   67159     /* Make sure a corrupt database has not given us an oversize header.
   67160     ** Do this now to avoid an oversize memory allocation.
   67161     **
   67162     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   67163     ** types use so much data space that there can only be 4096 and 32 of
   67164     ** them, respectively.  So the maximum header length results from a
   67165     ** 3-byte type for each of the maximum of 32768 columns plus three
   67166     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   67167     */
   67168     if( u.an.offset > 98307 ){
   67169       rc = SQLITE_CORRUPT_BKPT;
   67170       goto op_column_out;
   67171     }
   67172 
   67173     /* Compute in u.an.len the number of bytes of data we need to read in order
   67174     ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
   67175     ** u.an.nField might be significantly less than the true number of columns
   67176     ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
   67177     ** We want to minimize u.an.len in order to limit the size of the memory
   67178     ** allocation, especially if a corrupt database file has caused u.an.offset
   67179     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
   67180     ** still exceed Robson memory allocation limits on some configurations.
   67181     ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
   67182     ** will likely be much smaller since u.an.nField will likely be less than
   67183     ** 20 or so.  This insures that Robson memory allocation limits are
   67184     ** not exceeded even for corrupt database files.
   67185     */
   67186     u.an.len = u.an.nField*5 + 3;
   67187     if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
   67188 
   67189     /* The KeyFetch() or DataFetch() above are fast and will get the entire
   67190     ** record header in most cases.  But they will fail to get the complete
   67191     ** record header if the record header does not fit on a single page
   67192     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
   67193     ** acquire the complete header text.
   67194     */
   67195     if( !u.an.zRec && u.an.avail<u.an.len ){
   67196       u.an.sMem.flags = 0;
   67197       u.an.sMem.db = 0;
   67198       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
   67199       if( rc!=SQLITE_OK ){
   67200         goto op_column_out;
   67201       }
   67202       u.an.zData = u.an.sMem.z;
   67203     }
   67204     u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
   67205     u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
   67206 
   67207     /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
   67208     ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
   67209     ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
   67210     ** of the record to the start of the data for the u.an.i-th column
   67211     */
   67212     for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
   67213       if( u.an.zIdx<u.an.zEndHdr ){
   67214         u.an.aOffset[u.an.i] = u.an.offset;
   67215         if( u.an.zIdx[0]<0x80 ){
   67216           u.an.t = u.an.zIdx[0];
   67217           u.an.zIdx++;
   67218         }else{
   67219           u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
   67220         }
   67221         u.an.aType[u.an.i] = u.an.t;
   67222         u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
   67223         u.an.offset += u.an.szField;
   67224         if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
   67225           u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   67226           break;
   67227         }
   67228       }else{
   67229         /* If u.an.i is less that u.an.nField, then there are less fields in this
   67230         ** record than SetNumColumns indicated there are columns in the
   67231         ** table. Set the u.an.offset for any extra columns not present in
   67232         ** the record to 0. This tells code below to store a NULL
   67233         ** instead of deserializing a value from the record.
   67234         */
   67235         u.an.aOffset[u.an.i] = 0;
   67236       }
   67237     }
   67238     sqlite3VdbeMemRelease(&u.an.sMem);
   67239     u.an.sMem.flags = MEM_Null;
   67240 
   67241     /* If we have read more header data than was contained in the header,
   67242     ** or if the end of the last field appears to be past the end of the
   67243     ** record, or if the end of the last field appears to be before the end
   67244     ** of the record (when all fields present), then we must be dealing
   67245     ** with a corrupt database.
   67246     */
   67247     if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
   67248          || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
   67249       rc = SQLITE_CORRUPT_BKPT;
   67250       goto op_column_out;
   67251     }
   67252   }
   67253 
   67254   /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
   67255   ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
   67256   ** then there are not enough fields in the record to satisfy the
   67257   ** request.  In this case, set the value NULL or to P4 if P4 is
   67258   ** a pointer to a Mem object.
   67259   */
   67260   if( u.an.aOffset[u.an.p2] ){
   67261     assert( rc==SQLITE_OK );
   67262     if( u.an.zRec ){
   67263       VdbeMemRelease(u.an.pDest);
   67264       sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
   67265     }else{
   67266       u.an.len = sqlite3VdbeSerialTypeLen(u.an.aType[u.an.p2]);
   67267       sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
   67268       rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len, u.an.pC->isIndex, &u.an.sMem);
   67269       if( rc!=SQLITE_OK ){
   67270         goto op_column_out;
   67271       }
   67272       u.an.zData = u.an.sMem.z;
   67273       sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.aType[u.an.p2], u.an.pDest);
   67274     }
   67275     u.an.pDest->enc = encoding;
   67276   }else{
   67277     if( pOp->p4type==P4_MEM ){
   67278       sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
   67279     }else{
   67280       MemSetTypeFlag(u.an.pDest, MEM_Null);
   67281     }
   67282   }
   67283 
   67284   /* If we dynamically allocated space to hold the data (in the
   67285   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   67286   ** dynamically allocated space over to the u.an.pDest structure.
   67287   ** This prevents a memory copy.
   67288   */
   67289   if( u.an.sMem.zMalloc ){
   67290     assert( u.an.sMem.z==u.an.sMem.zMalloc );
   67291     assert( !(u.an.pDest->flags & MEM_Dyn) );
   67292     assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
   67293     u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
   67294     u.an.pDest->flags |= MEM_Term;
   67295     u.an.pDest->z = u.an.sMem.z;
   67296     u.an.pDest->zMalloc = u.an.sMem.zMalloc;
   67297   }
   67298 
   67299   rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
   67300 
   67301 op_column_out:
   67302   UPDATE_MAX_BLOBSIZE(u.an.pDest);
   67303   REGISTER_TRACE(pOp->p3, u.an.pDest);
   67304   break;
   67305 }
   67306 
   67307 /* Opcode: Affinity P1 P2 * P4 *
   67308 **
   67309 ** Apply affinities to a range of P2 registers starting with P1.
   67310 **
   67311 ** P4 is a string that is P2 characters long. The nth character of the
   67312 ** string indicates the column affinity that should be used for the nth
   67313 ** memory cell in the range.
   67314 */
   67315 case OP_Affinity: {
   67316 #if 0  /* local variables moved into u.ao */
   67317   const char *zAffinity;   /* The affinity to be applied */
   67318   char cAff;               /* A single character of affinity */
   67319 #endif /* local variables moved into u.ao */
   67320 
   67321   u.ao.zAffinity = pOp->p4.z;
   67322   assert( u.ao.zAffinity!=0 );
   67323   assert( u.ao.zAffinity[pOp->p2]==0 );
   67324   pIn1 = &aMem[pOp->p1];
   67325   while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
   67326     assert( pIn1 <= &p->aMem[p->nMem] );
   67327     assert( memIsValid(pIn1) );
   67328     ExpandBlob(pIn1);
   67329     applyAffinity(pIn1, u.ao.cAff, encoding);
   67330     pIn1++;
   67331   }
   67332   break;
   67333 }
   67334 
   67335 /* Opcode: MakeRecord P1 P2 P3 P4 *
   67336 **
   67337 ** Convert P2 registers beginning with P1 into the [record format]
   67338 ** use as a data record in a database table or as a key
   67339 ** in an index.  The OP_Column opcode can decode the record later.
   67340 **
   67341 ** P4 may be a string that is P2 characters long.  The nth character of the
   67342 ** string indicates the column affinity that should be used for the nth
   67343 ** field of the index key.
   67344 **
   67345 ** The mapping from character to affinity is given by the SQLITE_AFF_
   67346 ** macros defined in sqliteInt.h.
   67347 **
   67348 ** If P4 is NULL then all index fields have the affinity NONE.
   67349 */
   67350 case OP_MakeRecord: {
   67351 #if 0  /* local variables moved into u.ap */
   67352   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   67353   Mem *pRec;             /* The new record */
   67354   u64 nData;             /* Number of bytes of data space */
   67355   int nHdr;              /* Number of bytes of header space */
   67356   i64 nByte;             /* Data space required for this record */
   67357   int nZero;             /* Number of zero bytes at the end of the record */
   67358   int nVarint;           /* Number of bytes in a varint */
   67359   u32 serial_type;       /* Type field */
   67360   Mem *pData0;           /* First field to be combined into the record */
   67361   Mem *pLast;            /* Last field of the record */
   67362   int nField;            /* Number of fields in the record */
   67363   char *zAffinity;       /* The affinity string for the record */
   67364   int file_format;       /* File format to use for encoding */
   67365   int i;                 /* Space used in zNewRecord[] */
   67366   int len;               /* Length of a field */
   67367 #endif /* local variables moved into u.ap */
   67368 
   67369   /* Assuming the record contains N fields, the record format looks
   67370   ** like this:
   67371   **
   67372   ** ------------------------------------------------------------------------
   67373   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   67374   ** ------------------------------------------------------------------------
   67375   **
   67376   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   67377   ** and so froth.
   67378   **
   67379   ** Each type field is a varint representing the serial type of the
   67380   ** corresponding data element (see sqlite3VdbeSerialType()). The
   67381   ** hdr-size field is also a varint which is the offset from the beginning
   67382   ** of the record to data0.
   67383   */
   67384   u.ap.nData = 0;         /* Number of bytes of data space */
   67385   u.ap.nHdr = 0;          /* Number of bytes of header space */
   67386   u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
   67387   u.ap.nField = pOp->p1;
   67388   u.ap.zAffinity = pOp->p4.z;
   67389   assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
   67390   u.ap.pData0 = &aMem[u.ap.nField];
   67391   u.ap.nField = pOp->p2;
   67392   u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
   67393   u.ap.file_format = p->minWriteFileFormat;
   67394 
   67395   /* Identify the output register */
   67396   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   67397   pOut = &aMem[pOp->p3];
   67398   memAboutToChange(p, pOut);
   67399 
   67400   /* Loop through the elements that will make up the record to figure
   67401   ** out how much space is required for the new record.
   67402   */
   67403   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
   67404     assert( memIsValid(u.ap.pRec) );
   67405     if( u.ap.zAffinity ){
   67406       applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
   67407     }
   67408     if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
   67409       sqlite3VdbeMemExpandBlob(u.ap.pRec);
   67410     }
   67411     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
   67412     u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
   67413     u.ap.nData += u.ap.len;
   67414     u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
   67415     if( u.ap.pRec->flags & MEM_Zero ){
   67416       /* Only pure zero-filled BLOBs can be input to this Opcode.
   67417       ** We do not allow blobs with a prefix and a zero-filled tail. */
   67418       u.ap.nZero += u.ap.pRec->u.nZero;
   67419     }else if( u.ap.len ){
   67420       u.ap.nZero = 0;
   67421     }
   67422   }
   67423 
   67424   /* Add the initial header varint and total the size */
   67425   u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
   67426   if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
   67427     u.ap.nHdr++;
   67428   }
   67429   u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
   67430   if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   67431     goto too_big;
   67432   }
   67433 
   67434   /* Make sure the output register has a buffer large enough to store
   67435   ** the new record. The output register (pOp->p3) is not allowed to
   67436   ** be one of the input registers (because the following call to
   67437   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   67438   */
   67439   if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
   67440     goto no_mem;
   67441   }
   67442   u.ap.zNewRecord = (u8 *)pOut->z;
   67443 
   67444   /* Write the record */
   67445   u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
   67446   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
   67447     u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
   67448     u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
   67449   }
   67450   for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
   67451     u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
   67452   }
   67453   assert( u.ap.i==u.ap.nByte );
   67454 
   67455   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   67456   pOut->n = (int)u.ap.nByte;
   67457   pOut->flags = MEM_Blob | MEM_Dyn;
   67458   pOut->xDel = 0;
   67459   if( u.ap.nZero ){
   67460     pOut->u.nZero = u.ap.nZero;
   67461     pOut->flags |= MEM_Zero;
   67462   }
   67463   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   67464   REGISTER_TRACE(pOp->p3, pOut);
   67465   UPDATE_MAX_BLOBSIZE(pOut);
   67466   break;
   67467 }
   67468 
   67469 /* Opcode: Count P1 P2 * * *
   67470 **
   67471 ** Store the number of entries (an integer value) in the table or index
   67472 ** opened by cursor P1 in register P2
   67473 */
   67474 #ifndef SQLITE_OMIT_BTREECOUNT
   67475 case OP_Count: {         /* out2-prerelease */
   67476 #if 0  /* local variables moved into u.aq */
   67477   i64 nEntry;
   67478   BtCursor *pCrsr;
   67479 #endif /* local variables moved into u.aq */
   67480 
   67481   u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
   67482   if( ALWAYS(u.aq.pCrsr) ){
   67483     rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
   67484   }else{
   67485     u.aq.nEntry = 0;
   67486   }
   67487   pOut->u.i = u.aq.nEntry;
   67488   break;
   67489 }
   67490 #endif
   67491 
   67492 /* Opcode: Savepoint P1 * * P4 *
   67493 **
   67494 ** Open, release or rollback the savepoint named by parameter P4, depending
   67495 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   67496 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   67497 */
   67498 case OP_Savepoint: {
   67499 #if 0  /* local variables moved into u.ar */
   67500   int p1;                         /* Value of P1 operand */
   67501   char *zName;                    /* Name of savepoint */
   67502   int nName;
   67503   Savepoint *pNew;
   67504   Savepoint *pSavepoint;
   67505   Savepoint *pTmp;
   67506   int iSavepoint;
   67507   int ii;
   67508 #endif /* local variables moved into u.ar */
   67509 
   67510   u.ar.p1 = pOp->p1;
   67511   u.ar.zName = pOp->p4.z;
   67512 
   67513   /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
   67514   ** transaction, then there cannot be any savepoints.
   67515   */
   67516   assert( db->pSavepoint==0 || db->autoCommit==0 );
   67517   assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
   67518   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   67519   assert( checkSavepointCount(db) );
   67520 
   67521   if( u.ar.p1==SAVEPOINT_BEGIN ){
   67522     if( db->writeVdbeCnt>0 ){
   67523       /* A new savepoint cannot be created if there are active write
   67524       ** statements (i.e. open read/write incremental blob handles).
   67525       */
   67526       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   67527         "SQL statements in progress");
   67528       rc = SQLITE_BUSY;
   67529     }else{
   67530       u.ar.nName = sqlite3Strlen30(u.ar.zName);
   67531 
   67532 #ifndef SQLITE_OMIT_VIRTUALTABLE
   67533       /* This call is Ok even if this savepoint is actually a transaction
   67534       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
   67535       ** If this is a transaction savepoint being opened, it is guaranteed
   67536       ** that the db->aVTrans[] array is empty.  */
   67537       assert( db->autoCommit==0 || db->nVTrans==0 );
   67538       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
   67539                                 db->nStatement+db->nSavepoint);
   67540       if( rc!=SQLITE_OK ) goto abort_due_to_error;
   67541 #endif
   67542 
   67543       /* Create a new savepoint structure. */
   67544       u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
   67545       if( u.ar.pNew ){
   67546         u.ar.pNew->zName = (char *)&u.ar.pNew[1];
   67547         memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
   67548 
   67549         /* If there is no open transaction, then mark this as a special
   67550         ** "transaction savepoint". */
   67551         if( db->autoCommit ){
   67552           db->autoCommit = 0;
   67553           db->isTransactionSavepoint = 1;
   67554         }else{
   67555           db->nSavepoint++;
   67556         }
   67557 
   67558         /* Link the new savepoint into the database handle's list. */
   67559         u.ar.pNew->pNext = db->pSavepoint;
   67560         db->pSavepoint = u.ar.pNew;
   67561         u.ar.pNew->nDeferredCons = db->nDeferredCons;
   67562       }
   67563     }
   67564   }else{
   67565     u.ar.iSavepoint = 0;
   67566 
   67567     /* Find the named savepoint. If there is no such savepoint, then an
   67568     ** an error is returned to the user.  */
   67569     for(
   67570       u.ar.pSavepoint = db->pSavepoint;
   67571       u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
   67572       u.ar.pSavepoint = u.ar.pSavepoint->pNext
   67573     ){
   67574       u.ar.iSavepoint++;
   67575     }
   67576     if( !u.ar.pSavepoint ){
   67577       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
   67578       rc = SQLITE_ERROR;
   67579     }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
   67580       /* It is not possible to release (commit) a savepoint if there are
   67581       ** active write statements.
   67582       */
   67583       sqlite3SetString(&p->zErrMsg, db,
   67584         "cannot release savepoint - SQL statements in progress"
   67585       );
   67586       rc = SQLITE_BUSY;
   67587     }else{
   67588 
   67589       /* Determine whether or not this is a transaction savepoint. If so,
   67590       ** and this is a RELEASE command, then the current transaction
   67591       ** is committed.
   67592       */
   67593       int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
   67594       if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
   67595         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   67596           goto vdbe_return;
   67597         }
   67598         db->autoCommit = 1;
   67599         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   67600           p->pc = pc;
   67601           db->autoCommit = 0;
   67602           p->rc = rc = SQLITE_BUSY;
   67603           goto vdbe_return;
   67604         }
   67605         db->isTransactionSavepoint = 0;
   67606         rc = p->rc;
   67607       }else{
   67608         u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
   67609         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
   67610           sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
   67611         }
   67612         for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
   67613           rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
   67614           if( rc!=SQLITE_OK ){
   67615             goto abort_due_to_error;
   67616           }
   67617         }
   67618         if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   67619           sqlite3ExpirePreparedStatements(db);
   67620           sqlite3ResetInternalSchema(db, -1);
   67621           db->flags = (db->flags | SQLITE_InternChanges);
   67622         }
   67623       }
   67624 
   67625       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   67626       ** savepoints nested inside of the savepoint being operated on. */
   67627       while( db->pSavepoint!=u.ar.pSavepoint ){
   67628         u.ar.pTmp = db->pSavepoint;
   67629         db->pSavepoint = u.ar.pTmp->pNext;
   67630         sqlite3DbFree(db, u.ar.pTmp);
   67631         db->nSavepoint--;
   67632       }
   67633 
   67634       /* If it is a RELEASE, then destroy the savepoint being operated on
   67635       ** too. If it is a ROLLBACK TO, then set the number of deferred
   67636       ** constraint violations present in the database to the value stored
   67637       ** when the savepoint was created.  */
   67638       if( u.ar.p1==SAVEPOINT_RELEASE ){
   67639         assert( u.ar.pSavepoint==db->pSavepoint );
   67640         db->pSavepoint = u.ar.pSavepoint->pNext;
   67641         sqlite3DbFree(db, u.ar.pSavepoint);
   67642         if( !isTransaction ){
   67643           db->nSavepoint--;
   67644         }
   67645       }else{
   67646         db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
   67647       }
   67648 
   67649       if( !isTransaction ){
   67650         rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
   67651         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   67652       }
   67653     }
   67654   }
   67655 
   67656   break;
   67657 }
   67658 
   67659 /* Opcode: AutoCommit P1 P2 * * *
   67660 **
   67661 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   67662 ** back any currently active btree transactions. If there are any active
   67663 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   67664 ** there are active writing VMs or active VMs that use shared cache.
   67665 **
   67666 ** This instruction causes the VM to halt.
   67667 */
   67668 case OP_AutoCommit: {
   67669 #if 0  /* local variables moved into u.as */
   67670   int desiredAutoCommit;
   67671   int iRollback;
   67672   int turnOnAC;
   67673 #endif /* local variables moved into u.as */
   67674 
   67675   u.as.desiredAutoCommit = pOp->p1;
   67676   u.as.iRollback = pOp->p2;
   67677   u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
   67678   assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
   67679   assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
   67680   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
   67681 
   67682 #if 0
   67683   if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
   67684     /* If this instruction implements a ROLLBACK and other VMs are
   67685     ** still running, and a transaction is active, return an error indicating
   67686     ** that the other VMs must complete first.
   67687     */
   67688     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   67689         "SQL statements in progress");
   67690     rc = SQLITE_BUSY;
   67691   }else
   67692 #endif
   67693   if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
   67694     /* If this instruction implements a COMMIT and other VMs are writing
   67695     ** return an error indicating that the other VMs must complete first.
   67696     */
   67697     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   67698         "SQL statements in progress");
   67699     rc = SQLITE_BUSY;
   67700   }else if( u.as.desiredAutoCommit!=db->autoCommit ){
   67701     if( u.as.iRollback ){
   67702       assert( u.as.desiredAutoCommit==1 );
   67703       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
   67704       db->autoCommit = 1;
   67705     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   67706       goto vdbe_return;
   67707     }else{
   67708       db->autoCommit = (u8)u.as.desiredAutoCommit;
   67709       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   67710         p->pc = pc;
   67711         db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
   67712         p->rc = rc = SQLITE_BUSY;
   67713         goto vdbe_return;
   67714       }
   67715     }
   67716     assert( db->nStatement==0 );
   67717     sqlite3CloseSavepoints(db);
   67718     if( p->rc==SQLITE_OK ){
   67719       rc = SQLITE_DONE;
   67720     }else{
   67721       rc = SQLITE_ERROR;
   67722     }
   67723     goto vdbe_return;
   67724   }else{
   67725     sqlite3SetString(&p->zErrMsg, db,
   67726         (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
   67727         (u.as.iRollback)?"cannot rollback - no transaction is active":
   67728                    "cannot commit - no transaction is active"));
   67729 
   67730     rc = SQLITE_ERROR;
   67731   }
   67732   break;
   67733 }
   67734 
   67735 /* Opcode: Transaction P1 P2 * * *
   67736 **
   67737 ** Begin a transaction.  The transaction ends when a Commit or Rollback
   67738 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
   67739 ** transaction might also be rolled back if an error is encountered.
   67740 **
   67741 ** P1 is the index of the database file on which the transaction is
   67742 ** started.  Index 0 is the main database file and index 1 is the
   67743 ** file used for temporary tables.  Indices of 2 or more are used for
   67744 ** attached databases.
   67745 **
   67746 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
   67747 ** obtained on the database file when a write-transaction is started.  No
   67748 ** other process can start another write transaction while this transaction is
   67749 ** underway.  Starting a write transaction also creates a rollback journal. A
   67750 ** write transaction must be started before any changes can be made to the
   67751 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
   67752 ** on the file.
   67753 **
   67754 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   67755 ** true (this flag is set if the Vdbe may modify more than one row and may
   67756 ** throw an ABORT exception), a statement transaction may also be opened.
   67757 ** More specifically, a statement transaction is opened iff the database
   67758 ** connection is currently not in autocommit mode, or if there are other
   67759 ** active statements. A statement transaction allows the changes made by this
   67760 ** VDBE to be rolled back after an error without having to roll back the
   67761 ** entire transaction. If no error is encountered, the statement transaction
   67762 ** will automatically commit when the VDBE halts.
   67763 **
   67764 ** If P2 is zero, then a read-lock is obtained on the database file.
   67765 */
   67766 case OP_Transaction: {
   67767 #if 0  /* local variables moved into u.at */
   67768   Btree *pBt;
   67769 #endif /* local variables moved into u.at */
   67770 
   67771   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67772   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67773   u.at.pBt = db->aDb[pOp->p1].pBt;
   67774 
   67775   if( u.at.pBt ){
   67776     rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
   67777     if( rc==SQLITE_BUSY ){
   67778       p->pc = pc;
   67779       p->rc = rc = SQLITE_BUSY;
   67780       goto vdbe_return;
   67781     }
   67782     if( rc!=SQLITE_OK ){
   67783       goto abort_due_to_error;
   67784     }
   67785 
   67786     if( pOp->p2 && p->usesStmtJournal
   67787      && (db->autoCommit==0 || db->activeVdbeCnt>1)
   67788     ){
   67789       assert( sqlite3BtreeIsInTrans(u.at.pBt) );
   67790       if( p->iStatement==0 ){
   67791         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   67792         db->nStatement++;
   67793         p->iStatement = db->nSavepoint + db->nStatement;
   67794       }
   67795 
   67796       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
   67797       if( rc==SQLITE_OK ){
   67798         rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
   67799       }
   67800 
   67801       /* Store the current value of the database handles deferred constraint
   67802       ** counter. If the statement transaction needs to be rolled back,
   67803       ** the value of this counter needs to be restored too.  */
   67804       p->nStmtDefCons = db->nDeferredCons;
   67805     }
   67806   }
   67807   break;
   67808 }
   67809 
   67810 /* Opcode: ReadCookie P1 P2 P3 * *
   67811 **
   67812 ** Read cookie number P3 from database P1 and write it into register P2.
   67813 ** P3==1 is the schema version.  P3==2 is the database format.
   67814 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   67815 ** the main database file and P1==1 is the database file used to store
   67816 ** temporary tables.
   67817 **
   67818 ** There must be a read-lock on the database (either a transaction
   67819 ** must be started or there must be an open cursor) before
   67820 ** executing this instruction.
   67821 */
   67822 case OP_ReadCookie: {               /* out2-prerelease */
   67823 #if 0  /* local variables moved into u.au */
   67824   int iMeta;
   67825   int iDb;
   67826   int iCookie;
   67827 #endif /* local variables moved into u.au */
   67828 
   67829   u.au.iDb = pOp->p1;
   67830   u.au.iCookie = pOp->p3;
   67831   assert( pOp->p3<SQLITE_N_BTREE_META );
   67832   assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
   67833   assert( db->aDb[u.au.iDb].pBt!=0 );
   67834   assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
   67835 
   67836   sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
   67837   pOut->u.i = u.au.iMeta;
   67838   break;
   67839 }
   67840 
   67841 /* Opcode: SetCookie P1 P2 P3 * *
   67842 **
   67843 ** Write the content of register P3 (interpreted as an integer)
   67844 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   67845 ** P2==2 is the database format. P2==3 is the recommended pager cache
   67846 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   67847 ** database file used to store temporary tables.
   67848 **
   67849 ** A transaction must be started before executing this opcode.
   67850 */
   67851 case OP_SetCookie: {       /* in3 */
   67852 #if 0  /* local variables moved into u.av */
   67853   Db *pDb;
   67854 #endif /* local variables moved into u.av */
   67855   assert( pOp->p2<SQLITE_N_BTREE_META );
   67856   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67857   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67858   u.av.pDb = &db->aDb[pOp->p1];
   67859   assert( u.av.pDb->pBt!=0 );
   67860   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   67861   pIn3 = &aMem[pOp->p3];
   67862   sqlite3VdbeMemIntegerify(pIn3);
   67863   /* See note about index shifting on OP_ReadCookie */
   67864   rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
   67865   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   67866     /* When the schema cookie changes, record the new cookie internally */
   67867     u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   67868     db->flags |= SQLITE_InternChanges;
   67869   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   67870     /* Record changes in the file format */
   67871     u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
   67872   }
   67873   if( pOp->p1==1 ){
   67874     /* Invalidate all prepared statements whenever the TEMP database
   67875     ** schema is changed.  Ticket #1644 */
   67876     sqlite3ExpirePreparedStatements(db);
   67877     p->expired = 0;
   67878   }
   67879   break;
   67880 }
   67881 
   67882 /* Opcode: VerifyCookie P1 P2 P3 * *
   67883 **
   67884 ** Check the value of global database parameter number 0 (the
   67885 ** schema version) and make sure it is equal to P2 and that the
   67886 ** generation counter on the local schema parse equals P3.
   67887 **
   67888 ** P1 is the database number which is 0 for the main database file
   67889 ** and 1 for the file holding temporary tables and some higher number
   67890 ** for auxiliary databases.
   67891 **
   67892 ** The cookie changes its value whenever the database schema changes.
   67893 ** This operation is used to detect when that the cookie has changed
   67894 ** and that the current process needs to reread the schema.
   67895 **
   67896 ** Either a transaction needs to have been started or an OP_Open needs
   67897 ** to be executed (to establish a read lock) before this opcode is
   67898 ** invoked.
   67899 */
   67900 case OP_VerifyCookie: {
   67901 #if 0  /* local variables moved into u.aw */
   67902   int iMeta;
   67903   int iGen;
   67904   Btree *pBt;
   67905 #endif /* local variables moved into u.aw */
   67906 
   67907   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   67908   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   67909   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
   67910   u.aw.pBt = db->aDb[pOp->p1].pBt;
   67911   if( u.aw.pBt ){
   67912     sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
   67913     u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
   67914   }else{
   67915     u.aw.iGen = u.aw.iMeta = 0;
   67916   }
   67917   if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
   67918     sqlite3DbFree(db, p->zErrMsg);
   67919     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   67920     /* If the schema-cookie from the database file matches the cookie
   67921     ** stored with the in-memory representation of the schema, do
   67922     ** not reload the schema from the database file.
   67923     **
   67924     ** If virtual-tables are in use, this is not just an optimization.
   67925     ** Often, v-tables store their data in other SQLite tables, which
   67926     ** are queried from within xNext() and other v-table methods using
   67927     ** prepared queries. If such a query is out-of-date, we do not want to
   67928     ** discard the database schema, as the user code implementing the
   67929     ** v-table would have to be ready for the sqlite3_vtab structure itself
   67930     ** to be invalidated whenever sqlite3_step() is called from within
   67931     ** a v-table method.
   67932     */
   67933     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
   67934       sqlite3ResetInternalSchema(db, pOp->p1);
   67935     }
   67936 
   67937     p->expired = 1;
   67938     rc = SQLITE_SCHEMA;
   67939   }
   67940   break;
   67941 }
   67942 
   67943 /* Opcode: OpenRead P1 P2 P3 P4 P5
   67944 **
   67945 ** Open a read-only cursor for the database table whose root page is
   67946 ** P2 in a database file.  The database file is determined by P3.
   67947 ** P3==0 means the main database, P3==1 means the database used for
   67948 ** temporary tables, and P3>1 means used the corresponding attached
   67949 ** database.  Give the new cursor an identifier of P1.  The P1
   67950 ** values need not be contiguous but all P1 values should be small integers.
   67951 ** It is an error for P1 to be negative.
   67952 **
   67953 ** If P5!=0 then use the content of register P2 as the root page, not
   67954 ** the value of P2 itself.
   67955 **
   67956 ** There will be a read lock on the database whenever there is an
   67957 ** open cursor.  If the database was unlocked prior to this instruction
   67958 ** then a read lock is acquired as part of this instruction.  A read
   67959 ** lock allows other processes to read the database but prohibits
   67960 ** any other process from modifying the database.  The read lock is
   67961 ** released when all cursors are closed.  If this instruction attempts
   67962 ** to get a read lock but fails, the script terminates with an
   67963 ** SQLITE_BUSY error code.
   67964 **
   67965 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   67966 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   67967 ** structure, then said structure defines the content and collating
   67968 ** sequence of the index being opened. Otherwise, if P4 is an integer
   67969 ** value, it is set to the number of columns in the table.
   67970 **
   67971 ** See also OpenWrite.
   67972 */
   67973 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   67974 **
   67975 ** Open a read/write cursor named P1 on the table or index whose root
   67976 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   67977 ** root page.
   67978 **
   67979 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   67980 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   67981 ** structure, then said structure defines the content and collating
   67982 ** sequence of the index being opened. Otherwise, if P4 is an integer
   67983 ** value, it is set to the number of columns in the table, or to the
   67984 ** largest index of any column of the table that is actually used.
   67985 **
   67986 ** This instruction works just like OpenRead except that it opens the cursor
   67987 ** in read/write mode.  For a given table, there can be one or more read-only
   67988 ** cursors or a single read/write cursor but not both.
   67989 **
   67990 ** See also OpenRead.
   67991 */
   67992 case OP_OpenRead:
   67993 case OP_OpenWrite: {
   67994 #if 0  /* local variables moved into u.ax */
   67995   int nField;
   67996   KeyInfo *pKeyInfo;
   67997   int p2;
   67998   int iDb;
   67999   int wrFlag;
   68000   Btree *pX;
   68001   VdbeCursor *pCur;
   68002   Db *pDb;
   68003 #endif /* local variables moved into u.ax */
   68004 
   68005   if( p->expired ){
   68006     rc = SQLITE_ABORT;
   68007     break;
   68008   }
   68009 
   68010   u.ax.nField = 0;
   68011   u.ax.pKeyInfo = 0;
   68012   u.ax.p2 = pOp->p2;
   68013   u.ax.iDb = pOp->p3;
   68014   assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
   68015   assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
   68016   u.ax.pDb = &db->aDb[u.ax.iDb];
   68017   u.ax.pX = u.ax.pDb->pBt;
   68018   assert( u.ax.pX!=0 );
   68019   if( pOp->opcode==OP_OpenWrite ){
   68020     u.ax.wrFlag = 1;
   68021     assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
   68022     if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
   68023       p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
   68024     }
   68025   }else{
   68026     u.ax.wrFlag = 0;
   68027   }
   68028   if( pOp->p5 ){
   68029     assert( u.ax.p2>0 );
   68030     assert( u.ax.p2<=p->nMem );
   68031     pIn2 = &aMem[u.ax.p2];
   68032     assert( memIsValid(pIn2) );
   68033     assert( (pIn2->flags & MEM_Int)!=0 );
   68034     sqlite3VdbeMemIntegerify(pIn2);
   68035     u.ax.p2 = (int)pIn2->u.i;
   68036     /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
   68037     ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
   68038     ** If there were a failure, the prepared statement would have halted
   68039     ** before reaching this instruction. */
   68040     if( NEVER(u.ax.p2<2) ) {
   68041       rc = SQLITE_CORRUPT_BKPT;
   68042       goto abort_due_to_error;
   68043     }
   68044   }
   68045   if( pOp->p4type==P4_KEYINFO ){
   68046     u.ax.pKeyInfo = pOp->p4.pKeyInfo;
   68047     u.ax.pKeyInfo->enc = ENC(p->db);
   68048     u.ax.nField = u.ax.pKeyInfo->nField+1;
   68049   }else if( pOp->p4type==P4_INT32 ){
   68050     u.ax.nField = pOp->p4.i;
   68051   }
   68052   assert( pOp->p1>=0 );
   68053   u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
   68054   if( u.ax.pCur==0 ) goto no_mem;
   68055   u.ax.pCur->nullRow = 1;
   68056   u.ax.pCur->isOrdered = 1;
   68057   rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
   68058   u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
   68059 
   68060   /* Since it performs no memory allocation or IO, the only value that
   68061   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
   68062   assert( rc==SQLITE_OK );
   68063 
   68064   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
   68065   ** SQLite used to check if the root-page flags were sane at this point
   68066   ** and report database corruption if they were not, but this check has
   68067   ** since moved into the btree layer.  */
   68068   u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
   68069   u.ax.pCur->isIndex = !u.ax.pCur->isTable;
   68070   break;
   68071 }
   68072 
   68073 /* Opcode: OpenEphemeral P1 P2 * P4 P5
   68074 **
   68075 ** Open a new cursor P1 to a transient table.
   68076 ** The cursor is always opened read/write even if
   68077 ** the main database is read-only.  The ephemeral
   68078 ** table is deleted automatically when the cursor is closed.
   68079 **
   68080 ** P2 is the number of columns in the ephemeral table.
   68081 ** The cursor points to a BTree table if P4==0 and to a BTree index
   68082 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   68083 ** that defines the format of keys in the index.
   68084 **
   68085 ** This opcode was once called OpenTemp.  But that created
   68086 ** confusion because the term "temp table", might refer either
   68087 ** to a TEMP table at the SQL level, or to a table opened by
   68088 ** this opcode.  Then this opcode was call OpenVirtual.  But
   68089 ** that created confusion with the whole virtual-table idea.
   68090 **
   68091 ** The P5 parameter can be a mask of the BTREE_* flags defined
   68092 ** in btree.h.  These flags control aspects of the operation of
   68093 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
   68094 ** added automatically.
   68095 */
   68096 /* Opcode: OpenAutoindex P1 P2 * P4 *
   68097 **
   68098 ** This opcode works the same as OP_OpenEphemeral.  It has a
   68099 ** different name to distinguish its use.  Tables created using
   68100 ** by this opcode will be used for automatically created transient
   68101 ** indices in joins.
   68102 */
   68103 case OP_OpenAutoindex:
   68104 case OP_OpenEphemeral: {
   68105 #if 0  /* local variables moved into u.ay */
   68106   VdbeCursor *pCx;
   68107 #endif /* local variables moved into u.ay */
   68108   static const int vfsFlags =
   68109       SQLITE_OPEN_READWRITE |
   68110       SQLITE_OPEN_CREATE |
   68111       SQLITE_OPEN_EXCLUSIVE |
   68112       SQLITE_OPEN_DELETEONCLOSE |
   68113       SQLITE_OPEN_TRANSIENT_DB;
   68114 
   68115   assert( pOp->p1>=0 );
   68116   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   68117   if( u.ay.pCx==0 ) goto no_mem;
   68118   u.ay.pCx->nullRow = 1;
   68119   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
   68120                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   68121   if( rc==SQLITE_OK ){
   68122     rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
   68123   }
   68124   if( rc==SQLITE_OK ){
   68125     /* If a transient index is required, create it by calling
   68126     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   68127     ** opening it. If a transient table is required, just use the
   68128     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   68129     */
   68130     if( pOp->p4.pKeyInfo ){
   68131       int pgno;
   68132       assert( pOp->p4type==P4_KEYINFO );
   68133       rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
   68134       if( rc==SQLITE_OK ){
   68135         assert( pgno==MASTER_ROOT+1 );
   68136         rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
   68137                                 (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
   68138         u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   68139         u.ay.pCx->pKeyInfo->enc = ENC(p->db);
   68140       }
   68141       u.ay.pCx->isTable = 0;
   68142     }else{
   68143       rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
   68144       u.ay.pCx->isTable = 1;
   68145     }
   68146   }
   68147   u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   68148   u.ay.pCx->isIndex = !u.ay.pCx->isTable;
   68149   break;
   68150 }
   68151 
   68152 /* Opcode: OpenSorter P1 P2 * P4 *
   68153 **
   68154 ** This opcode works like OP_OpenEphemeral except that it opens
   68155 ** a transient index that is specifically designed to sort large
   68156 ** tables using an external merge-sort algorithm.
   68157 */
   68158 case OP_SorterOpen: {
   68159 #if 0  /* local variables moved into u.az */
   68160   VdbeCursor *pCx;
   68161 #endif /* local variables moved into u.az */
   68162 #ifndef SQLITE_OMIT_MERGE_SORT
   68163   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   68164   if( u.az.pCx==0 ) goto no_mem;
   68165   u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   68166   u.az.pCx->pKeyInfo->enc = ENC(p->db);
   68167   u.az.pCx->isSorter = 1;
   68168   rc = sqlite3VdbeSorterInit(db, u.az.pCx);
   68169 #else
   68170   pOp->opcode = OP_OpenEphemeral;
   68171   pc--;
   68172 #endif
   68173   break;
   68174 }
   68175 
   68176 /* Opcode: OpenPseudo P1 P2 P3 * *
   68177 **
   68178 ** Open a new cursor that points to a fake table that contains a single
   68179 ** row of data.  The content of that one row in the content of memory
   68180 ** register P2.  In other words, cursor P1 becomes an alias for the
   68181 ** MEM_Blob content contained in register P2.
   68182 **
   68183 ** A pseudo-table created by this opcode is used to hold a single
   68184 ** row output from the sorter so that the row can be decomposed into
   68185 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   68186 ** is the only cursor opcode that works with a pseudo-table.
   68187 **
   68188 ** P3 is the number of fields in the records that will be stored by
   68189 ** the pseudo-table.
   68190 */
   68191 case OP_OpenPseudo: {
   68192 #if 0  /* local variables moved into u.ba */
   68193   VdbeCursor *pCx;
   68194 #endif /* local variables moved into u.ba */
   68195 
   68196   assert( pOp->p1>=0 );
   68197   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   68198   if( u.ba.pCx==0 ) goto no_mem;
   68199   u.ba.pCx->nullRow = 1;
   68200   u.ba.pCx->pseudoTableReg = pOp->p2;
   68201   u.ba.pCx->isTable = 1;
   68202   u.ba.pCx->isIndex = 0;
   68203   break;
   68204 }
   68205 
   68206 /* Opcode: Close P1 * * * *
   68207 **
   68208 ** Close a cursor previously opened as P1.  If P1 is not
   68209 ** currently open, this instruction is a no-op.
   68210 */
   68211 case OP_Close: {
   68212   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68213   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   68214   p->apCsr[pOp->p1] = 0;
   68215   break;
   68216 }
   68217 
   68218 /* Opcode: SeekGe P1 P2 P3 P4 *
   68219 **
   68220 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68221 ** use the value in register P3 as the key.  If cursor P1 refers
   68222 ** to an SQL index, then P3 is the first in an array of P4 registers
   68223 ** that are used as an unpacked index key.
   68224 **
   68225 ** Reposition cursor P1 so that  it points to the smallest entry that
   68226 ** is greater than or equal to the key value. If there are no records
   68227 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   68228 **
   68229 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
   68230 */
   68231 /* Opcode: SeekGt P1 P2 P3 P4 *
   68232 **
   68233 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68234 ** use the value in register P3 as a key. If cursor P1 refers
   68235 ** to an SQL index, then P3 is the first in an array of P4 registers
   68236 ** that are used as an unpacked index key.
   68237 **
   68238 ** Reposition cursor P1 so that  it points to the smallest entry that
   68239 ** is greater than the key value. If there are no records greater than
   68240 ** the key and P2 is not zero, then jump to P2.
   68241 **
   68242 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
   68243 */
   68244 /* Opcode: SeekLt P1 P2 P3 P4 *
   68245 **
   68246 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68247 ** use the value in register P3 as a key. If cursor P1 refers
   68248 ** to an SQL index, then P3 is the first in an array of P4 registers
   68249 ** that are used as an unpacked index key.
   68250 **
   68251 ** Reposition cursor P1 so that  it points to the largest entry that
   68252 ** is less than the key value. If there are no records less than
   68253 ** the key and P2 is not zero, then jump to P2.
   68254 **
   68255 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
   68256 */
   68257 /* Opcode: SeekLe P1 P2 P3 P4 *
   68258 **
   68259 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   68260 ** use the value in register P3 as a key. If cursor P1 refers
   68261 ** to an SQL index, then P3 is the first in an array of P4 registers
   68262 ** that are used as an unpacked index key.
   68263 **
   68264 ** Reposition cursor P1 so that it points to the largest entry that
   68265 ** is less than or equal to the key value. If there are no records
   68266 ** less than or equal to the key and P2 is not zero, then jump to P2.
   68267 **
   68268 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
   68269 */
   68270 case OP_SeekLt:         /* jump, in3 */
   68271 case OP_SeekLe:         /* jump, in3 */
   68272 case OP_SeekGe:         /* jump, in3 */
   68273 case OP_SeekGt: {       /* jump, in3 */
   68274 #if 0  /* local variables moved into u.bb */
   68275   int res;
   68276   int oc;
   68277   VdbeCursor *pC;
   68278   UnpackedRecord r;
   68279   int nField;
   68280   i64 iKey;      /* The rowid we are to seek to */
   68281 #endif /* local variables moved into u.bb */
   68282 
   68283   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68284   assert( pOp->p2!=0 );
   68285   u.bb.pC = p->apCsr[pOp->p1];
   68286   assert( u.bb.pC!=0 );
   68287   assert( u.bb.pC->pseudoTableReg==0 );
   68288   assert( OP_SeekLe == OP_SeekLt+1 );
   68289   assert( OP_SeekGe == OP_SeekLt+2 );
   68290   assert( OP_SeekGt == OP_SeekLt+3 );
   68291   assert( u.bb.pC->isOrdered );
   68292   if( ALWAYS(u.bb.pC->pCursor!=0) ){
   68293     u.bb.oc = pOp->opcode;
   68294     u.bb.pC->nullRow = 0;
   68295     if( u.bb.pC->isTable ){
   68296       /* The input value in P3 might be of any type: integer, real, string,
   68297       ** blob, or NULL.  But it needs to be an integer before we can do
   68298       ** the seek, so covert it. */
   68299       pIn3 = &aMem[pOp->p3];
   68300       applyNumericAffinity(pIn3);
   68301       u.bb.iKey = sqlite3VdbeIntValue(pIn3);
   68302       u.bb.pC->rowidIsValid = 0;
   68303 
   68304       /* If the P3 value could not be converted into an integer without
   68305       ** loss of information, then special processing is required... */
   68306       if( (pIn3->flags & MEM_Int)==0 ){
   68307         if( (pIn3->flags & MEM_Real)==0 ){
   68308           /* If the P3 value cannot be converted into any kind of a number,
   68309           ** then the seek is not possible, so jump to P2 */
   68310           pc = pOp->p2 - 1;
   68311           break;
   68312         }
   68313         /* If we reach this point, then the P3 value must be a floating
   68314         ** point number. */
   68315         assert( (pIn3->flags & MEM_Real)!=0 );
   68316 
   68317         if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
   68318           /* The P3 value is too large in magnitude to be expressed as an
   68319           ** integer. */
   68320           u.bb.res = 1;
   68321           if( pIn3->r<0 ){
   68322             if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
   68323               rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
   68324               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68325             }
   68326           }else{
   68327             if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
   68328               rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
   68329               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68330             }
   68331           }
   68332           if( u.bb.res ){
   68333             pc = pOp->p2 - 1;
   68334           }
   68335           break;
   68336         }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
   68337           /* Use the ceiling() function to convert real->int */
   68338           if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
   68339         }else{
   68340           /* Use the floor() function to convert real->int */
   68341           assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
   68342           if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
   68343         }
   68344       }
   68345       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
   68346       if( rc!=SQLITE_OK ){
   68347         goto abort_due_to_error;
   68348       }
   68349       if( u.bb.res==0 ){
   68350         u.bb.pC->rowidIsValid = 1;
   68351         u.bb.pC->lastRowid = u.bb.iKey;
   68352       }
   68353     }else{
   68354       u.bb.nField = pOp->p4.i;
   68355       assert( pOp->p4type==P4_INT32 );
   68356       assert( u.bb.nField>0 );
   68357       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
   68358       u.bb.r.nField = (u16)u.bb.nField;
   68359 
   68360       /* The next line of code computes as follows, only faster:
   68361       **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
   68362       **     u.bb.r.flags = UNPACKED_INCRKEY;
   68363       **   }else{
   68364       **     u.bb.r.flags = 0;
   68365       **   }
   68366       */
   68367       u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
   68368       assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
   68369       assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
   68370       assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
   68371       assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
   68372 
   68373       u.bb.r.aMem = &aMem[pOp->p3];
   68374 #ifdef SQLITE_DEBUG
   68375       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
   68376 #endif
   68377       ExpandBlob(u.bb.r.aMem);
   68378       rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
   68379       if( rc!=SQLITE_OK ){
   68380         goto abort_due_to_error;
   68381       }
   68382       u.bb.pC->rowidIsValid = 0;
   68383     }
   68384     u.bb.pC->deferredMoveto = 0;
   68385     u.bb.pC->cacheStatus = CACHE_STALE;
   68386 #ifdef SQLITE_TEST
   68387     sqlite3_search_count++;
   68388 #endif
   68389     if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
   68390       if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
   68391         rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
   68392         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68393         u.bb.pC->rowidIsValid = 0;
   68394       }else{
   68395         u.bb.res = 0;
   68396       }
   68397     }else{
   68398       assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
   68399       if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
   68400         rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
   68401         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   68402         u.bb.pC->rowidIsValid = 0;
   68403       }else{
   68404         /* u.bb.res might be negative because the table is empty.  Check to
   68405         ** see if this is the case.
   68406         */
   68407         u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
   68408       }
   68409     }
   68410     assert( pOp->p2>0 );
   68411     if( u.bb.res ){
   68412       pc = pOp->p2 - 1;
   68413     }
   68414   }else{
   68415     /* This happens when attempting to open the sqlite3_master table
   68416     ** for read access returns SQLITE_EMPTY. In this case always
   68417     ** take the jump (since there are no records in the table).
   68418     */
   68419     pc = pOp->p2 - 1;
   68420   }
   68421   break;
   68422 }
   68423 
   68424 /* Opcode: Seek P1 P2 * * *
   68425 **
   68426 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   68427 ** for P1 to move so that it points to the rowid given by P2.
   68428 **
   68429 ** This is actually a deferred seek.  Nothing actually happens until
   68430 ** the cursor is used to read a record.  That way, if no reads
   68431 ** occur, no unnecessary I/O happens.
   68432 */
   68433 case OP_Seek: {    /* in2 */
   68434 #if 0  /* local variables moved into u.bc */
   68435   VdbeCursor *pC;
   68436 #endif /* local variables moved into u.bc */
   68437 
   68438   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68439   u.bc.pC = p->apCsr[pOp->p1];
   68440   assert( u.bc.pC!=0 );
   68441   if( ALWAYS(u.bc.pC->pCursor!=0) ){
   68442     assert( u.bc.pC->isTable );
   68443     u.bc.pC->nullRow = 0;
   68444     pIn2 = &aMem[pOp->p2];
   68445     u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   68446     u.bc.pC->rowidIsValid = 0;
   68447     u.bc.pC->deferredMoveto = 1;
   68448   }
   68449   break;
   68450 }
   68451 
   68452 
   68453 /* Opcode: Found P1 P2 P3 P4 *
   68454 **
   68455 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   68456 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   68457 ** record.
   68458 **
   68459 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   68460 ** is a prefix of any entry in P1 then a jump is made to P2 and
   68461 ** P1 is left pointing at the matching entry.
   68462 */
   68463 /* Opcode: NotFound P1 P2 P3 P4 *
   68464 **
   68465 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   68466 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   68467 ** record.
   68468 **
   68469 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   68470 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   68471 ** does contain an entry whose prefix matches the P3/P4 record then control
   68472 ** falls through to the next instruction and P1 is left pointing at the
   68473 ** matching entry.
   68474 **
   68475 ** See also: Found, NotExists, IsUnique
   68476 */
   68477 case OP_NotFound:       /* jump, in3 */
   68478 case OP_Found: {        /* jump, in3 */
   68479 #if 0  /* local variables moved into u.bd */
   68480   int alreadyExists;
   68481   VdbeCursor *pC;
   68482   int res;
   68483   char *pFree;
   68484   UnpackedRecord *pIdxKey;
   68485   UnpackedRecord r;
   68486   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   68487 #endif /* local variables moved into u.bd */
   68488 
   68489 #ifdef SQLITE_TEST
   68490   sqlite3_found_count++;
   68491 #endif
   68492 
   68493   u.bd.alreadyExists = 0;
   68494   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68495   assert( pOp->p4type==P4_INT32 );
   68496   u.bd.pC = p->apCsr[pOp->p1];
   68497   assert( u.bd.pC!=0 );
   68498   pIn3 = &aMem[pOp->p3];
   68499   if( ALWAYS(u.bd.pC->pCursor!=0) ){
   68500 
   68501     assert( u.bd.pC->isTable==0 );
   68502     if( pOp->p4.i>0 ){
   68503       u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
   68504       u.bd.r.nField = (u16)pOp->p4.i;
   68505       u.bd.r.aMem = pIn3;
   68506 #ifdef SQLITE_DEBUG
   68507       { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
   68508 #endif
   68509       u.bd.r.flags = UNPACKED_PREFIX_MATCH;
   68510       u.bd.pIdxKey = &u.bd.r;
   68511     }else{
   68512       u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
   68513           u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
   68514       );
   68515       if( u.bd.pIdxKey==0 ) goto no_mem;
   68516       assert( pIn3->flags & MEM_Blob );
   68517       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
   68518       sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
   68519       u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
   68520     }
   68521     rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
   68522     if( pOp->p4.i==0 ){
   68523       sqlite3DbFree(db, u.bd.pFree);
   68524     }
   68525     if( rc!=SQLITE_OK ){
   68526       break;
   68527     }
   68528     u.bd.alreadyExists = (u.bd.res==0);
   68529     u.bd.pC->deferredMoveto = 0;
   68530     u.bd.pC->cacheStatus = CACHE_STALE;
   68531   }
   68532   if( pOp->opcode==OP_Found ){
   68533     if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
   68534   }else{
   68535     if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
   68536   }
   68537   break;
   68538 }
   68539 
   68540 /* Opcode: IsUnique P1 P2 P3 P4 *
   68541 **
   68542 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
   68543 ** no data and where the key are records generated by OP_MakeRecord with
   68544 ** the list field being the integer ROWID of the entry that the index
   68545 ** entry refers to.
   68546 **
   68547 ** The P3 register contains an integer record number. Call this record
   68548 ** number R. Register P4 is the first in a set of N contiguous registers
   68549 ** that make up an unpacked index key that can be used with cursor P1.
   68550 ** The value of N can be inferred from the cursor. N includes the rowid
   68551 ** value appended to the end of the index record. This rowid value may
   68552 ** or may not be the same as R.
   68553 **
   68554 ** If any of the N registers beginning with register P4 contains a NULL
   68555 ** value, jump immediately to P2.
   68556 **
   68557 ** Otherwise, this instruction checks if cursor P1 contains an entry
   68558 ** where the first (N-1) fields match but the rowid value at the end
   68559 ** of the index entry is not R. If there is no such entry, control jumps
   68560 ** to instruction P2. Otherwise, the rowid of the conflicting index
   68561 ** entry is copied to register P3 and control falls through to the next
   68562 ** instruction.
   68563 **
   68564 ** See also: NotFound, NotExists, Found
   68565 */
   68566 case OP_IsUnique: {        /* jump, in3 */
   68567 #if 0  /* local variables moved into u.be */
   68568   u16 ii;
   68569   VdbeCursor *pCx;
   68570   BtCursor *pCrsr;
   68571   u16 nField;
   68572   Mem *aMx;
   68573   UnpackedRecord r;                  /* B-Tree index search key */
   68574   i64 R;                             /* Rowid stored in register P3 */
   68575 #endif /* local variables moved into u.be */
   68576 
   68577   pIn3 = &aMem[pOp->p3];
   68578   u.be.aMx = &aMem[pOp->p4.i];
   68579   /* Assert that the values of parameters P1 and P4 are in range. */
   68580   assert( pOp->p4type==P4_INT32 );
   68581   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
   68582   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68583 
   68584   /* Find the index cursor. */
   68585   u.be.pCx = p->apCsr[pOp->p1];
   68586   assert( u.be.pCx->deferredMoveto==0 );
   68587   u.be.pCx->seekResult = 0;
   68588   u.be.pCx->cacheStatus = CACHE_STALE;
   68589   u.be.pCrsr = u.be.pCx->pCursor;
   68590 
   68591   /* If any of the values are NULL, take the jump. */
   68592   u.be.nField = u.be.pCx->pKeyInfo->nField;
   68593   for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
   68594     if( u.be.aMx[u.be.ii].flags & MEM_Null ){
   68595       pc = pOp->p2 - 1;
   68596       u.be.pCrsr = 0;
   68597       break;
   68598     }
   68599   }
   68600   assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
   68601 
   68602   if( u.be.pCrsr!=0 ){
   68603     /* Populate the index search key. */
   68604     u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
   68605     u.be.r.nField = u.be.nField + 1;
   68606     u.be.r.flags = UNPACKED_PREFIX_SEARCH;
   68607     u.be.r.aMem = u.be.aMx;
   68608 #ifdef SQLITE_DEBUG
   68609     { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
   68610 #endif
   68611 
   68612     /* Extract the value of u.be.R from register P3. */
   68613     sqlite3VdbeMemIntegerify(pIn3);
   68614     u.be.R = pIn3->u.i;
   68615 
   68616     /* Search the B-Tree index. If no conflicting record is found, jump
   68617     ** to P2. Otherwise, copy the rowid of the conflicting record to
   68618     ** register P3 and fall through to the next instruction.  */
   68619     rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
   68620     if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
   68621       pc = pOp->p2 - 1;
   68622     }else{
   68623       pIn3->u.i = u.be.r.rowid;
   68624     }
   68625   }
   68626   break;
   68627 }
   68628 
   68629 /* Opcode: NotExists P1 P2 P3 * *
   68630 **
   68631 ** Use the content of register P3 as an integer key.  If a record
   68632 ** with that key does not exist in table of P1, then jump to P2.
   68633 ** If the record does exist, then fall through.  The cursor is left
   68634 ** pointing to the record if it exists.
   68635 **
   68636 ** The difference between this operation and NotFound is that this
   68637 ** operation assumes the key is an integer and that P1 is a table whereas
   68638 ** NotFound assumes key is a blob constructed from MakeRecord and
   68639 ** P1 is an index.
   68640 **
   68641 ** See also: Found, NotFound, IsUnique
   68642 */
   68643 case OP_NotExists: {        /* jump, in3 */
   68644 #if 0  /* local variables moved into u.bf */
   68645   VdbeCursor *pC;
   68646   BtCursor *pCrsr;
   68647   int res;
   68648   u64 iKey;
   68649 #endif /* local variables moved into u.bf */
   68650 
   68651   pIn3 = &aMem[pOp->p3];
   68652   assert( pIn3->flags & MEM_Int );
   68653   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68654   u.bf.pC = p->apCsr[pOp->p1];
   68655   assert( u.bf.pC!=0 );
   68656   assert( u.bf.pC->isTable );
   68657   assert( u.bf.pC->pseudoTableReg==0 );
   68658   u.bf.pCrsr = u.bf.pC->pCursor;
   68659   if( ALWAYS(u.bf.pCrsr!=0) ){
   68660     u.bf.res = 0;
   68661     u.bf.iKey = pIn3->u.i;
   68662     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
   68663     u.bf.pC->lastRowid = pIn3->u.i;
   68664     u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
   68665     u.bf.pC->nullRow = 0;
   68666     u.bf.pC->cacheStatus = CACHE_STALE;
   68667     u.bf.pC->deferredMoveto = 0;
   68668     if( u.bf.res!=0 ){
   68669       pc = pOp->p2 - 1;
   68670       assert( u.bf.pC->rowidIsValid==0 );
   68671     }
   68672     u.bf.pC->seekResult = u.bf.res;
   68673   }else{
   68674     /* This happens when an attempt to open a read cursor on the
   68675     ** sqlite_master table returns SQLITE_EMPTY.
   68676     */
   68677     pc = pOp->p2 - 1;
   68678     assert( u.bf.pC->rowidIsValid==0 );
   68679     u.bf.pC->seekResult = 0;
   68680   }
   68681   break;
   68682 }
   68683 
   68684 /* Opcode: Sequence P1 P2 * * *
   68685 **
   68686 ** Find the next available sequence number for cursor P1.
   68687 ** Write the sequence number into register P2.
   68688 ** The sequence number on the cursor is incremented after this
   68689 ** instruction.
   68690 */
   68691 case OP_Sequence: {           /* out2-prerelease */
   68692   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68693   assert( p->apCsr[pOp->p1]!=0 );
   68694   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   68695   break;
   68696 }
   68697 
   68698 
   68699 /* Opcode: NewRowid P1 P2 P3 * *
   68700 **
   68701 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   68702 ** The record number is not previously used as a key in the database
   68703 ** table that cursor P1 points to.  The new record number is written
   68704 ** written to register P2.
   68705 **
   68706 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   68707 ** the largest previously generated record number. No new record numbers are
   68708 ** allowed to be less than this value. When this value reaches its maximum,
   68709 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
   68710 ** generated record number. This P3 mechanism is used to help implement the
   68711 ** AUTOINCREMENT feature.
   68712 */
   68713 case OP_NewRowid: {           /* out2-prerelease */
   68714 #if 0  /* local variables moved into u.bg */
   68715   i64 v;                 /* The new rowid */
   68716   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   68717   int res;               /* Result of an sqlite3BtreeLast() */
   68718   int cnt;               /* Counter to limit the number of searches */
   68719   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   68720   VdbeFrame *pFrame;     /* Root frame of VDBE */
   68721 #endif /* local variables moved into u.bg */
   68722 
   68723   u.bg.v = 0;
   68724   u.bg.res = 0;
   68725   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68726   u.bg.pC = p->apCsr[pOp->p1];
   68727   assert( u.bg.pC!=0 );
   68728   if( NEVER(u.bg.pC->pCursor==0) ){
   68729     /* The zero initialization above is all that is needed */
   68730   }else{
   68731     /* The next rowid or record number (different terms for the same
   68732     ** thing) is obtained in a two-step algorithm.
   68733     **
   68734     ** First we attempt to find the largest existing rowid and add one
   68735     ** to that.  But if the largest existing rowid is already the maximum
   68736     ** positive integer, we have to fall through to the second
   68737     ** probabilistic algorithm
   68738     **
   68739     ** The second algorithm is to select a rowid at random and see if
   68740     ** it already exists in the table.  If it does not exist, we have
   68741     ** succeeded.  If the random rowid does exist, we select a new one
   68742     ** and try again, up to 100 times.
   68743     */
   68744     assert( u.bg.pC->isTable );
   68745 
   68746 #ifdef SQLITE_32BIT_ROWID
   68747 #   define MAX_ROWID 0x7fffffff
   68748 #else
   68749     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   68750     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   68751     ** to provide the constant while making all compilers happy.
   68752     */
   68753 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   68754 #endif
   68755 
   68756     if( !u.bg.pC->useRandomRowid ){
   68757       u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
   68758       if( u.bg.v==0 ){
   68759         rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
   68760         if( rc!=SQLITE_OK ){
   68761           goto abort_due_to_error;
   68762         }
   68763         if( u.bg.res ){
   68764           u.bg.v = 1;   /* IMP: R-61914-48074 */
   68765         }else{
   68766           assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
   68767           rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
   68768           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   68769           if( u.bg.v>=MAX_ROWID ){
   68770             u.bg.pC->useRandomRowid = 1;
   68771           }else{
   68772             u.bg.v++;   /* IMP: R-29538-34987 */
   68773           }
   68774         }
   68775       }
   68776 
   68777 #ifndef SQLITE_OMIT_AUTOINCREMENT
   68778       if( pOp->p3 ){
   68779         /* Assert that P3 is a valid memory cell. */
   68780         assert( pOp->p3>0 );
   68781         if( p->pFrame ){
   68782           for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
   68783           /* Assert that P3 is a valid memory cell. */
   68784           assert( pOp->p3<=u.bg.pFrame->nMem );
   68785           u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
   68786         }else{
   68787           /* Assert that P3 is a valid memory cell. */
   68788           assert( pOp->p3<=p->nMem );
   68789           u.bg.pMem = &aMem[pOp->p3];
   68790           memAboutToChange(p, u.bg.pMem);
   68791         }
   68792         assert( memIsValid(u.bg.pMem) );
   68793 
   68794         REGISTER_TRACE(pOp->p3, u.bg.pMem);
   68795         sqlite3VdbeMemIntegerify(u.bg.pMem);
   68796         assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   68797         if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
   68798           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   68799           goto abort_due_to_error;
   68800         }
   68801         if( u.bg.v<u.bg.pMem->u.i+1 ){
   68802           u.bg.v = u.bg.pMem->u.i + 1;
   68803         }
   68804         u.bg.pMem->u.i = u.bg.v;
   68805       }
   68806 #endif
   68807 
   68808       sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
   68809     }
   68810     if( u.bg.pC->useRandomRowid ){
   68811       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   68812       ** largest possible integer (9223372036854775807) then the database
   68813       ** engine starts picking positive candidate ROWIDs at random until
   68814       ** it finds one that is not previously used. */
   68815       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   68816                              ** an AUTOINCREMENT table. */
   68817       /* on the first attempt, simply do one more than previous */
   68818       u.bg.v = lastRowid;
   68819       u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   68820       u.bg.v++; /* ensure non-zero */
   68821       u.bg.cnt = 0;
   68822       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
   68823                                                  0, &u.bg.res))==SQLITE_OK)
   68824             && (u.bg.res==0)
   68825             && (++u.bg.cnt<100)){
   68826         /* collision - try another random rowid */
   68827         sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
   68828         if( u.bg.cnt<5 ){
   68829           /* try "small" random rowids for the initial attempts */
   68830           u.bg.v &= 0xffffff;
   68831         }else{
   68832           u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   68833         }
   68834         u.bg.v++; /* ensure non-zero */
   68835       }
   68836       if( rc==SQLITE_OK && u.bg.res==0 ){
   68837         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   68838         goto abort_due_to_error;
   68839       }
   68840       assert( u.bg.v>0 );  /* EV: R-40812-03570 */
   68841     }
   68842     u.bg.pC->rowidIsValid = 0;
   68843     u.bg.pC->deferredMoveto = 0;
   68844     u.bg.pC->cacheStatus = CACHE_STALE;
   68845   }
   68846   pOut->u.i = u.bg.v;
   68847   break;
   68848 }
   68849 
   68850 /* Opcode: Insert P1 P2 P3 P4 P5
   68851 **
   68852 ** Write an entry into the table of cursor P1.  A new entry is
   68853 ** created if it doesn't already exist or the data for an existing
   68854 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   68855 ** number P2. The key is stored in register P3. The key must
   68856 ** be a MEM_Int.
   68857 **
   68858 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   68859 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   68860 ** then rowid is stored for subsequent return by the
   68861 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   68862 **
   68863 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   68864 ** the last seek operation (OP_NotExists) was a success, then this
   68865 ** operation will not attempt to find the appropriate row before doing
   68866 ** the insert but will instead overwrite the row that the cursor is
   68867 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   68868 ** has already positioned the cursor correctly.  This is an optimization
   68869 ** that boosts performance by avoiding redundant seeks.
   68870 **
   68871 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   68872 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   68873 ** is part of an INSERT operation.  The difference is only important to
   68874 ** the update hook.
   68875 **
   68876 ** Parameter P4 may point to a string containing the table-name, or
   68877 ** may be NULL. If it is not NULL, then the update-hook
   68878 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   68879 **
   68880 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   68881 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   68882 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   68883 ** value of register P2 will then change.  Make sure this does not
   68884 ** cause any problems.)
   68885 **
   68886 ** This instruction only works on tables.  The equivalent instruction
   68887 ** for indices is OP_IdxInsert.
   68888 */
   68889 /* Opcode: InsertInt P1 P2 P3 P4 P5
   68890 **
   68891 ** This works exactly like OP_Insert except that the key is the
   68892 ** integer value P3, not the value of the integer stored in register P3.
   68893 */
   68894 case OP_Insert:
   68895 case OP_InsertInt: {
   68896 #if 0  /* local variables moved into u.bh */
   68897   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   68898   Mem *pKey;        /* MEM cell holding key  for the record */
   68899   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   68900   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   68901   int nZero;        /* Number of zero-bytes to append */
   68902   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   68903   const char *zDb;  /* database name - used by the update hook */
   68904   const char *zTbl; /* Table name - used by the opdate hook */
   68905   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   68906 #endif /* local variables moved into u.bh */
   68907 
   68908   u.bh.pData = &aMem[pOp->p2];
   68909   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68910   assert( memIsValid(u.bh.pData) );
   68911   u.bh.pC = p->apCsr[pOp->p1];
   68912   assert( u.bh.pC!=0 );
   68913   assert( u.bh.pC->pCursor!=0 );
   68914   assert( u.bh.pC->pseudoTableReg==0 );
   68915   assert( u.bh.pC->isTable );
   68916   REGISTER_TRACE(pOp->p2, u.bh.pData);
   68917 
   68918   if( pOp->opcode==OP_Insert ){
   68919     u.bh.pKey = &aMem[pOp->p3];
   68920     assert( u.bh.pKey->flags & MEM_Int );
   68921     assert( memIsValid(u.bh.pKey) );
   68922     REGISTER_TRACE(pOp->p3, u.bh.pKey);
   68923     u.bh.iKey = u.bh.pKey->u.i;
   68924   }else{
   68925     assert( pOp->opcode==OP_InsertInt );
   68926     u.bh.iKey = pOp->p3;
   68927   }
   68928 
   68929   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   68930   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
   68931   if( u.bh.pData->flags & MEM_Null ){
   68932     u.bh.pData->z = 0;
   68933     u.bh.pData->n = 0;
   68934   }else{
   68935     assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
   68936   }
   68937   u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
   68938   if( u.bh.pData->flags & MEM_Zero ){
   68939     u.bh.nZero = u.bh.pData->u.nZero;
   68940   }else{
   68941     u.bh.nZero = 0;
   68942   }
   68943   sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
   68944   rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
   68945                           u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
   68946                           pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
   68947   );
   68948   u.bh.pC->rowidIsValid = 0;
   68949   u.bh.pC->deferredMoveto = 0;
   68950   u.bh.pC->cacheStatus = CACHE_STALE;
   68951 
   68952   /* Invoke the update-hook if required. */
   68953   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   68954     u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
   68955     u.bh.zTbl = pOp->p4.z;
   68956     u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   68957     assert( u.bh.pC->isTable );
   68958     db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
   68959     assert( u.bh.pC->iDb>=0 );
   68960   }
   68961   break;
   68962 }
   68963 
   68964 /* Opcode: Delete P1 P2 * P4 *
   68965 **
   68966 ** Delete the record at which the P1 cursor is currently pointing.
   68967 **
   68968 ** The cursor will be left pointing at either the next or the previous
   68969 ** record in the table. If it is left pointing at the next record, then
   68970 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   68971 ** a record from within an Next loop.
   68972 **
   68973 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   68974 ** incremented (otherwise not).
   68975 **
   68976 ** P1 must not be pseudo-table.  It has to be a real table with
   68977 ** multiple rows.
   68978 **
   68979 ** If P4 is not NULL, then it is the name of the table that P1 is
   68980 ** pointing to.  The update hook will be invoked, if it exists.
   68981 ** If P4 is not NULL then the P1 cursor must have been positioned
   68982 ** using OP_NotFound prior to invoking this opcode.
   68983 */
   68984 case OP_Delete: {
   68985 #if 0  /* local variables moved into u.bi */
   68986   i64 iKey;
   68987   VdbeCursor *pC;
   68988 #endif /* local variables moved into u.bi */
   68989 
   68990   u.bi.iKey = 0;
   68991   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   68992   u.bi.pC = p->apCsr[pOp->p1];
   68993   assert( u.bi.pC!=0 );
   68994   assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   68995 
   68996   /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
   68997   ** row being deleted.
   68998   */
   68999   if( db->xUpdateCallback && pOp->p4.z ){
   69000     assert( u.bi.pC->isTable );
   69001     assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
   69002     u.bi.iKey = u.bi.pC->lastRowid;
   69003   }
   69004 
   69005   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   69006   ** OP_Column on the same table without any intervening operations that
   69007   ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
   69008   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   69009   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   69010   ** to guard against future changes to the code generator.
   69011   **/
   69012   assert( u.bi.pC->deferredMoveto==0 );
   69013   rc = sqlite3VdbeCursorMoveto(u.bi.pC);
   69014   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   69015 
   69016   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
   69017   rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
   69018   u.bi.pC->cacheStatus = CACHE_STALE;
   69019 
   69020   /* Invoke the update-hook if required. */
   69021   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   69022     const char *zDb = db->aDb[u.bi.pC->iDb].zName;
   69023     const char *zTbl = pOp->p4.z;
   69024     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
   69025     assert( u.bi.pC->iDb>=0 );
   69026   }
   69027   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   69028   break;
   69029 }
   69030 /* Opcode: ResetCount * * * * *
   69031 **
   69032 ** The value of the change counter is copied to the database handle
   69033 ** change counter (returned by subsequent calls to sqlite3_changes()).
   69034 ** Then the VMs internal change counter resets to 0.
   69035 ** This is used by trigger programs.
   69036 */
   69037 case OP_ResetCount: {
   69038   sqlite3VdbeSetChanges(db, p->nChange);
   69039   p->nChange = 0;
   69040   break;
   69041 }
   69042 
   69043 /* Opcode: SorterCompare P1 P2 P3
   69044 **
   69045 ** P1 is a sorter cursor. This instruction compares the record blob in
   69046 ** register P3 with the entry that the sorter cursor currently points to.
   69047 ** If, excluding the rowid fields at the end, the two records are a match,
   69048 ** fall through to the next instruction. Otherwise, jump to instruction P2.
   69049 */
   69050 case OP_SorterCompare: {
   69051 #if 0  /* local variables moved into u.bj */
   69052   VdbeCursor *pC;
   69053   int res;
   69054 #endif /* local variables moved into u.bj */
   69055 
   69056   u.bj.pC = p->apCsr[pOp->p1];
   69057   assert( isSorter(u.bj.pC) );
   69058   pIn3 = &aMem[pOp->p3];
   69059   rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
   69060   if( u.bj.res ){
   69061     pc = pOp->p2-1;
   69062   }
   69063   break;
   69064 };
   69065 
   69066 /* Opcode: SorterData P1 P2 * * *
   69067 **
   69068 ** Write into register P2 the current sorter data for sorter cursor P1.
   69069 */
   69070 case OP_SorterData: {
   69071 #if 0  /* local variables moved into u.bk */
   69072   VdbeCursor *pC;
   69073 #endif /* local variables moved into u.bk */
   69074 #ifndef SQLITE_OMIT_MERGE_SORT
   69075   pOut = &aMem[pOp->p2];
   69076   u.bk.pC = p->apCsr[pOp->p1];
   69077   assert( u.bk.pC->isSorter );
   69078   rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
   69079 #else
   69080   pOp->opcode = OP_RowKey;
   69081   pc--;
   69082 #endif
   69083   break;
   69084 }
   69085 
   69086 /* Opcode: RowData P1 P2 * * *
   69087 **
   69088 ** Write into register P2 the complete row data for cursor P1.
   69089 ** There is no interpretation of the data.
   69090 ** It is just copied onto the P2 register exactly as
   69091 ** it is found in the database file.
   69092 **
   69093 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   69094 ** of a real table, not a pseudo-table.
   69095 */
   69096 /* Opcode: RowKey P1 P2 * * *
   69097 **
   69098 ** Write into register P2 the complete row key for cursor P1.
   69099 ** There is no interpretation of the data.
   69100 ** The key is copied onto the P3 register exactly as
   69101 ** it is found in the database file.
   69102 **
   69103 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   69104 ** of a real table, not a pseudo-table.
   69105 */
   69106 case OP_RowKey:
   69107 case OP_RowData: {
   69108 #if 0  /* local variables moved into u.bl */
   69109   VdbeCursor *pC;
   69110   BtCursor *pCrsr;
   69111   u32 n;
   69112   i64 n64;
   69113 #endif /* local variables moved into u.bl */
   69114 
   69115   pOut = &aMem[pOp->p2];
   69116   memAboutToChange(p, pOut);
   69117 
   69118   /* Note that RowKey and RowData are really exactly the same instruction */
   69119   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69120   u.bl.pC = p->apCsr[pOp->p1];
   69121   assert( u.bl.pC->isSorter==0 );
   69122   assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
   69123   assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
   69124   assert( u.bl.pC!=0 );
   69125   assert( u.bl.pC->nullRow==0 );
   69126   assert( u.bl.pC->pseudoTableReg==0 );
   69127   assert( !u.bl.pC->isSorter );
   69128   assert( u.bl.pC->pCursor!=0 );
   69129   u.bl.pCrsr = u.bl.pC->pCursor;
   69130   assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
   69131 
   69132   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   69133   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   69134   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   69135   ** a no-op and can never fail.  But we leave it in place as a safety.
   69136   */
   69137   assert( u.bl.pC->deferredMoveto==0 );
   69138   rc = sqlite3VdbeCursorMoveto(u.bl.pC);
   69139   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   69140 
   69141   if( u.bl.pC->isIndex ){
   69142     assert( !u.bl.pC->isTable );
   69143     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
   69144     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   69145     if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69146       goto too_big;
   69147     }
   69148     u.bl.n = (u32)u.bl.n64;
   69149   }else{
   69150     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
   69151     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   69152     if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   69153       goto too_big;
   69154     }
   69155   }
   69156   if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
   69157     goto no_mem;
   69158   }
   69159   pOut->n = u.bl.n;
   69160   MemSetTypeFlag(pOut, MEM_Blob);
   69161   if( u.bl.pC->isIndex ){
   69162     rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
   69163   }else{
   69164     rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
   69165   }
   69166   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   69167   UPDATE_MAX_BLOBSIZE(pOut);
   69168   break;
   69169 }
   69170 
   69171 /* Opcode: Rowid P1 P2 * * *
   69172 **
   69173 ** Store in register P2 an integer which is the key of the table entry that
   69174 ** P1 is currently point to.
   69175 **
   69176 ** P1 can be either an ordinary table or a virtual table.  There used to
   69177 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   69178 ** one opcode now works for both table types.
   69179 */
   69180 case OP_Rowid: {                 /* out2-prerelease */
   69181 #if 0  /* local variables moved into u.bm */
   69182   VdbeCursor *pC;
   69183   i64 v;
   69184   sqlite3_vtab *pVtab;
   69185   const sqlite3_module *pModule;
   69186 #endif /* local variables moved into u.bm */
   69187 
   69188   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69189   u.bm.pC = p->apCsr[pOp->p1];
   69190   assert( u.bm.pC!=0 );
   69191   assert( u.bm.pC->pseudoTableReg==0 );
   69192   if( u.bm.pC->nullRow ){
   69193     pOut->flags = MEM_Null;
   69194     break;
   69195   }else if( u.bm.pC->deferredMoveto ){
   69196     u.bm.v = u.bm.pC->movetoTarget;
   69197 #ifndef SQLITE_OMIT_VIRTUALTABLE
   69198   }else if( u.bm.pC->pVtabCursor ){
   69199     u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
   69200     u.bm.pModule = u.bm.pVtab->pModule;
   69201     assert( u.bm.pModule->xRowid );
   69202     rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
   69203     importVtabErrMsg(p, u.bm.pVtab);
   69204 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   69205   }else{
   69206     assert( u.bm.pC->pCursor!=0 );
   69207     rc = sqlite3VdbeCursorMoveto(u.bm.pC);
   69208     if( rc ) goto abort_due_to_error;
   69209     if( u.bm.pC->rowidIsValid ){
   69210       u.bm.v = u.bm.pC->lastRowid;
   69211     }else{
   69212       rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
   69213       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   69214     }
   69215   }
   69216   pOut->u.i = u.bm.v;
   69217   break;
   69218 }
   69219 
   69220 /* Opcode: NullRow P1 * * * *
   69221 **
   69222 ** Move the cursor P1 to a null row.  Any OP_Column operations
   69223 ** that occur while the cursor is on the null row will always
   69224 ** write a NULL.
   69225 */
   69226 case OP_NullRow: {
   69227 #if 0  /* local variables moved into u.bn */
   69228   VdbeCursor *pC;
   69229 #endif /* local variables moved into u.bn */
   69230 
   69231   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69232   u.bn.pC = p->apCsr[pOp->p1];
   69233   assert( u.bn.pC!=0 );
   69234   u.bn.pC->nullRow = 1;
   69235   u.bn.pC->rowidIsValid = 0;
   69236   assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
   69237   if( u.bn.pC->pCursor ){
   69238     sqlite3BtreeClearCursor(u.bn.pC->pCursor);
   69239   }
   69240   break;
   69241 }
   69242 
   69243 /* Opcode: Last P1 P2 * * *
   69244 **
   69245 ** The next use of the Rowid or Column or Next instruction for P1
   69246 ** will refer to the last entry in the database table or index.
   69247 ** If the table or index is empty and P2>0, then jump immediately to P2.
   69248 ** If P2 is 0 or if the table or index is not empty, fall through
   69249 ** to the following instruction.
   69250 */
   69251 case OP_Last: {        /* jump */
   69252 #if 0  /* local variables moved into u.bo */
   69253   VdbeCursor *pC;
   69254   BtCursor *pCrsr;
   69255   int res;
   69256 #endif /* local variables moved into u.bo */
   69257 
   69258   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69259   u.bo.pC = p->apCsr[pOp->p1];
   69260   assert( u.bo.pC!=0 );
   69261   u.bo.pCrsr = u.bo.pC->pCursor;
   69262   u.bo.res = 0;
   69263   if( ALWAYS(u.bo.pCrsr!=0) ){
   69264     rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
   69265   }
   69266   u.bo.pC->nullRow = (u8)u.bo.res;
   69267   u.bo.pC->deferredMoveto = 0;
   69268   u.bo.pC->rowidIsValid = 0;
   69269   u.bo.pC->cacheStatus = CACHE_STALE;
   69270   if( pOp->p2>0 && u.bo.res ){
   69271     pc = pOp->p2 - 1;
   69272   }
   69273   break;
   69274 }
   69275 
   69276 
   69277 /* Opcode: Sort P1 P2 * * *
   69278 **
   69279 ** This opcode does exactly the same thing as OP_Rewind except that
   69280 ** it increments an undocumented global variable used for testing.
   69281 **
   69282 ** Sorting is accomplished by writing records into a sorting index,
   69283 ** then rewinding that index and playing it back from beginning to
   69284 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   69285 ** rewinding so that the global variable will be incremented and
   69286 ** regression tests can determine whether or not the optimizer is
   69287 ** correctly optimizing out sorts.
   69288 */
   69289 case OP_SorterSort:    /* jump */
   69290 #ifdef SQLITE_OMIT_MERGE_SORT
   69291   pOp->opcode = OP_Sort;
   69292 #endif
   69293 case OP_Sort: {        /* jump */
   69294 #ifdef SQLITE_TEST
   69295   sqlite3_sort_count++;
   69296   sqlite3_search_count--;
   69297 #endif
   69298   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
   69299   /* Fall through into OP_Rewind */
   69300 }
   69301 /* Opcode: Rewind P1 P2 * * *
   69302 **
   69303 ** The next use of the Rowid or Column or Next instruction for P1
   69304 ** will refer to the first entry in the database table or index.
   69305 ** If the table or index is empty and P2>0, then jump immediately to P2.
   69306 ** If P2 is 0 or if the table or index is not empty, fall through
   69307 ** to the following instruction.
   69308 */
   69309 case OP_Rewind: {        /* jump */
   69310 #if 0  /* local variables moved into u.bp */
   69311   VdbeCursor *pC;
   69312   BtCursor *pCrsr;
   69313   int res;
   69314 #endif /* local variables moved into u.bp */
   69315 
   69316   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69317   u.bp.pC = p->apCsr[pOp->p1];
   69318   assert( u.bp.pC!=0 );
   69319   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
   69320   u.bp.res = 1;
   69321   if( isSorter(u.bp.pC) ){
   69322     rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
   69323   }else{
   69324     u.bp.pCrsr = u.bp.pC->pCursor;
   69325     assert( u.bp.pCrsr );
   69326     rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
   69327     u.bp.pC->atFirst = u.bp.res==0 ?1:0;
   69328     u.bp.pC->deferredMoveto = 0;
   69329     u.bp.pC->cacheStatus = CACHE_STALE;
   69330     u.bp.pC->rowidIsValid = 0;
   69331   }
   69332   u.bp.pC->nullRow = (u8)u.bp.res;
   69333   assert( pOp->p2>0 && pOp->p2<p->nOp );
   69334   if( u.bp.res ){
   69335     pc = pOp->p2 - 1;
   69336   }
   69337   break;
   69338 }
   69339 
   69340 /* Opcode: Next P1 P2 * P4 P5
   69341 **
   69342 ** Advance cursor P1 so that it points to the next key/data pair in its
   69343 ** table or index.  If there are no more key/value pairs then fall through
   69344 ** to the following instruction.  But if the cursor advance was successful,
   69345 ** jump immediately to P2.
   69346 **
   69347 ** The P1 cursor must be for a real table, not a pseudo-table.
   69348 **
   69349 ** P4 is always of type P4_ADVANCE. The function pointer points to
   69350 ** sqlite3BtreeNext().
   69351 **
   69352 ** If P5 is positive and the jump is taken, then event counter
   69353 ** number P5-1 in the prepared statement is incremented.
   69354 **
   69355 ** See also: Prev
   69356 */
   69357 /* Opcode: Prev P1 P2 * * P5
   69358 **
   69359 ** Back up cursor P1 so that it points to the previous key/data pair in its
   69360 ** table or index.  If there is no previous key/value pairs then fall through
   69361 ** to the following instruction.  But if the cursor backup 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 ** sqlite3BtreePrevious().
   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 case OP_SorterNext:    /* jump */
   69373 #ifdef SQLITE_OMIT_MERGE_SORT
   69374   pOp->opcode = OP_Next;
   69375 #endif
   69376 case OP_Prev:          /* jump */
   69377 case OP_Next: {        /* jump */
   69378 #if 0  /* local variables moved into u.bq */
   69379   VdbeCursor *pC;
   69380   int res;
   69381 #endif /* local variables moved into u.bq */
   69382 
   69383   CHECK_FOR_INTERRUPT;
   69384   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69385   assert( pOp->p5<=ArraySize(p->aCounter) );
   69386   u.bq.pC = p->apCsr[pOp->p1];
   69387   if( u.bq.pC==0 ){
   69388     break;  /* See ticket #2273 */
   69389   }
   69390   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
   69391   if( isSorter(u.bq.pC) ){
   69392     assert( pOp->opcode==OP_SorterNext );
   69393     rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
   69394   }else{
   69395     u.bq.res = 1;
   69396     assert( u.bq.pC->deferredMoveto==0 );
   69397     assert( u.bq.pC->pCursor );
   69398     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
   69399     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
   69400     rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
   69401   }
   69402   u.bq.pC->nullRow = (u8)u.bq.res;
   69403   u.bq.pC->cacheStatus = CACHE_STALE;
   69404   if( u.bq.res==0 ){
   69405     pc = pOp->p2 - 1;
   69406     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
   69407 #ifdef SQLITE_TEST
   69408     sqlite3_search_count++;
   69409 #endif
   69410   }
   69411   u.bq.pC->rowidIsValid = 0;
   69412   break;
   69413 }
   69414 
   69415 /* Opcode: IdxInsert P1 P2 P3 * P5
   69416 **
   69417 ** Register P2 holds an SQL index key made using the
   69418 ** MakeRecord instructions.  This opcode writes that key
   69419 ** into the index P1.  Data for the entry is nil.
   69420 **
   69421 ** P3 is a flag that provides a hint to the b-tree layer that this
   69422 ** insert is likely to be an append.
   69423 **
   69424 ** This instruction only works for indices.  The equivalent instruction
   69425 ** for tables is OP_Insert.
   69426 */
   69427 case OP_SorterInsert:       /* in2 */
   69428 #ifdef SQLITE_OMIT_MERGE_SORT
   69429   pOp->opcode = OP_IdxInsert;
   69430 #endif
   69431 case OP_IdxInsert: {        /* in2 */
   69432 #if 0  /* local variables moved into u.br */
   69433   VdbeCursor *pC;
   69434   BtCursor *pCrsr;
   69435   int nKey;
   69436   const char *zKey;
   69437 #endif /* local variables moved into u.br */
   69438 
   69439   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69440   u.br.pC = p->apCsr[pOp->p1];
   69441   assert( u.br.pC!=0 );
   69442   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
   69443   pIn2 = &aMem[pOp->p2];
   69444   assert( pIn2->flags & MEM_Blob );
   69445   u.br.pCrsr = u.br.pC->pCursor;
   69446   if( ALWAYS(u.br.pCrsr!=0) ){
   69447     assert( u.br.pC->isTable==0 );
   69448     rc = ExpandBlob(pIn2);
   69449     if( rc==SQLITE_OK ){
   69450       if( isSorter(u.br.pC) ){
   69451         rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
   69452       }else{
   69453         u.br.nKey = pIn2->n;
   69454         u.br.zKey = pIn2->z;
   69455         rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
   69456             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
   69457             );
   69458         assert( u.br.pC->deferredMoveto==0 );
   69459         u.br.pC->cacheStatus = CACHE_STALE;
   69460       }
   69461     }
   69462   }
   69463   break;
   69464 }
   69465 
   69466 /* Opcode: IdxDelete P1 P2 P3 * *
   69467 **
   69468 ** The content of P3 registers starting at register P2 form
   69469 ** an unpacked index key. This opcode removes that entry from the
   69470 ** index opened by cursor P1.
   69471 */
   69472 case OP_IdxDelete: {
   69473 #if 0  /* local variables moved into u.bs */
   69474   VdbeCursor *pC;
   69475   BtCursor *pCrsr;
   69476   int res;
   69477   UnpackedRecord r;
   69478 #endif /* local variables moved into u.bs */
   69479 
   69480   assert( pOp->p3>0 );
   69481   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
   69482   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69483   u.bs.pC = p->apCsr[pOp->p1];
   69484   assert( u.bs.pC!=0 );
   69485   u.bs.pCrsr = u.bs.pC->pCursor;
   69486   if( ALWAYS(u.bs.pCrsr!=0) ){
   69487     u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
   69488     u.bs.r.nField = (u16)pOp->p3;
   69489     u.bs.r.flags = 0;
   69490     u.bs.r.aMem = &aMem[pOp->p2];
   69491 #ifdef SQLITE_DEBUG
   69492     { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
   69493 #endif
   69494     rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
   69495     if( rc==SQLITE_OK && u.bs.res==0 ){
   69496       rc = sqlite3BtreeDelete(u.bs.pCrsr);
   69497     }
   69498     assert( u.bs.pC->deferredMoveto==0 );
   69499     u.bs.pC->cacheStatus = CACHE_STALE;
   69500   }
   69501   break;
   69502 }
   69503 
   69504 /* Opcode: IdxRowid P1 P2 * * *
   69505 **
   69506 ** Write into register P2 an integer which is the last entry in the record at
   69507 ** the end of the index key pointed to by cursor P1.  This integer should be
   69508 ** the rowid of the table entry to which this index entry points.
   69509 **
   69510 ** See also: Rowid, MakeRecord.
   69511 */
   69512 case OP_IdxRowid: {              /* out2-prerelease */
   69513 #if 0  /* local variables moved into u.bt */
   69514   BtCursor *pCrsr;
   69515   VdbeCursor *pC;
   69516   i64 rowid;
   69517 #endif /* local variables moved into u.bt */
   69518 
   69519   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69520   u.bt.pC = p->apCsr[pOp->p1];
   69521   assert( u.bt.pC!=0 );
   69522   u.bt.pCrsr = u.bt.pC->pCursor;
   69523   pOut->flags = MEM_Null;
   69524   if( ALWAYS(u.bt.pCrsr!=0) ){
   69525     rc = sqlite3VdbeCursorMoveto(u.bt.pC);
   69526     if( NEVER(rc) ) goto abort_due_to_error;
   69527     assert( u.bt.pC->deferredMoveto==0 );
   69528     assert( u.bt.pC->isTable==0 );
   69529     if( !u.bt.pC->nullRow ){
   69530       rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
   69531       if( rc!=SQLITE_OK ){
   69532         goto abort_due_to_error;
   69533       }
   69534       pOut->u.i = u.bt.rowid;
   69535       pOut->flags = MEM_Int;
   69536     }
   69537   }
   69538   break;
   69539 }
   69540 
   69541 /* Opcode: IdxGE P1 P2 P3 P4 P5
   69542 **
   69543 ** The P4 register values beginning with P3 form an unpacked index
   69544 ** key that omits the ROWID.  Compare this key value against the index
   69545 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   69546 **
   69547 ** If the P1 index entry is greater than or equal to the key value
   69548 ** then jump to P2.  Otherwise fall through to the next instruction.
   69549 **
   69550 ** If P5 is non-zero then the key value is increased by an epsilon
   69551 ** prior to the comparison.  This make the opcode work like IdxGT except
   69552 ** that if the key from register P3 is a prefix of the key in the cursor,
   69553 ** the result is false whereas it would be true with IdxGT.
   69554 */
   69555 /* Opcode: IdxLT P1 P2 P3 P4 P5
   69556 **
   69557 ** The P4 register values beginning with P3 form an unpacked index
   69558 ** key that omits the ROWID.  Compare this key value against the index
   69559 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   69560 **
   69561 ** If the P1 index entry is less than the key value then jump to P2.
   69562 ** Otherwise fall through to the next instruction.
   69563 **
   69564 ** If P5 is non-zero then the key value is increased by an epsilon prior
   69565 ** to the comparison.  This makes the opcode work like IdxLE.
   69566 */
   69567 case OP_IdxLT:          /* jump */
   69568 case OP_IdxGE: {        /* jump */
   69569 #if 0  /* local variables moved into u.bu */
   69570   VdbeCursor *pC;
   69571   int res;
   69572   UnpackedRecord r;
   69573 #endif /* local variables moved into u.bu */
   69574 
   69575   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   69576   u.bu.pC = p->apCsr[pOp->p1];
   69577   assert( u.bu.pC!=0 );
   69578   assert( u.bu.pC->isOrdered );
   69579   if( ALWAYS(u.bu.pC->pCursor!=0) ){
   69580     assert( u.bu.pC->deferredMoveto==0 );
   69581     assert( pOp->p5==0 || pOp->p5==1 );
   69582     assert( pOp->p4type==P4_INT32 );
   69583     u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
   69584     u.bu.r.nField = (u16)pOp->p4.i;
   69585     if( pOp->p5 ){
   69586       u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
   69587     }else{
   69588       u.bu.r.flags = UNPACKED_PREFIX_MATCH;
   69589     }
   69590     u.bu.r.aMem = &aMem[pOp->p3];
   69591 #ifdef SQLITE_DEBUG
   69592     { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
   69593 #endif
   69594     rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
   69595     if( pOp->opcode==OP_IdxLT ){
   69596       u.bu.res = -u.bu.res;
   69597     }else{
   69598       assert( pOp->opcode==OP_IdxGE );
   69599       u.bu.res++;
   69600     }
   69601     if( u.bu.res>0 ){
   69602       pc = pOp->p2 - 1 ;
   69603     }
   69604   }
   69605   break;
   69606 }
   69607 
   69608 /* Opcode: Destroy P1 P2 P3 * *
   69609 **
   69610 ** Delete an entire database table or index whose root page in the database
   69611 ** file is given by P1.
   69612 **
   69613 ** The table being destroyed is in the main database file if P3==0.  If
   69614 ** P3==1 then the table to be clear is in the auxiliary database file
   69615 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   69616 **
   69617 ** If AUTOVACUUM is enabled then it is possible that another root page
   69618 ** might be moved into the newly deleted root page in order to keep all
   69619 ** root pages contiguous at the beginning of the database.  The former
   69620 ** value of the root page that moved - its value before the move occurred -
   69621 ** is stored in register P2.  If no page
   69622 ** movement was required (because the table being dropped was already
   69623 ** the last one in the database) then a zero is stored in register P2.
   69624 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   69625 **
   69626 ** See also: Clear
   69627 */
   69628 case OP_Destroy: {     /* out2-prerelease */
   69629 #if 0  /* local variables moved into u.bv */
   69630   int iMoved;
   69631   int iCnt;
   69632   Vdbe *pVdbe;
   69633   int iDb;
   69634 #endif /* local variables moved into u.bv */
   69635 #ifndef SQLITE_OMIT_VIRTUALTABLE
   69636   u.bv.iCnt = 0;
   69637   for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
   69638     if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
   69639       u.bv.iCnt++;
   69640     }
   69641   }
   69642 #else
   69643   u.bv.iCnt = db->activeVdbeCnt;
   69644 #endif
   69645   pOut->flags = MEM_Null;
   69646   if( u.bv.iCnt>1 ){
   69647     rc = SQLITE_LOCKED;
   69648     p->errorAction = OE_Abort;
   69649   }else{
   69650     u.bv.iDb = pOp->p3;
   69651     assert( u.bv.iCnt==1 );
   69652     assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
   69653     rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
   69654     pOut->flags = MEM_Int;
   69655     pOut->u.i = u.bv.iMoved;
   69656 #ifndef SQLITE_OMIT_AUTOVACUUM
   69657     if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
   69658       sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
   69659       /* All OP_Destroy operations occur on the same btree */
   69660       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
   69661       resetSchemaOnFault = u.bv.iDb+1;
   69662     }
   69663 #endif
   69664   }
   69665   break;
   69666 }
   69667 
   69668 /* Opcode: Clear P1 P2 P3
   69669 **
   69670 ** Delete all contents of the database table or index whose root page
   69671 ** in the database file is given by P1.  But, unlike Destroy, do not
   69672 ** remove the table or index from the database file.
   69673 **
   69674 ** The table being clear is in the main database file if P2==0.  If
   69675 ** P2==1 then the table to be clear is in the auxiliary database file
   69676 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   69677 **
   69678 ** If the P3 value is non-zero, then the table referred to must be an
   69679 ** intkey table (an SQL table, not an index). In this case the row change
   69680 ** count is incremented by the number of rows in the table being cleared.
   69681 ** If P3 is greater than zero, then the value stored in register P3 is
   69682 ** also incremented by the number of rows in the table being cleared.
   69683 **
   69684 ** See also: Destroy
   69685 */
   69686 case OP_Clear: {
   69687 #if 0  /* local variables moved into u.bw */
   69688   int nChange;
   69689 #endif /* local variables moved into u.bw */
   69690 
   69691   u.bw.nChange = 0;
   69692   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
   69693   rc = sqlite3BtreeClearTable(
   69694       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
   69695   );
   69696   if( pOp->p3 ){
   69697     p->nChange += u.bw.nChange;
   69698     if( pOp->p3>0 ){
   69699       assert( memIsValid(&aMem[pOp->p3]) );
   69700       memAboutToChange(p, &aMem[pOp->p3]);
   69701       aMem[pOp->p3].u.i += u.bw.nChange;
   69702     }
   69703   }
   69704   break;
   69705 }
   69706 
   69707 /* Opcode: CreateTable P1 P2 * * *
   69708 **
   69709 ** Allocate a new table in the main database file if P1==0 or in the
   69710 ** auxiliary database file if P1==1 or in an attached database if
   69711 ** P1>1.  Write the root page number of the new table into
   69712 ** register P2
   69713 **
   69714 ** The difference between a table and an index is this:  A table must
   69715 ** have a 4-byte integer key and can have arbitrary data.  An index
   69716 ** has an arbitrary key but no data.
   69717 **
   69718 ** See also: CreateIndex
   69719 */
   69720 /* Opcode: CreateIndex P1 P2 * * *
   69721 **
   69722 ** Allocate a new index in the main database file if P1==0 or in the
   69723 ** auxiliary database file if P1==1 or in an attached database if
   69724 ** P1>1.  Write the root page number of the new table into
   69725 ** register P2.
   69726 **
   69727 ** See documentation on OP_CreateTable for additional information.
   69728 */
   69729 case OP_CreateIndex:            /* out2-prerelease */
   69730 case OP_CreateTable: {          /* out2-prerelease */
   69731 #if 0  /* local variables moved into u.bx */
   69732   int pgno;
   69733   int flags;
   69734   Db *pDb;
   69735 #endif /* local variables moved into u.bx */
   69736 
   69737   u.bx.pgno = 0;
   69738   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   69739   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   69740   u.bx.pDb = &db->aDb[pOp->p1];
   69741   assert( u.bx.pDb->pBt!=0 );
   69742   if( pOp->opcode==OP_CreateTable ){
   69743     /* u.bx.flags = BTREE_INTKEY; */
   69744     u.bx.flags = BTREE_INTKEY;
   69745   }else{
   69746     u.bx.flags = BTREE_BLOBKEY;
   69747   }
   69748   rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
   69749   pOut->u.i = u.bx.pgno;
   69750   break;
   69751 }
   69752 
   69753 /* Opcode: ParseSchema P1 * * P4 *
   69754 **
   69755 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   69756 ** that match the WHERE clause P4.
   69757 **
   69758 ** This opcode invokes the parser to create a new virtual machine,
   69759 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   69760 */
   69761 case OP_ParseSchema: {
   69762 #if 0  /* local variables moved into u.by */
   69763   int iDb;
   69764   const char *zMaster;
   69765   char *zSql;
   69766   InitData initData;
   69767 #endif /* local variables moved into u.by */
   69768 
   69769   /* Any prepared statement that invokes this opcode will hold mutexes
   69770   ** on every btree.  This is a prerequisite for invoking
   69771   ** sqlite3InitCallback().
   69772   */
   69773 #ifdef SQLITE_DEBUG
   69774   for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
   69775     assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
   69776   }
   69777 #endif
   69778 
   69779   u.by.iDb = pOp->p1;
   69780   assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
   69781   assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
   69782   /* Used to be a conditional */ {
   69783     u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
   69784     u.by.initData.db = db;
   69785     u.by.initData.iDb = pOp->p1;
   69786     u.by.initData.pzErrMsg = &p->zErrMsg;
   69787     u.by.zSql = sqlite3MPrintf(db,
   69788        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   69789        db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
   69790     if( u.by.zSql==0 ){
   69791       rc = SQLITE_NOMEM;
   69792     }else{
   69793       assert( db->init.busy==0 );
   69794       db->init.busy = 1;
   69795       u.by.initData.rc = SQLITE_OK;
   69796       assert( !db->mallocFailed );
   69797       rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
   69798       if( rc==SQLITE_OK ) rc = u.by.initData.rc;
   69799       sqlite3DbFree(db, u.by.zSql);
   69800       db->init.busy = 0;
   69801     }
   69802   }
   69803   if( rc ) sqlite3ResetInternalSchema(db, -1);
   69804   if( rc==SQLITE_NOMEM ){
   69805     goto no_mem;
   69806   }
   69807   break;
   69808 }
   69809 
   69810 #if !defined(SQLITE_OMIT_ANALYZE)
   69811 /* Opcode: LoadAnalysis P1 * * * *
   69812 **
   69813 ** Read the sqlite_stat1 table for database P1 and load the content
   69814 ** of that table into the internal index hash table.  This will cause
   69815 ** the analysis to be used when preparing all subsequent queries.
   69816 */
   69817 case OP_LoadAnalysis: {
   69818   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   69819   rc = sqlite3AnalysisLoad(db, pOp->p1);
   69820   break;
   69821 }
   69822 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   69823 
   69824 /* Opcode: DropTable P1 * * P4 *
   69825 **
   69826 ** Remove the internal (in-memory) data structures that describe
   69827 ** the table named P4 in database P1.  This is called after a table
   69828 ** is dropped in order to keep the internal representation of the
   69829 ** schema consistent with what is on disk.
   69830 */
   69831 case OP_DropTable: {
   69832   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   69833   break;
   69834 }
   69835 
   69836 /* Opcode: DropIndex P1 * * P4 *
   69837 **
   69838 ** Remove the internal (in-memory) data structures that describe
   69839 ** the index named P4 in database P1.  This is called after an index
   69840 ** is dropped in order to keep the internal representation of the
   69841 ** schema consistent with what is on disk.
   69842 */
   69843 case OP_DropIndex: {
   69844   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   69845   break;
   69846 }
   69847 
   69848 /* Opcode: DropTrigger P1 * * P4 *
   69849 **
   69850 ** Remove the internal (in-memory) data structures that describe
   69851 ** the trigger named P4 in database P1.  This is called after a trigger
   69852 ** is dropped in order to keep the internal representation of the
   69853 ** schema consistent with what is on disk.
   69854 */
   69855 case OP_DropTrigger: {
   69856   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   69857   break;
   69858 }
   69859 
   69860 
   69861 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   69862 /* Opcode: IntegrityCk P1 P2 P3 * P5
   69863 **
   69864 ** Do an analysis of the currently open database.  Store in
   69865 ** register P1 the text of an error message describing any problems.
   69866 ** If no problems are found, store a NULL in register P1.
   69867 **
   69868 ** The register P3 contains the maximum number of allowed errors.
   69869 ** At most reg(P3) errors will be reported.
   69870 ** In other words, the analysis stops as soon as reg(P1) errors are
   69871 ** seen.  Reg(P1) is updated with the number of errors remaining.
   69872 **
   69873 ** The root page numbers of all tables in the database are integer
   69874 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   69875 ** total.
   69876 **
   69877 ** If P5 is not zero, the check is done on the auxiliary database
   69878 ** file, not the main database file.
   69879 **
   69880 ** This opcode is used to implement the integrity_check pragma.
   69881 */
   69882 case OP_IntegrityCk: {
   69883 #if 0  /* local variables moved into u.bz */
   69884   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   69885   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   69886   int j;          /* Loop counter */
   69887   int nErr;       /* Number of errors reported */
   69888   char *z;        /* Text of the error report */
   69889   Mem *pnErr;     /* Register keeping track of errors remaining */
   69890 #endif /* local variables moved into u.bz */
   69891 
   69892   u.bz.nRoot = pOp->p2;
   69893   assert( u.bz.nRoot>0 );
   69894   u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
   69895   if( u.bz.aRoot==0 ) goto no_mem;
   69896   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   69897   u.bz.pnErr = &aMem[pOp->p3];
   69898   assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
   69899   assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   69900   pIn1 = &aMem[pOp->p1];
   69901   for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
   69902     u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
   69903   }
   69904   u.bz.aRoot[u.bz.j] = 0;
   69905   assert( pOp->p5<db->nDb );
   69906   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
   69907   u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
   69908                                  (int)u.bz.pnErr->u.i, &u.bz.nErr);
   69909   sqlite3DbFree(db, u.bz.aRoot);
   69910   u.bz.pnErr->u.i -= u.bz.nErr;
   69911   sqlite3VdbeMemSetNull(pIn1);
   69912   if( u.bz.nErr==0 ){
   69913     assert( u.bz.z==0 );
   69914   }else if( u.bz.z==0 ){
   69915     goto no_mem;
   69916   }else{
   69917     sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
   69918   }
   69919   UPDATE_MAX_BLOBSIZE(pIn1);
   69920   sqlite3VdbeChangeEncoding(pIn1, encoding);
   69921   break;
   69922 }
   69923 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   69924 
   69925 /* Opcode: RowSetAdd P1 P2 * * *
   69926 **
   69927 ** Insert the integer value held by register P2 into a boolean index
   69928 ** held in register P1.
   69929 **
   69930 ** An assertion fails if P2 is not an integer.
   69931 */
   69932 case OP_RowSetAdd: {       /* in1, in2 */
   69933   pIn1 = &aMem[pOp->p1];
   69934   pIn2 = &aMem[pOp->p2];
   69935   assert( (pIn2->flags & MEM_Int)!=0 );
   69936   if( (pIn1->flags & MEM_RowSet)==0 ){
   69937     sqlite3VdbeMemSetRowSet(pIn1);
   69938     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   69939   }
   69940   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   69941   break;
   69942 }
   69943 
   69944 /* Opcode: RowSetRead P1 P2 P3 * *
   69945 **
   69946 ** Extract the smallest value from boolean index P1 and put that value into
   69947 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   69948 ** unchanged and jump to instruction P2.
   69949 */
   69950 case OP_RowSetRead: {       /* jump, in1, out3 */
   69951 #if 0  /* local variables moved into u.ca */
   69952   i64 val;
   69953 #endif /* local variables moved into u.ca */
   69954   CHECK_FOR_INTERRUPT;
   69955   pIn1 = &aMem[pOp->p1];
   69956   if( (pIn1->flags & MEM_RowSet)==0
   69957    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
   69958   ){
   69959     /* The boolean index is empty */
   69960     sqlite3VdbeMemSetNull(pIn1);
   69961     pc = pOp->p2 - 1;
   69962   }else{
   69963     /* A value was pulled from the index */
   69964     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
   69965   }
   69966   break;
   69967 }
   69968 
   69969 /* Opcode: RowSetTest P1 P2 P3 P4
   69970 **
   69971 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   69972 ** contains a RowSet object and that RowSet object contains
   69973 ** the value held in P3, jump to register P2. Otherwise, insert the
   69974 ** integer in P3 into the RowSet and continue on to the
   69975 ** next opcode.
   69976 **
   69977 ** The RowSet object is optimized for the case where successive sets
   69978 ** of integers, where each set contains no duplicates. Each set
   69979 ** of values is identified by a unique P4 value. The first set
   69980 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   69981 ** non-negative.  For non-negative values of P4 only the lower 4
   69982 ** bits are significant.
   69983 **
   69984 ** This allows optimizations: (a) when P4==0 there is no need to test
   69985 ** the rowset object for P3, as it is guaranteed not to contain it,
   69986 ** (b) when P4==-1 there is no need to insert the value, as it will
   69987 ** never be tested for, and (c) when a value that is part of set X is
   69988 ** inserted, there is no need to search to see if the same value was
   69989 ** previously inserted as part of set X (only if it was previously
   69990 ** inserted as part of some other set).
   69991 */
   69992 case OP_RowSetTest: {                     /* jump, in1, in3 */
   69993 #if 0  /* local variables moved into u.cb */
   69994   int iSet;
   69995   int exists;
   69996 #endif /* local variables moved into u.cb */
   69997 
   69998   pIn1 = &aMem[pOp->p1];
   69999   pIn3 = &aMem[pOp->p3];
   70000   u.cb.iSet = pOp->p4.i;
   70001   assert( pIn3->flags&MEM_Int );
   70002 
   70003   /* If there is anything other than a rowset object in memory cell P1,
   70004   ** delete it now and initialize P1 with an empty rowset
   70005   */
   70006   if( (pIn1->flags & MEM_RowSet)==0 ){
   70007     sqlite3VdbeMemSetRowSet(pIn1);
   70008     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   70009   }
   70010 
   70011   assert( pOp->p4type==P4_INT32 );
   70012   assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
   70013   if( u.cb.iSet ){
   70014     u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
   70015                                (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
   70016                                pIn3->u.i);
   70017     if( u.cb.exists ){
   70018       pc = pOp->p2 - 1;
   70019       break;
   70020     }
   70021   }
   70022   if( u.cb.iSet>=0 ){
   70023     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   70024   }
   70025   break;
   70026 }
   70027 
   70028 
   70029 #ifndef SQLITE_OMIT_TRIGGER
   70030 
   70031 /* Opcode: Program P1 P2 P3 P4 *
   70032 **
   70033 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   70034 **
   70035 ** P1 contains the address of the memory cell that contains the first memory
   70036 ** cell in an array of values used as arguments to the sub-program. P2
   70037 ** contains the address to jump to if the sub-program throws an IGNORE
   70038 ** exception using the RAISE() function. Register P3 contains the address
   70039 ** of a memory cell in this (the parent) VM that is used to allocate the
   70040 ** memory required by the sub-vdbe at runtime.
   70041 **
   70042 ** P4 is a pointer to the VM containing the trigger program.
   70043 */
   70044 case OP_Program: {        /* jump */
   70045 #if 0  /* local variables moved into u.cc */
   70046   int nMem;               /* Number of memory registers for sub-program */
   70047   int nByte;              /* Bytes of runtime space required for sub-program */
   70048   Mem *pRt;               /* Register to allocate runtime space */
   70049   Mem *pMem;              /* Used to iterate through memory cells */
   70050   Mem *pEnd;              /* Last memory cell in new array */
   70051   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   70052   SubProgram *pProgram;   /* Sub-program to execute */
   70053   void *t;                /* Token identifying trigger */
   70054 #endif /* local variables moved into u.cc */
   70055 
   70056   u.cc.pProgram = pOp->p4.pProgram;
   70057   u.cc.pRt = &aMem[pOp->p3];
   70058   assert( u.cc.pProgram->nOp>0 );
   70059 
   70060   /* If the p5 flag is clear, then recursive invocation of triggers is
   70061   ** disabled for backwards compatibility (p5 is set if this sub-program
   70062   ** is really a trigger, not a foreign key action, and the flag set
   70063   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   70064   **
   70065   ** It is recursive invocation of triggers, at the SQL level, that is
   70066   ** disabled. In some cases a single trigger may generate more than one
   70067   ** SubProgram (if the trigger may be executed with more than one different
   70068   ** ON CONFLICT algorithm). SubProgram structures associated with a
   70069   ** single trigger all have the same value for the SubProgram.token
   70070   ** variable.  */
   70071   if( pOp->p5 ){
   70072     u.cc.t = u.cc.pProgram->token;
   70073     for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
   70074     if( u.cc.pFrame ) break;
   70075   }
   70076 
   70077   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   70078     rc = SQLITE_ERROR;
   70079     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   70080     break;
   70081   }
   70082 
   70083   /* Register u.cc.pRt is used to store the memory required to save the state
   70084   ** of the current program, and the memory required at runtime to execute
   70085   ** the trigger program. If this trigger has been fired before, then u.cc.pRt
   70086   ** is already allocated. Otherwise, it must be initialized.  */
   70087   if( (u.cc.pRt->flags&MEM_Frame)==0 ){
   70088     /* SubProgram.nMem is set to the number of memory cells used by the
   70089     ** program stored in SubProgram.aOp. As well as these, one memory
   70090     ** cell is required for each cursor used by the program. Set local
   70091     ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
   70092     */
   70093     u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
   70094     u.cc.nByte = ROUND8(sizeof(VdbeFrame))
   70095               + u.cc.nMem * sizeof(Mem)
   70096               + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
   70097               + u.cc.pProgram->nOnce * sizeof(u8);
   70098     u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
   70099     if( !u.cc.pFrame ){
   70100       goto no_mem;
   70101     }
   70102     sqlite3VdbeMemRelease(u.cc.pRt);
   70103     u.cc.pRt->flags = MEM_Frame;
   70104     u.cc.pRt->u.pFrame = u.cc.pFrame;
   70105 
   70106     u.cc.pFrame->v = p;
   70107     u.cc.pFrame->nChildMem = u.cc.nMem;
   70108     u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
   70109     u.cc.pFrame->pc = pc;
   70110     u.cc.pFrame->aMem = p->aMem;
   70111     u.cc.pFrame->nMem = p->nMem;
   70112     u.cc.pFrame->apCsr = p->apCsr;
   70113     u.cc.pFrame->nCursor = p->nCursor;
   70114     u.cc.pFrame->aOp = p->aOp;
   70115     u.cc.pFrame->nOp = p->nOp;
   70116     u.cc.pFrame->token = u.cc.pProgram->token;
   70117     u.cc.pFrame->aOnceFlag = p->aOnceFlag;
   70118     u.cc.pFrame->nOnceFlag = p->nOnceFlag;
   70119 
   70120     u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
   70121     for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
   70122       u.cc.pMem->flags = MEM_Invalid;
   70123       u.cc.pMem->db = db;
   70124     }
   70125   }else{
   70126     u.cc.pFrame = u.cc.pRt->u.pFrame;
   70127     assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
   70128     assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
   70129     assert( pc==u.cc.pFrame->pc );
   70130   }
   70131 
   70132   p->nFrame++;
   70133   u.cc.pFrame->pParent = p->pFrame;
   70134   u.cc.pFrame->lastRowid = lastRowid;
   70135   u.cc.pFrame->nChange = p->nChange;
   70136   p->nChange = 0;
   70137   p->pFrame = u.cc.pFrame;
   70138   p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
   70139   p->nMem = u.cc.pFrame->nChildMem;
   70140   p->nCursor = (u16)u.cc.pFrame->nChildCsr;
   70141   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   70142   p->aOp = aOp = u.cc.pProgram->aOp;
   70143   p->nOp = u.cc.pProgram->nOp;
   70144   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
   70145   p->nOnceFlag = u.cc.pProgram->nOnce;
   70146   pc = -1;
   70147   memset(p->aOnceFlag, 0, p->nOnceFlag);
   70148 
   70149   break;
   70150 }
   70151 
   70152 /* Opcode: Param P1 P2 * * *
   70153 **
   70154 ** This opcode is only ever present in sub-programs called via the
   70155 ** OP_Program instruction. Copy a value currently stored in a memory
   70156 ** cell of the calling (parent) frame to cell P2 in the current frames
   70157 ** address space. This is used by trigger programs to access the new.*
   70158 ** and old.* values.
   70159 **
   70160 ** The address of the cell in the parent frame is determined by adding
   70161 ** the value of the P1 argument to the value of the P1 argument to the
   70162 ** calling OP_Program instruction.
   70163 */
   70164 case OP_Param: {           /* out2-prerelease */
   70165 #if 0  /* local variables moved into u.cd */
   70166   VdbeFrame *pFrame;
   70167   Mem *pIn;
   70168 #endif /* local variables moved into u.cd */
   70169   u.cd.pFrame = p->pFrame;
   70170   u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
   70171   sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
   70172   break;
   70173 }
   70174 
   70175 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   70176 
   70177 #ifndef SQLITE_OMIT_FOREIGN_KEY
   70178 /* Opcode: FkCounter P1 P2 * * *
   70179 **
   70180 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   70181 ** If P1 is non-zero, the database constraint counter is incremented
   70182 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   70183 ** statement counter is incremented (immediate foreign key constraints).
   70184 */
   70185 case OP_FkCounter: {
   70186   if( pOp->p1 ){
   70187     db->nDeferredCons += pOp->p2;
   70188   }else{
   70189     p->nFkConstraint += pOp->p2;
   70190   }
   70191   break;
   70192 }
   70193 
   70194 /* Opcode: FkIfZero P1 P2 * * *
   70195 **
   70196 ** This opcode tests if a foreign key constraint-counter is currently zero.
   70197 ** If so, jump to instruction P2. Otherwise, fall through to the next
   70198 ** instruction.
   70199 **
   70200 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   70201 ** is zero (the one that counts deferred constraint violations). If P1 is
   70202 ** zero, the jump is taken if the statement constraint-counter is zero
   70203 ** (immediate foreign key constraint violations).
   70204 */
   70205 case OP_FkIfZero: {         /* jump */
   70206   if( pOp->p1 ){
   70207     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
   70208   }else{
   70209     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
   70210   }
   70211   break;
   70212 }
   70213 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   70214 
   70215 #ifndef SQLITE_OMIT_AUTOINCREMENT
   70216 /* Opcode: MemMax P1 P2 * * *
   70217 **
   70218 ** P1 is a register in the root frame of this VM (the root frame is
   70219 ** different from the current frame if this instruction is being executed
   70220 ** within a sub-program). Set the value of register P1 to the maximum of
   70221 ** its current value and the value in register P2.
   70222 **
   70223 ** This instruction throws an error if the memory cell is not initially
   70224 ** an integer.
   70225 */
   70226 case OP_MemMax: {        /* in2 */
   70227 #if 0  /* local variables moved into u.ce */
   70228   Mem *pIn1;
   70229   VdbeFrame *pFrame;
   70230 #endif /* local variables moved into u.ce */
   70231   if( p->pFrame ){
   70232     for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
   70233     u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
   70234   }else{
   70235     u.ce.pIn1 = &aMem[pOp->p1];
   70236   }
   70237   assert( memIsValid(u.ce.pIn1) );
   70238   sqlite3VdbeMemIntegerify(u.ce.pIn1);
   70239   pIn2 = &aMem[pOp->p2];
   70240   sqlite3VdbeMemIntegerify(pIn2);
   70241   if( u.ce.pIn1->u.i<pIn2->u.i){
   70242     u.ce.pIn1->u.i = pIn2->u.i;
   70243   }
   70244   break;
   70245 }
   70246 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   70247 
   70248 /* Opcode: IfPos P1 P2 * * *
   70249 **
   70250 ** If the value of register P1 is 1 or greater, jump to P2.
   70251 **
   70252 ** It is illegal to use this instruction on a register that does
   70253 ** not contain an integer.  An assertion fault will result if you try.
   70254 */
   70255 case OP_IfPos: {        /* jump, in1 */
   70256   pIn1 = &aMem[pOp->p1];
   70257   assert( pIn1->flags&MEM_Int );
   70258   if( pIn1->u.i>0 ){
   70259      pc = pOp->p2 - 1;
   70260   }
   70261   break;
   70262 }
   70263 
   70264 /* Opcode: IfNeg P1 P2 * * *
   70265 **
   70266 ** If the value of register P1 is less than zero, jump to P2.
   70267 **
   70268 ** It is illegal to use this instruction on a register that does
   70269 ** not contain an integer.  An assertion fault will result if you try.
   70270 */
   70271 case OP_IfNeg: {        /* jump, in1 */
   70272   pIn1 = &aMem[pOp->p1];
   70273   assert( pIn1->flags&MEM_Int );
   70274   if( pIn1->u.i<0 ){
   70275      pc = pOp->p2 - 1;
   70276   }
   70277   break;
   70278 }
   70279 
   70280 /* Opcode: IfZero P1 P2 P3 * *
   70281 **
   70282 ** The register P1 must contain an integer.  Add literal P3 to the
   70283 ** value in register P1.  If the result is exactly 0, 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_IfZero: {        /* jump, in1 */
   70289   pIn1 = &aMem[pOp->p1];
   70290   assert( pIn1->flags&MEM_Int );
   70291   pIn1->u.i += pOp->p3;
   70292   if( pIn1->u.i==0 ){
   70293      pc = pOp->p2 - 1;
   70294   }
   70295   break;
   70296 }
   70297 
   70298 /* Opcode: AggStep * P2 P3 P4 P5
   70299 **
   70300 ** Execute the step function for an aggregate.  The
   70301 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   70302 ** structure that specifies the function.  Use register
   70303 ** P3 as the accumulator.
   70304 **
   70305 ** The P5 arguments are taken from register P2 and its
   70306 ** successors.
   70307 */
   70308 case OP_AggStep: {
   70309 #if 0  /* local variables moved into u.cf */
   70310   int n;
   70311   int i;
   70312   Mem *pMem;
   70313   Mem *pRec;
   70314   sqlite3_context ctx;
   70315   sqlite3_value **apVal;
   70316 #endif /* local variables moved into u.cf */
   70317 
   70318   u.cf.n = pOp->p5;
   70319   assert( u.cf.n>=0 );
   70320   u.cf.pRec = &aMem[pOp->p2];
   70321   u.cf.apVal = p->apArg;
   70322   assert( u.cf.apVal || u.cf.n==0 );
   70323   for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
   70324     assert( memIsValid(u.cf.pRec) );
   70325     u.cf.apVal[u.cf.i] = u.cf.pRec;
   70326     memAboutToChange(p, u.cf.pRec);
   70327     sqlite3VdbeMemStoreType(u.cf.pRec);
   70328   }
   70329   u.cf.ctx.pFunc = pOp->p4.pFunc;
   70330   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   70331   u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
   70332   u.cf.pMem->n++;
   70333   u.cf.ctx.s.flags = MEM_Null;
   70334   u.cf.ctx.s.z = 0;
   70335   u.cf.ctx.s.zMalloc = 0;
   70336   u.cf.ctx.s.xDel = 0;
   70337   u.cf.ctx.s.db = db;
   70338   u.cf.ctx.isError = 0;
   70339   u.cf.ctx.pColl = 0;
   70340   u.cf.ctx.skipFlag = 0;
   70341   if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   70342     assert( pOp>p->aOp );
   70343     assert( pOp[-1].p4type==P4_COLLSEQ );
   70344     assert( pOp[-1].opcode==OP_CollSeq );
   70345     u.cf.ctx.pColl = pOp[-1].p4.pColl;
   70346   }
   70347   (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
   70348   if( u.cf.ctx.isError ){
   70349     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
   70350     rc = u.cf.ctx.isError;
   70351   }
   70352   if( u.cf.ctx.skipFlag ){
   70353     assert( pOp[-1].opcode==OP_CollSeq );
   70354     u.cf.i = pOp[-1].p1;
   70355     if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
   70356   }
   70357 
   70358   sqlite3VdbeMemRelease(&u.cf.ctx.s);
   70359 
   70360   break;
   70361 }
   70362 
   70363 /* Opcode: AggFinal P1 P2 * P4 *
   70364 **
   70365 ** Execute the finalizer function for an aggregate.  P1 is
   70366 ** the memory location that is the accumulator for the aggregate.
   70367 **
   70368 ** P2 is the number of arguments that the step function takes and
   70369 ** P4 is a pointer to the FuncDef for this function.  The P2
   70370 ** argument is not used by this opcode.  It is only there to disambiguate
   70371 ** functions that can take varying numbers of arguments.  The
   70372 ** P4 argument is only needed for the degenerate case where
   70373 ** the step function was not previously called.
   70374 */
   70375 case OP_AggFinal: {
   70376 #if 0  /* local variables moved into u.cg */
   70377   Mem *pMem;
   70378 #endif /* local variables moved into u.cg */
   70379   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   70380   u.cg.pMem = &aMem[pOp->p1];
   70381   assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   70382   rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
   70383   if( rc ){
   70384     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
   70385   }
   70386   sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
   70387   UPDATE_MAX_BLOBSIZE(u.cg.pMem);
   70388   if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
   70389     goto too_big;
   70390   }
   70391   break;
   70392 }
   70393 
   70394 #ifndef SQLITE_OMIT_WAL
   70395 /* Opcode: Checkpoint P1 P2 P3 * *
   70396 **
   70397 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   70398 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
   70399 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
   70400 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
   70401 ** WAL after the checkpoint into mem[P3+1] and the number of pages
   70402 ** in the WAL that have been checkpointed after the checkpoint
   70403 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
   70404 ** mem[P3+2] are initialized to -1.
   70405 */
   70406 case OP_Checkpoint: {
   70407 #if 0  /* local variables moved into u.ch */
   70408   int i;                          /* Loop counter */
   70409   int aRes[3];                    /* Results */
   70410   Mem *pMem;                      /* Write results here */
   70411 #endif /* local variables moved into u.ch */
   70412 
   70413   u.ch.aRes[0] = 0;
   70414   u.ch.aRes[1] = u.ch.aRes[2] = -1;
   70415   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
   70416        || pOp->p2==SQLITE_CHECKPOINT_FULL
   70417        || pOp->p2==SQLITE_CHECKPOINT_RESTART
   70418   );
   70419   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
   70420   if( rc==SQLITE_BUSY ){
   70421     rc = SQLITE_OK;
   70422     u.ch.aRes[0] = 1;
   70423   }
   70424   for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
   70425     sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
   70426   }
   70427   break;
   70428 };
   70429 #endif
   70430 
   70431 #ifndef SQLITE_OMIT_PRAGMA
   70432 /* Opcode: JournalMode P1 P2 P3 * P5
   70433 **
   70434 ** Change the journal mode of database P1 to P3. P3 must be one of the
   70435 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   70436 ** modes (delete, truncate, persist, off and memory), this is a simple
   70437 ** operation. No IO is required.
   70438 **
   70439 ** If changing into or out of WAL mode the procedure is more complicated.
   70440 **
   70441 ** Write a string containing the final journal-mode to register P2.
   70442 */
   70443 case OP_JournalMode: {    /* out2-prerelease */
   70444 #if 0  /* local variables moved into u.ci */
   70445   Btree *pBt;                     /* Btree to change journal mode of */
   70446   Pager *pPager;                  /* Pager associated with pBt */
   70447   int eNew;                       /* New journal mode */
   70448   int eOld;                       /* The old journal mode */
   70449   const char *zFilename;          /* Name of database file for pPager */
   70450 #endif /* local variables moved into u.ci */
   70451 
   70452   u.ci.eNew = pOp->p3;
   70453   assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
   70454        || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
   70455        || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
   70456        || u.ci.eNew==PAGER_JOURNALMODE_OFF
   70457        || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
   70458        || u.ci.eNew==PAGER_JOURNALMODE_WAL
   70459        || u.ci.eNew==PAGER_JOURNALMODE_QUERY
   70460   );
   70461   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   70462 
   70463   u.ci.pBt = db->aDb[pOp->p1].pBt;
   70464   u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
   70465   u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
   70466   if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
   70467   if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
   70468 
   70469 #ifndef SQLITE_OMIT_WAL
   70470   u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager);
   70471 
   70472   /* Do not allow a transition to journal_mode=WAL for a database
   70473   ** in temporary storage or if the VFS does not support shared memory
   70474   */
   70475   if( u.ci.eNew==PAGER_JOURNALMODE_WAL
   70476    && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
   70477        || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
   70478   ){
   70479     u.ci.eNew = u.ci.eOld;
   70480   }
   70481 
   70482   if( (u.ci.eNew!=u.ci.eOld)
   70483    && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
   70484   ){
   70485     if( !db->autoCommit || db->activeVdbeCnt>1 ){
   70486       rc = SQLITE_ERROR;
   70487       sqlite3SetString(&p->zErrMsg, db,
   70488           "cannot change %s wal mode from within a transaction",
   70489           (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   70490       );
   70491       break;
   70492     }else{
   70493 
   70494       if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
   70495         /* If leaving WAL mode, close the log file. If successful, the call
   70496         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   70497         ** file. An EXCLUSIVE lock may still be held on the database file
   70498         ** after a successful return.
   70499         */
   70500         rc = sqlite3PagerCloseWal(u.ci.pPager);
   70501         if( rc==SQLITE_OK ){
   70502           sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
   70503         }
   70504       }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
   70505         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   70506         ** as an intermediate */
   70507         sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
   70508       }
   70509 
   70510       /* Open a transaction on the database file. Regardless of the journal
   70511       ** mode, this transaction always uses a rollback journal.
   70512       */
   70513       assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
   70514       if( rc==SQLITE_OK ){
   70515         rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   70516       }
   70517     }
   70518   }
   70519 #endif /* ifndef SQLITE_OMIT_WAL */
   70520 
   70521   if( rc ){
   70522     u.ci.eNew = u.ci.eOld;
   70523   }
   70524   u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
   70525 
   70526   pOut = &aMem[pOp->p2];
   70527   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   70528   pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
   70529   pOut->n = sqlite3Strlen30(pOut->z);
   70530   pOut->enc = SQLITE_UTF8;
   70531   sqlite3VdbeChangeEncoding(pOut, encoding);
   70532   break;
   70533 };
   70534 #endif /* SQLITE_OMIT_PRAGMA */
   70535 
   70536 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   70537 /* Opcode: Vacuum * * * * *
   70538 **
   70539 ** Vacuum the entire database.  This opcode will cause other virtual
   70540 ** machines to be created and run.  It may not be called from within
   70541 ** a transaction.
   70542 */
   70543 case OP_Vacuum: {
   70544   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   70545   break;
   70546 }
   70547 #endif
   70548 
   70549 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   70550 /* Opcode: IncrVacuum P1 P2 * * *
   70551 **
   70552 ** Perform a single step of the incremental vacuum procedure on
   70553 ** the P1 database. If the vacuum has finished, jump to instruction
   70554 ** P2. Otherwise, fall through to the next instruction.
   70555 */
   70556 case OP_IncrVacuum: {        /* jump */
   70557 #if 0  /* local variables moved into u.cj */
   70558   Btree *pBt;
   70559 #endif /* local variables moved into u.cj */
   70560 
   70561   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   70562   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
   70563   u.cj.pBt = db->aDb[pOp->p1].pBt;
   70564   rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
   70565   if( rc==SQLITE_DONE ){
   70566     pc = pOp->p2 - 1;
   70567     rc = SQLITE_OK;
   70568   }
   70569   break;
   70570 }
   70571 #endif
   70572 
   70573 /* Opcode: Expire P1 * * * *
   70574 **
   70575 ** Cause precompiled statements to become expired. An expired statement
   70576 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
   70577 ** (via sqlite3_step()).
   70578 **
   70579 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   70580 ** then only the currently executing statement is affected.
   70581 */
   70582 case OP_Expire: {
   70583   if( !pOp->p1 ){
   70584     sqlite3ExpirePreparedStatements(db);
   70585   }else{
   70586     p->expired = 1;
   70587   }
   70588   break;
   70589 }
   70590 
   70591 #ifndef SQLITE_OMIT_SHARED_CACHE
   70592 /* Opcode: TableLock P1 P2 P3 P4 *
   70593 **
   70594 ** Obtain a lock on a particular table. This instruction is only used when
   70595 ** the shared-cache feature is enabled.
   70596 **
   70597 ** P1 is the index of the database in sqlite3.aDb[] of the database
   70598 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   70599 ** a write lock if P3==1.
   70600 **
   70601 ** P2 contains the root-page of the table to lock.
   70602 **
   70603 ** P4 contains a pointer to the name of the table being locked. This is only
   70604 ** used to generate an error message if the lock cannot be obtained.
   70605 */
   70606 case OP_TableLock: {
   70607   u8 isWriteLock = (u8)pOp->p3;
   70608   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   70609     int p1 = pOp->p1;
   70610     assert( p1>=0 && p1<db->nDb );
   70611     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
   70612     assert( isWriteLock==0 || isWriteLock==1 );
   70613     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   70614     if( (rc&0xFF)==SQLITE_LOCKED ){
   70615       const char *z = pOp->p4.z;
   70616       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   70617     }
   70618   }
   70619   break;
   70620 }
   70621 #endif /* SQLITE_OMIT_SHARED_CACHE */
   70622 
   70623 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70624 /* Opcode: VBegin * * * P4 *
   70625 **
   70626 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   70627 ** xBegin method for that table.
   70628 **
   70629 ** Also, whether or not P4 is set, check that this is not being called from
   70630 ** within a callback to a virtual table xSync() method. If it is, the error
   70631 ** code will be set to SQLITE_LOCKED.
   70632 */
   70633 case OP_VBegin: {
   70634 #if 0  /* local variables moved into u.ck */
   70635   VTable *pVTab;
   70636 #endif /* local variables moved into u.ck */
   70637   u.ck.pVTab = pOp->p4.pVtab;
   70638   rc = sqlite3VtabBegin(db, u.ck.pVTab);
   70639   if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
   70640   break;
   70641 }
   70642 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70643 
   70644 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70645 /* Opcode: VCreate P1 * * P4 *
   70646 **
   70647 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   70648 ** for that table.
   70649 */
   70650 case OP_VCreate: {
   70651   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   70652   break;
   70653 }
   70654 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70655 
   70656 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70657 /* Opcode: VDestroy P1 * * P4 *
   70658 **
   70659 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   70660 ** of that table.
   70661 */
   70662 case OP_VDestroy: {
   70663   p->inVtabMethod = 2;
   70664   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   70665   p->inVtabMethod = 0;
   70666   break;
   70667 }
   70668 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70669 
   70670 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70671 /* Opcode: VOpen P1 * * P4 *
   70672 **
   70673 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70674 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   70675 ** table and stores that cursor in P1.
   70676 */
   70677 case OP_VOpen: {
   70678 #if 0  /* local variables moved into u.cl */
   70679   VdbeCursor *pCur;
   70680   sqlite3_vtab_cursor *pVtabCursor;
   70681   sqlite3_vtab *pVtab;
   70682   sqlite3_module *pModule;
   70683 #endif /* local variables moved into u.cl */
   70684 
   70685   u.cl.pCur = 0;
   70686   u.cl.pVtabCursor = 0;
   70687   u.cl.pVtab = pOp->p4.pVtab->pVtab;
   70688   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
   70689   assert(u.cl.pVtab && u.cl.pModule);
   70690   rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
   70691   importVtabErrMsg(p, u.cl.pVtab);
   70692   if( SQLITE_OK==rc ){
   70693     /* Initialize sqlite3_vtab_cursor base class */
   70694     u.cl.pVtabCursor->pVtab = u.cl.pVtab;
   70695 
   70696     /* Initialise vdbe cursor object */
   70697     u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   70698     if( u.cl.pCur ){
   70699       u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
   70700       u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
   70701     }else{
   70702       db->mallocFailed = 1;
   70703       u.cl.pModule->xClose(u.cl.pVtabCursor);
   70704     }
   70705   }
   70706   break;
   70707 }
   70708 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70709 
   70710 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70711 /* Opcode: VFilter P1 P2 P3 P4 *
   70712 **
   70713 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   70714 ** the filtered result set is empty.
   70715 **
   70716 ** P4 is either NULL or a string that was generated by the xBestIndex
   70717 ** method of the module.  The interpretation of the P4 string is left
   70718 ** to the module implementation.
   70719 **
   70720 ** This opcode invokes the xFilter method on the virtual table specified
   70721 ** by P1.  The integer query plan parameter to xFilter is stored in register
   70722 ** P3. Register P3+1 stores the argc parameter to be passed to the
   70723 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   70724 ** additional parameters which are passed to
   70725 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   70726 **
   70727 ** A jump is made to P2 if the result set after filtering would be empty.
   70728 */
   70729 case OP_VFilter: {   /* jump */
   70730 #if 0  /* local variables moved into u.cm */
   70731   int nArg;
   70732   int iQuery;
   70733   const sqlite3_module *pModule;
   70734   Mem *pQuery;
   70735   Mem *pArgc;
   70736   sqlite3_vtab_cursor *pVtabCursor;
   70737   sqlite3_vtab *pVtab;
   70738   VdbeCursor *pCur;
   70739   int res;
   70740   int i;
   70741   Mem **apArg;
   70742 #endif /* local variables moved into u.cm */
   70743 
   70744   u.cm.pQuery = &aMem[pOp->p3];
   70745   u.cm.pArgc = &u.cm.pQuery[1];
   70746   u.cm.pCur = p->apCsr[pOp->p1];
   70747   assert( memIsValid(u.cm.pQuery) );
   70748   REGISTER_TRACE(pOp->p3, u.cm.pQuery);
   70749   assert( u.cm.pCur->pVtabCursor );
   70750   u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
   70751   u.cm.pVtab = u.cm.pVtabCursor->pVtab;
   70752   u.cm.pModule = u.cm.pVtab->pModule;
   70753 
   70754   /* Grab the index number and argc parameters */
   70755   assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
   70756   u.cm.nArg = (int)u.cm.pArgc->u.i;
   70757   u.cm.iQuery = (int)u.cm.pQuery->u.i;
   70758 
   70759   /* Invoke the xFilter method */
   70760   {
   70761     u.cm.res = 0;
   70762     u.cm.apArg = p->apArg;
   70763     for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
   70764       u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
   70765       sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
   70766     }
   70767 
   70768     p->inVtabMethod = 1;
   70769     rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
   70770     p->inVtabMethod = 0;
   70771     importVtabErrMsg(p, u.cm.pVtab);
   70772     if( rc==SQLITE_OK ){
   70773       u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
   70774     }
   70775 
   70776     if( u.cm.res ){
   70777       pc = pOp->p2 - 1;
   70778     }
   70779   }
   70780   u.cm.pCur->nullRow = 0;
   70781 
   70782   break;
   70783 }
   70784 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70785 
   70786 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70787 /* Opcode: VColumn P1 P2 P3 * *
   70788 **
   70789 ** Store the value of the P2-th column of
   70790 ** the row of the virtual-table that the
   70791 ** P1 cursor is pointing to into register P3.
   70792 */
   70793 case OP_VColumn: {
   70794 #if 0  /* local variables moved into u.cn */
   70795   sqlite3_vtab *pVtab;
   70796   const sqlite3_module *pModule;
   70797   Mem *pDest;
   70798   sqlite3_context sContext;
   70799 #endif /* local variables moved into u.cn */
   70800 
   70801   VdbeCursor *pCur = p->apCsr[pOp->p1];
   70802   assert( pCur->pVtabCursor );
   70803   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   70804   u.cn.pDest = &aMem[pOp->p3];
   70805   memAboutToChange(p, u.cn.pDest);
   70806   if( pCur->nullRow ){
   70807     sqlite3VdbeMemSetNull(u.cn.pDest);
   70808     break;
   70809   }
   70810   u.cn.pVtab = pCur->pVtabCursor->pVtab;
   70811   u.cn.pModule = u.cn.pVtab->pModule;
   70812   assert( u.cn.pModule->xColumn );
   70813   memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
   70814 
   70815   /* The output cell may already have a buffer allocated. Move
   70816   ** the current contents to u.cn.sContext.s so in case the user-function
   70817   ** can use the already allocated buffer instead of allocating a
   70818   ** new one.
   70819   */
   70820   sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
   70821   MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
   70822 
   70823   rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
   70824   importVtabErrMsg(p, u.cn.pVtab);
   70825   if( u.cn.sContext.isError ){
   70826     rc = u.cn.sContext.isError;
   70827   }
   70828 
   70829   /* Copy the result of the function to the P3 register. We
   70830   ** do this regardless of whether or not an error occurred to ensure any
   70831   ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
   70832   */
   70833   sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
   70834   sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
   70835   REGISTER_TRACE(pOp->p3, u.cn.pDest);
   70836   UPDATE_MAX_BLOBSIZE(u.cn.pDest);
   70837 
   70838   if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
   70839     goto too_big;
   70840   }
   70841   break;
   70842 }
   70843 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70844 
   70845 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70846 /* Opcode: VNext P1 P2 * * *
   70847 **
   70848 ** Advance virtual table P1 to the next row in its result set and
   70849 ** jump to instruction P2.  Or, if the virtual table has reached
   70850 ** the end of its result set, then fall through to the next instruction.
   70851 */
   70852 case OP_VNext: {   /* jump */
   70853 #if 0  /* local variables moved into u.co */
   70854   sqlite3_vtab *pVtab;
   70855   const sqlite3_module *pModule;
   70856   int res;
   70857   VdbeCursor *pCur;
   70858 #endif /* local variables moved into u.co */
   70859 
   70860   u.co.res = 0;
   70861   u.co.pCur = p->apCsr[pOp->p1];
   70862   assert( u.co.pCur->pVtabCursor );
   70863   if( u.co.pCur->nullRow ){
   70864     break;
   70865   }
   70866   u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
   70867   u.co.pModule = u.co.pVtab->pModule;
   70868   assert( u.co.pModule->xNext );
   70869 
   70870   /* Invoke the xNext() method of the module. There is no way for the
   70871   ** underlying implementation to return an error if one occurs during
   70872   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   70873   ** data is available) and the error code returned when xColumn or
   70874   ** some other method is next invoked on the save virtual table cursor.
   70875   */
   70876   p->inVtabMethod = 1;
   70877   rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
   70878   p->inVtabMethod = 0;
   70879   importVtabErrMsg(p, u.co.pVtab);
   70880   if( rc==SQLITE_OK ){
   70881     u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
   70882   }
   70883 
   70884   if( !u.co.res ){
   70885     /* If there is data, jump to P2 */
   70886     pc = pOp->p2 - 1;
   70887   }
   70888   break;
   70889 }
   70890 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70891 
   70892 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70893 /* Opcode: VRename P1 * * P4 *
   70894 **
   70895 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70896 ** This opcode invokes the corresponding xRename method. The value
   70897 ** in register P1 is passed as the zName argument to the xRename method.
   70898 */
   70899 case OP_VRename: {
   70900 #if 0  /* local variables moved into u.cp */
   70901   sqlite3_vtab *pVtab;
   70902   Mem *pName;
   70903 #endif /* local variables moved into u.cp */
   70904 
   70905   u.cp.pVtab = pOp->p4.pVtab->pVtab;
   70906   u.cp.pName = &aMem[pOp->p1];
   70907   assert( u.cp.pVtab->pModule->xRename );
   70908   assert( memIsValid(u.cp.pName) );
   70909   REGISTER_TRACE(pOp->p1, u.cp.pName);
   70910   assert( u.cp.pName->flags & MEM_Str );
   70911   testcase( u.cp.pName->enc==SQLITE_UTF8 );
   70912   testcase( u.cp.pName->enc==SQLITE_UTF16BE );
   70913   testcase( u.cp.pName->enc==SQLITE_UTF16LE );
   70914   rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
   70915   if( rc==SQLITE_OK ){
   70916     rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
   70917     importVtabErrMsg(p, u.cp.pVtab);
   70918     p->expired = 0;
   70919   }
   70920   break;
   70921 }
   70922 #endif
   70923 
   70924 #ifndef SQLITE_OMIT_VIRTUALTABLE
   70925 /* Opcode: VUpdate P1 P2 P3 P4 *
   70926 **
   70927 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   70928 ** This opcode invokes the corresponding xUpdate method. P2 values
   70929 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   70930 ** invocation. The value in register (P3+P2-1) corresponds to the
   70931 ** p2th element of the argv array passed to xUpdate.
   70932 **
   70933 ** The xUpdate method will do a DELETE or an INSERT or both.
   70934 ** The argv[0] element (which corresponds to memory cell P3)
   70935 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   70936 ** deletion occurs.  The argv[1] element is the rowid of the new
   70937 ** row.  This can be NULL to have the virtual table select the new
   70938 ** rowid for itself.  The subsequent elements in the array are
   70939 ** the values of columns in the new row.
   70940 **
   70941 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   70942 ** a row to delete.
   70943 **
   70944 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   70945 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   70946 ** is set to the value of the rowid for the row just inserted.
   70947 */
   70948 case OP_VUpdate: {
   70949 #if 0  /* local variables moved into u.cq */
   70950   sqlite3_vtab *pVtab;
   70951   sqlite3_module *pModule;
   70952   int nArg;
   70953   int i;
   70954   sqlite_int64 rowid;
   70955   Mem **apArg;
   70956   Mem *pX;
   70957 #endif /* local variables moved into u.cq */
   70958 
   70959   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
   70960        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   70961   );
   70962   u.cq.pVtab = pOp->p4.pVtab->pVtab;
   70963   u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
   70964   u.cq.nArg = pOp->p2;
   70965   assert( pOp->p4type==P4_VTAB );
   70966   if( ALWAYS(u.cq.pModule->xUpdate) ){
   70967     u8 vtabOnConflict = db->vtabOnConflict;
   70968     u.cq.apArg = p->apArg;
   70969     u.cq.pX = &aMem[pOp->p3];
   70970     for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
   70971       assert( memIsValid(u.cq.pX) );
   70972       memAboutToChange(p, u.cq.pX);
   70973       sqlite3VdbeMemStoreType(u.cq.pX);
   70974       u.cq.apArg[u.cq.i] = u.cq.pX;
   70975       u.cq.pX++;
   70976     }
   70977     db->vtabOnConflict = pOp->p5;
   70978     rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
   70979     db->vtabOnConflict = vtabOnConflict;
   70980     importVtabErrMsg(p, u.cq.pVtab);
   70981     if( rc==SQLITE_OK && pOp->p1 ){
   70982       assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
   70983       db->lastRowid = lastRowid = u.cq.rowid;
   70984     }
   70985     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
   70986       if( pOp->p5==OE_Ignore ){
   70987         rc = SQLITE_OK;
   70988       }else{
   70989         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
   70990       }
   70991     }else{
   70992       p->nChange++;
   70993     }
   70994   }
   70995   break;
   70996 }
   70997 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   70998 
   70999 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   71000 /* Opcode: Pagecount P1 P2 * * *
   71001 **
   71002 ** Write the current number of pages in database P1 to memory cell P2.
   71003 */
   71004 case OP_Pagecount: {            /* out2-prerelease */
   71005   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   71006   break;
   71007 }
   71008 #endif
   71009 
   71010 
   71011 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   71012 /* Opcode: MaxPgcnt P1 P2 P3 * *
   71013 **
   71014 ** Try to set the maximum page count for database P1 to the value in P3.
   71015 ** Do not let the maximum page count fall below the current page count and
   71016 ** do not change the maximum page count value if P3==0.
   71017 **
   71018 ** Store the maximum page count after the change in register P2.
   71019 */
   71020 case OP_MaxPgcnt: {            /* out2-prerelease */
   71021   unsigned int newMax;
   71022   Btree *pBt;
   71023 
   71024   pBt = db->aDb[pOp->p1].pBt;
   71025   newMax = 0;
   71026   if( pOp->p3 ){
   71027     newMax = sqlite3BtreeLastPage(pBt);
   71028     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   71029   }
   71030   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   71031   break;
   71032 }
   71033 #endif
   71034 
   71035 
   71036 #ifndef SQLITE_OMIT_TRACE
   71037 /* Opcode: Trace * * * P4 *
   71038 **
   71039 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   71040 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   71041 */
   71042 case OP_Trace: {
   71043 #if 0  /* local variables moved into u.cr */
   71044   char *zTrace;
   71045   char *z;
   71046 #endif /* local variables moved into u.cr */
   71047 
   71048   if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
   71049     u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
   71050     db->xTrace(db->pTraceArg, u.cr.z);
   71051     sqlite3DbFree(db, u.cr.z);
   71052   }
   71053 #ifdef SQLITE_DEBUG
   71054   if( (db->flags & SQLITE_SqlTrace)!=0
   71055    && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
   71056   ){
   71057     sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
   71058   }
   71059 #endif /* SQLITE_DEBUG */
   71060   break;
   71061 }
   71062 #endif
   71063 
   71064 
   71065 /* Opcode: Noop * * * * *
   71066 **
   71067 ** Do nothing.  This instruction is often useful as a jump
   71068 ** destination.
   71069 */
   71070 /*
   71071 ** The magic Explain opcode are only inserted when explain==2 (which
   71072 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   71073 ** This opcode records information from the optimizer.  It is the
   71074 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   71075 */
   71076 default: {          /* This is really OP_Noop and OP_Explain */
   71077   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   71078   break;
   71079 }
   71080 
   71081 /*****************************************************************************
   71082 ** The cases of the switch statement above this line should all be indented
   71083 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   71084 ** readability.  From this point on down, the normal indentation rules are
   71085 ** restored.
   71086 *****************************************************************************/
   71087     }
   71088 
   71089 #ifdef VDBE_PROFILE
   71090     {
   71091       u64 elapsed = sqlite3Hwtime() - start;
   71092       pOp->cycles += elapsed;
   71093       pOp->cnt++;
   71094 #if 0
   71095         fprintf(stdout, "%10llu ", elapsed);
   71096         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
   71097 #endif
   71098     }
   71099 #endif
   71100 
   71101     /* The following code adds nothing to the actual functionality
   71102     ** of the program.  It is only here for testing and debugging.
   71103     ** On the other hand, it does burn CPU cycles every time through
   71104     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   71105     */
   71106 #ifndef NDEBUG
   71107     assert( pc>=-1 && pc<p->nOp );
   71108 
   71109 #ifdef SQLITE_DEBUG
   71110     if( p->trace ){
   71111       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
   71112       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   71113         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
   71114       }
   71115       if( pOp->opflags & OPFLG_OUT3 ){
   71116         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
   71117       }
   71118     }
   71119 #endif  /* SQLITE_DEBUG */
   71120 #endif  /* NDEBUG */
   71121   }  /* The end of the for(;;) loop the loops through opcodes */
   71122 
   71123   /* If we reach this point, it means that execution is finished with
   71124   ** an error of some kind.
   71125   */
   71126 vdbe_error_halt:
   71127   assert( rc );
   71128   p->rc = rc;
   71129   testcase( sqlite3GlobalConfig.xLog!=0 );
   71130   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   71131                    pc, p->zSql, p->zErrMsg);
   71132   sqlite3VdbeHalt(p);
   71133   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   71134   rc = SQLITE_ERROR;
   71135   if( resetSchemaOnFault>0 ){
   71136     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
   71137   }
   71138 
   71139   /* This is the only way out of this procedure.  We have to
   71140   ** release the mutexes on btrees that were acquired at the
   71141   ** top. */
   71142 vdbe_return:
   71143   db->lastRowid = lastRowid;
   71144   sqlite3VdbeLeave(p);
   71145   return rc;
   71146 
   71147   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   71148   ** is encountered.
   71149   */
   71150 too_big:
   71151   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   71152   rc = SQLITE_TOOBIG;
   71153   goto vdbe_error_halt;
   71154 
   71155   /* Jump to here if a malloc() fails.
   71156   */
   71157 no_mem:
   71158   db->mallocFailed = 1;
   71159   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   71160   rc = SQLITE_NOMEM;
   71161   goto vdbe_error_halt;
   71162 
   71163   /* Jump to here for any other kind of fatal error.  The "rc" variable
   71164   ** should hold the error number.
   71165   */
   71166 abort_due_to_error:
   71167   assert( p->zErrMsg==0 );
   71168   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   71169   if( rc!=SQLITE_IOERR_NOMEM ){
   71170     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   71171   }
   71172   goto vdbe_error_halt;
   71173 
   71174   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   71175   ** flag.
   71176   */
   71177 abort_due_to_interrupt:
   71178   assert( db->u1.isInterrupted );
   71179   rc = SQLITE_INTERRUPT;
   71180   p->rc = rc;
   71181   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   71182   goto vdbe_error_halt;
   71183 }
   71184 
   71185 /************** End of vdbe.c ************************************************/
   71186 /************** Begin file vdbeblob.c ****************************************/
   71187 /*
   71188 ** 2007 May 1
   71189 **
   71190 ** The author disclaims copyright to this source code.  In place of
   71191 ** a legal notice, here is a blessing:
   71192 **
   71193 **    May you do good and not evil.
   71194 **    May you find forgiveness for yourself and forgive others.
   71195 **    May you share freely, never taking more than you give.
   71196 **
   71197 *************************************************************************
   71198 **
   71199 ** This file contains code used to implement incremental BLOB I/O.
   71200 */
   71201 
   71202 
   71203 #ifndef SQLITE_OMIT_INCRBLOB
   71204 
   71205 /*
   71206 ** Valid sqlite3_blob* handles point to Incrblob structures.
   71207 */
   71208 typedef struct Incrblob Incrblob;
   71209 struct Incrblob {
   71210   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   71211   int nByte;              /* Size of open blob, in bytes */
   71212   int iOffset;            /* Byte offset of blob in cursor data */
   71213   int iCol;               /* Table column this handle is open on */
   71214   BtCursor *pCsr;         /* Cursor pointing at blob row */
   71215   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   71216   sqlite3 *db;            /* The associated database */
   71217 };
   71218 
   71219 
   71220 /*
   71221 ** This function is used by both blob_open() and blob_reopen(). It seeks
   71222 ** the b-tree cursor associated with blob handle p to point to row iRow.
   71223 ** If successful, SQLITE_OK is returned and subsequent calls to
   71224 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   71225 **
   71226 ** If an error occurs, or if the specified row does not exist or does not
   71227 ** contain a value of type TEXT or BLOB in the column nominated when the
   71228 ** blob handle was opened, then an error code is returned and *pzErr may
   71229 ** be set to point to a buffer containing an error message. It is the
   71230 ** responsibility of the caller to free the error message buffer using
   71231 ** sqlite3DbFree().
   71232 **
   71233 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   71234 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   71235 ** immediately return SQLITE_ABORT.
   71236 */
   71237 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   71238   int rc;                         /* Error code */
   71239   char *zErr = 0;                 /* Error message */
   71240   Vdbe *v = (Vdbe *)p->pStmt;
   71241 
   71242   /* Set the value of the SQL statements only variable to integer iRow.
   71243   ** This is done directly instead of using sqlite3_bind_int64() to avoid
   71244   ** triggering asserts related to mutexes.
   71245   */
   71246   assert( v->aVar[0].flags&MEM_Int );
   71247   v->aVar[0].u.i = iRow;
   71248 
   71249   rc = sqlite3_step(p->pStmt);
   71250   if( rc==SQLITE_ROW ){
   71251     u32 type = v->apCsr[0]->aType[p->iCol];
   71252     if( type<12 ){
   71253       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   71254           type==0?"null": type==7?"real": "integer"
   71255       );
   71256       rc = SQLITE_ERROR;
   71257       sqlite3_finalize(p->pStmt);
   71258       p->pStmt = 0;
   71259     }else{
   71260       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
   71261       p->nByte = sqlite3VdbeSerialTypeLen(type);
   71262       p->pCsr =  v->apCsr[0]->pCursor;
   71263       sqlite3BtreeEnterCursor(p->pCsr);
   71264       sqlite3BtreeCacheOverflow(p->pCsr);
   71265       sqlite3BtreeLeaveCursor(p->pCsr);
   71266     }
   71267   }
   71268 
   71269   if( rc==SQLITE_ROW ){
   71270     rc = SQLITE_OK;
   71271   }else if( p->pStmt ){
   71272     rc = sqlite3_finalize(p->pStmt);
   71273     p->pStmt = 0;
   71274     if( rc==SQLITE_OK ){
   71275       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   71276       rc = SQLITE_ERROR;
   71277     }else{
   71278       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   71279     }
   71280   }
   71281 
   71282   assert( rc!=SQLITE_OK || zErr==0 );
   71283   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   71284 
   71285   *pzErr = zErr;
   71286   return rc;
   71287 }
   71288 
   71289 /*
   71290 ** Open a blob handle.
   71291 */
   71292 SQLITE_API int sqlite3_blob_open(
   71293   sqlite3* db,            /* The database connection */
   71294   const char *zDb,        /* The attached database containing the blob */
   71295   const char *zTable,     /* The table containing the blob */
   71296   const char *zColumn,    /* The column containing the blob */
   71297   sqlite_int64 iRow,      /* The row containing the glob */
   71298   int flags,              /* True -> read/write access, false -> read-only */
   71299   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   71300 ){
   71301   int nAttempt = 0;
   71302   int iCol;               /* Index of zColumn in row-record */
   71303 
   71304   /* This VDBE program seeks a btree cursor to the identified
   71305   ** db/table/row entry. The reason for using a vdbe program instead
   71306   ** of writing code to use the b-tree layer directly is that the
   71307   ** vdbe program will take advantage of the various transaction,
   71308   ** locking and error handling infrastructure built into the vdbe.
   71309   **
   71310   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   71311   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   71312   ** uses it to implement the blob_read(), blob_write() and
   71313   ** blob_bytes() functions.
   71314   **
   71315   ** The sqlite3_blob_close() function finalizes the vdbe program,
   71316   ** which closes the b-tree cursor and (possibly) commits the
   71317   ** transaction.
   71318   */
   71319   static const VdbeOpList openBlob[] = {
   71320     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
   71321     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
   71322     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
   71323 
   71324     /* One of the following two instructions is replaced by an OP_Noop. */
   71325     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
   71326     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
   71327 
   71328     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
   71329     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
   71330     {OP_Column, 0, 0, 1},          /* 7  */
   71331     {OP_ResultRow, 1, 0, 0},       /* 8  */
   71332     {OP_Goto, 0, 5, 0},            /* 9  */
   71333     {OP_Close, 0, 0, 0},           /* 10 */
   71334     {OP_Halt, 0, 0, 0},            /* 11 */
   71335   };
   71336 
   71337   int rc = SQLITE_OK;
   71338   char *zErr = 0;
   71339   Table *pTab;
   71340   Parse *pParse = 0;
   71341   Incrblob *pBlob = 0;
   71342 
   71343   flags = !!flags;                /* flags = (flags ? 1 : 0); */
   71344   *ppBlob = 0;
   71345 
   71346   sqlite3_mutex_enter(db->mutex);
   71347 
   71348   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   71349   if( !pBlob ) goto blob_open_out;
   71350   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   71351   if( !pParse ) goto blob_open_out;
   71352 
   71353   do {
   71354     memset(pParse, 0, sizeof(Parse));
   71355     pParse->db = db;
   71356     sqlite3DbFree(db, zErr);
   71357     zErr = 0;
   71358 
   71359     sqlite3BtreeEnterAll(db);
   71360     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   71361     if( pTab && IsVirtual(pTab) ){
   71362       pTab = 0;
   71363       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   71364     }
   71365 #ifndef SQLITE_OMIT_VIEW
   71366     if( pTab && pTab->pSelect ){
   71367       pTab = 0;
   71368       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   71369     }
   71370 #endif
   71371     if( !pTab ){
   71372       if( pParse->zErrMsg ){
   71373         sqlite3DbFree(db, zErr);
   71374         zErr = pParse->zErrMsg;
   71375         pParse->zErrMsg = 0;
   71376       }
   71377       rc = SQLITE_ERROR;
   71378       sqlite3BtreeLeaveAll(db);
   71379       goto blob_open_out;
   71380     }
   71381 
   71382     /* Now search pTab for the exact column. */
   71383     for(iCol=0; iCol<pTab->nCol; iCol++) {
   71384       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   71385         break;
   71386       }
   71387     }
   71388     if( iCol==pTab->nCol ){
   71389       sqlite3DbFree(db, zErr);
   71390       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   71391       rc = SQLITE_ERROR;
   71392       sqlite3BtreeLeaveAll(db);
   71393       goto blob_open_out;
   71394     }
   71395 
   71396     /* If the value is being opened for writing, check that the
   71397     ** column is not indexed, and that it is not part of a foreign key.
   71398     ** It is against the rules to open a column to which either of these
   71399     ** descriptions applies for writing.  */
   71400     if( flags ){
   71401       const char *zFault = 0;
   71402       Index *pIdx;
   71403 #ifndef SQLITE_OMIT_FOREIGN_KEY
   71404       if( db->flags&SQLITE_ForeignKeys ){
   71405         /* Check that the column is not part of an FK child key definition. It
   71406         ** is not necessary to check if it is part of a parent key, as parent
   71407         ** key columns must be indexed. The check below will pick up this
   71408         ** case.  */
   71409         FKey *pFKey;
   71410         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   71411           int j;
   71412           for(j=0; j<pFKey->nCol; j++){
   71413             if( pFKey->aCol[j].iFrom==iCol ){
   71414               zFault = "foreign key";
   71415             }
   71416           }
   71417         }
   71418       }
   71419 #endif
   71420       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   71421         int j;
   71422         for(j=0; j<pIdx->nColumn; j++){
   71423           if( pIdx->aiColumn[j]==iCol ){
   71424             zFault = "indexed";
   71425           }
   71426         }
   71427       }
   71428       if( zFault ){
   71429         sqlite3DbFree(db, zErr);
   71430         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   71431         rc = SQLITE_ERROR;
   71432         sqlite3BtreeLeaveAll(db);
   71433         goto blob_open_out;
   71434       }
   71435     }
   71436 
   71437     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
   71438     assert( pBlob->pStmt || db->mallocFailed );
   71439     if( pBlob->pStmt ){
   71440       Vdbe *v = (Vdbe *)pBlob->pStmt;
   71441       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   71442 
   71443       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
   71444 
   71445 
   71446       /* Configure the OP_Transaction */
   71447       sqlite3VdbeChangeP1(v, 0, iDb);
   71448       sqlite3VdbeChangeP2(v, 0, flags);
   71449 
   71450       /* Configure the OP_VerifyCookie */
   71451       sqlite3VdbeChangeP1(v, 1, iDb);
   71452       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
   71453       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
   71454 
   71455       /* Make sure a mutex is held on the table to be accessed */
   71456       sqlite3VdbeUsesBtree(v, iDb);
   71457 
   71458       /* Configure the OP_TableLock instruction */
   71459 #ifdef SQLITE_OMIT_SHARED_CACHE
   71460       sqlite3VdbeChangeToNoop(v, 2);
   71461 #else
   71462       sqlite3VdbeChangeP1(v, 2, iDb);
   71463       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
   71464       sqlite3VdbeChangeP3(v, 2, flags);
   71465       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
   71466 #endif
   71467 
   71468       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   71469       ** parameter of the other to pTab->tnum.  */
   71470       sqlite3VdbeChangeToNoop(v, 4 - flags);
   71471       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
   71472       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
   71473 
   71474       /* Configure the number of columns. Configure the cursor to
   71475       ** think that the table has one more column than it really
   71476       ** does. An OP_Column to retrieve this imaginary column will
   71477       ** always return an SQL NULL. This is useful because it means
   71478       ** we can invoke OP_Column to fill in the vdbe cursors type
   71479       ** and offset cache without causing any IO.
   71480       */
   71481       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   71482       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
   71483       if( !db->mallocFailed ){
   71484         pParse->nVar = 1;
   71485         pParse->nMem = 1;
   71486         pParse->nTab = 1;
   71487         sqlite3VdbeMakeReady(v, pParse);
   71488       }
   71489     }
   71490 
   71491     pBlob->flags = flags;
   71492     pBlob->iCol = iCol;
   71493     pBlob->db = db;
   71494     sqlite3BtreeLeaveAll(db);
   71495     if( db->mallocFailed ){
   71496       goto blob_open_out;
   71497     }
   71498     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
   71499     rc = blobSeekToRow(pBlob, iRow, &zErr);
   71500   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
   71501 
   71502 blob_open_out:
   71503   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   71504     *ppBlob = (sqlite3_blob *)pBlob;
   71505   }else{
   71506     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   71507     sqlite3DbFree(db, pBlob);
   71508   }
   71509   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   71510   sqlite3DbFree(db, zErr);
   71511   sqlite3StackFree(db, pParse);
   71512   rc = sqlite3ApiExit(db, rc);
   71513   sqlite3_mutex_leave(db->mutex);
   71514   return rc;
   71515 }
   71516 
   71517 /*
   71518 ** Close a blob handle that was previously created using
   71519 ** sqlite3_blob_open().
   71520 */
   71521 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   71522   Incrblob *p = (Incrblob *)pBlob;
   71523   int rc;
   71524   sqlite3 *db;
   71525 
   71526   if( p ){
   71527     db = p->db;
   71528     sqlite3_mutex_enter(db->mutex);
   71529     rc = sqlite3_finalize(p->pStmt);
   71530     sqlite3DbFree(db, p);
   71531     sqlite3_mutex_leave(db->mutex);
   71532   }else{
   71533     rc = SQLITE_OK;
   71534   }
   71535   return rc;
   71536 }
   71537 
   71538 /*
   71539 ** Perform a read or write operation on a blob
   71540 */
   71541 static int blobReadWrite(
   71542   sqlite3_blob *pBlob,
   71543   void *z,
   71544   int n,
   71545   int iOffset,
   71546   int (*xCall)(BtCursor*, u32, u32, void*)
   71547 ){
   71548   int rc;
   71549   Incrblob *p = (Incrblob *)pBlob;
   71550   Vdbe *v;
   71551   sqlite3 *db;
   71552 
   71553   if( p==0 ) return SQLITE_MISUSE_BKPT;
   71554   db = p->db;
   71555   sqlite3_mutex_enter(db->mutex);
   71556   v = (Vdbe*)p->pStmt;
   71557 
   71558   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   71559     /* Request is out of range. Return a transient error. */
   71560     rc = SQLITE_ERROR;
   71561     sqlite3Error(db, SQLITE_ERROR, 0);
   71562   }else if( v==0 ){
   71563     /* If there is no statement handle, then the blob-handle has
   71564     ** already been invalidated. Return SQLITE_ABORT in this case.
   71565     */
   71566     rc = SQLITE_ABORT;
   71567   }else{
   71568     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   71569     ** returned, clean-up the statement handle.
   71570     */
   71571     assert( db == v->db );
   71572     sqlite3BtreeEnterCursor(p->pCsr);
   71573     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   71574     sqlite3BtreeLeaveCursor(p->pCsr);
   71575     if( rc==SQLITE_ABORT ){
   71576       sqlite3VdbeFinalize(v);
   71577       p->pStmt = 0;
   71578     }else{
   71579       db->errCode = rc;
   71580       v->rc = rc;
   71581     }
   71582   }
   71583   rc = sqlite3ApiExit(db, rc);
   71584   sqlite3_mutex_leave(db->mutex);
   71585   return rc;
   71586 }
   71587 
   71588 /*
   71589 ** Read data from a blob handle.
   71590 */
   71591 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   71592   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   71593 }
   71594 
   71595 /*
   71596 ** Write data to a blob handle.
   71597 */
   71598 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   71599   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   71600 }
   71601 
   71602 /*
   71603 ** Query a blob handle for the size of the data.
   71604 **
   71605 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   71606 ** so no mutex is required for access.
   71607 */
   71608 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   71609   Incrblob *p = (Incrblob *)pBlob;
   71610   return (p && p->pStmt) ? p->nByte : 0;
   71611 }
   71612 
   71613 /*
   71614 ** Move an existing blob handle to point to a different row of the same
   71615 ** database table.
   71616 **
   71617 ** If an error occurs, or if the specified row does not exist or does not
   71618 ** contain a blob or text value, then an error code is returned and the
   71619 ** database handle error code and message set. If this happens, then all
   71620 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   71621 ** immediately return SQLITE_ABORT.
   71622 */
   71623 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   71624   int rc;
   71625   Incrblob *p = (Incrblob *)pBlob;
   71626   sqlite3 *db;
   71627 
   71628   if( p==0 ) return SQLITE_MISUSE_BKPT;
   71629   db = p->db;
   71630   sqlite3_mutex_enter(db->mutex);
   71631 
   71632   if( p->pStmt==0 ){
   71633     /* If there is no statement handle, then the blob-handle has
   71634     ** already been invalidated. Return SQLITE_ABORT in this case.
   71635     */
   71636     rc = SQLITE_ABORT;
   71637   }else{
   71638     char *zErr;
   71639     rc = blobSeekToRow(p, iRow, &zErr);
   71640     if( rc!=SQLITE_OK ){
   71641       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   71642       sqlite3DbFree(db, zErr);
   71643     }
   71644     assert( rc!=SQLITE_SCHEMA );
   71645   }
   71646 
   71647   rc = sqlite3ApiExit(db, rc);
   71648   assert( rc==SQLITE_OK || p->pStmt==0 );
   71649   sqlite3_mutex_leave(db->mutex);
   71650   return rc;
   71651 }
   71652 
   71653 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   71654 
   71655 /************** End of vdbeblob.c ********************************************/
   71656 /************** Begin file vdbesort.c ****************************************/
   71657 /*
   71658 ** 2011 July 9
   71659 **
   71660 ** The author disclaims copyright to this source code.  In place of
   71661 ** a legal notice, here is a blessing:
   71662 **
   71663 **    May you do good and not evil.
   71664 **    May you find forgiveness for yourself and forgive others.
   71665 **    May you share freely, never taking more than you give.
   71666 **
   71667 *************************************************************************
   71668 ** This file contains code for the VdbeSorter object, used in concert with
   71669 ** a VdbeCursor to sort large numbers of keys (as may be required, for
   71670 ** example, by CREATE INDEX statements on tables too large to fit in main
   71671 ** memory).
   71672 */
   71673 
   71674 
   71675 #ifndef SQLITE_OMIT_MERGE_SORT
   71676 
   71677 typedef struct VdbeSorterIter VdbeSorterIter;
   71678 typedef struct SorterRecord SorterRecord;
   71679 
   71680 /*
   71681 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
   71682 **
   71683 ** As keys are added to the sorter, they are written to disk in a series
   71684 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
   71685 ** the same as the cache-size allowed for temporary databases. In order
   71686 ** to allow the caller to extract keys from the sorter in sorted order,
   71687 ** all PMAs currently stored on disk must be merged together. This comment
   71688 ** describes the data structure used to do so. The structure supports
   71689 ** merging any number of arrays in a single pass with no redundant comparison
   71690 ** operations.
   71691 **
   71692 ** The aIter[] array contains an iterator for each of the PMAs being merged.
   71693 ** An aIter[] iterator either points to a valid key or else is at EOF. For
   71694 ** the purposes of the paragraphs below, we assume that the array is actually
   71695 ** N elements in size, where N is the smallest power of 2 greater to or equal
   71696 ** to the number of iterators being merged. The extra aIter[] elements are
   71697 ** treated as if they are empty (always at EOF).
   71698 **
   71699 ** The aTree[] array is also N elements in size. The value of N is stored in
   71700 ** the VdbeSorter.nTree variable.
   71701 **
   71702 ** The final (N/2) elements of aTree[] contain the results of comparing
   71703 ** pairs of iterator keys together. Element i contains the result of
   71704 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
   71705 ** aTree element is set to the index of it.
   71706 **
   71707 ** For the purposes of this comparison, EOF is considered greater than any
   71708 ** other key value. If the keys are equal (only possible with two EOF
   71709 ** values), it doesn't matter which index is stored.
   71710 **
   71711 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
   71712 ** above contains the index of the smallest of each block of 4 iterators.
   71713 ** And so on. So that aTree[1] contains the index of the iterator that
   71714 ** currently points to the smallest key value. aTree[0] is unused.
   71715 **
   71716 ** Example:
   71717 **
   71718 **     aIter[0] -> Banana
   71719 **     aIter[1] -> Feijoa
   71720 **     aIter[2] -> Elderberry
   71721 **     aIter[3] -> Currant
   71722 **     aIter[4] -> Grapefruit
   71723 **     aIter[5] -> Apple
   71724 **     aIter[6] -> Durian
   71725 **     aIter[7] -> EOF
   71726 **
   71727 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
   71728 **
   71729 ** The current element is "Apple" (the value of the key indicated by
   71730 ** iterator 5). When the Next() operation is invoked, iterator 5 will
   71731 ** be advanced to the next key in its segment. Say the next key is
   71732 ** "Eggplant":
   71733 **
   71734 **     aIter[5] -> Eggplant
   71735 **
   71736 ** The contents of aTree[] are updated first by comparing the new iterator
   71737 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
   71738 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
   71739 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
   71740 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
   71741 ** so the value written into element 1 of the array is 0. As follows:
   71742 **
   71743 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
   71744 **
   71745 ** In other words, each time we advance to the next sorter element, log2(N)
   71746 ** key comparison operations are required, where N is the number of segments
   71747 ** being merged (rounded up to the next power of 2).
   71748 */
   71749 struct VdbeSorter {
   71750   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
   71751   i64 iReadOff;                   /* Current read offset within file pTemp1 */
   71752   int nInMemory;                  /* Current size of pRecord list as PMA */
   71753   int nTree;                      /* Used size of aTree/aIter (power of 2) */
   71754   int nPMA;                       /* Number of PMAs stored in pTemp1 */
   71755   int mnPmaSize;                  /* Minimum PMA size, in bytes */
   71756   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
   71757   VdbeSorterIter *aIter;          /* Array of iterators to merge */
   71758   int *aTree;                     /* Current state of incremental merge */
   71759   sqlite3_file *pTemp1;           /* PMA file 1 */
   71760   SorterRecord *pRecord;          /* Head of in-memory record list */
   71761   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
   71762 };
   71763 
   71764 /*
   71765 ** The following type is an iterator for a PMA. It caches the current key in
   71766 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
   71767 */
   71768 struct VdbeSorterIter {
   71769   i64 iReadOff;                   /* Current read offset */
   71770   i64 iEof;                       /* 1 byte past EOF for this iterator */
   71771   int nAlloc;                     /* Bytes of space at aAlloc */
   71772   int nKey;                       /* Number of bytes in key */
   71773   sqlite3_file *pFile;            /* File iterator is reading from */
   71774   u8 *aAlloc;                     /* Allocated space */
   71775   u8 *aKey;                       /* Pointer to current key */
   71776 };
   71777 
   71778 /*
   71779 ** A structure to store a single record. All in-memory records are connected
   71780 ** together into a linked list headed at VdbeSorter.pRecord using the
   71781 ** SorterRecord.pNext pointer.
   71782 */
   71783 struct SorterRecord {
   71784   void *pVal;
   71785   int nVal;
   71786   SorterRecord *pNext;
   71787 };
   71788 
   71789 /* Minimum allowable value for the VdbeSorter.nWorking variable */
   71790 #define SORTER_MIN_WORKING 10
   71791 
   71792 /* Maximum number of segments to merge in a single pass. */
   71793 #define SORTER_MAX_MERGE_COUNT 16
   71794 
   71795 /*
   71796 ** Free all memory belonging to the VdbeSorterIter object passed as the second
   71797 ** argument. All structure fields are set to zero before returning.
   71798 */
   71799 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
   71800   sqlite3DbFree(db, pIter->aAlloc);
   71801   memset(pIter, 0, sizeof(VdbeSorterIter));
   71802 }
   71803 
   71804 /*
   71805 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
   71806 ** no error occurs, or an SQLite error code if one does.
   71807 */
   71808 static int vdbeSorterIterNext(
   71809   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
   71810   VdbeSorterIter *pIter           /* Iterator to advance */
   71811 ){
   71812   int rc;                         /* Return Code */
   71813   int nRead;                      /* Number of bytes read */
   71814   int nRec = 0;                   /* Size of record in bytes */
   71815   int iOff = 0;                   /* Size of serialized size varint in bytes */
   71816 
   71817   assert( pIter->iEof>=pIter->iReadOff );
   71818   if( pIter->iEof-pIter->iReadOff>5 ){
   71819     nRead = 5;
   71820   }else{
   71821     nRead = (int)(pIter->iEof - pIter->iReadOff);
   71822   }
   71823   if( nRead<=0 ){
   71824     /* This is an EOF condition */
   71825     vdbeSorterIterZero(db, pIter);
   71826     return SQLITE_OK;
   71827   }
   71828 
   71829   rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
   71830   if( rc==SQLITE_OK ){
   71831     iOff = getVarint32(pIter->aAlloc, nRec);
   71832     if( (iOff+nRec)>nRead ){
   71833       int nRead2;                   /* Number of extra bytes to read */
   71834       if( (iOff+nRec)>pIter->nAlloc ){
   71835         int nNew = pIter->nAlloc*2;
   71836         while( (iOff+nRec)>nNew ) nNew = nNew*2;
   71837         pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
   71838         if( !pIter->aAlloc ) return SQLITE_NOMEM;
   71839         pIter->nAlloc = nNew;
   71840       }
   71841 
   71842       nRead2 = iOff + nRec - nRead;
   71843       rc = sqlite3OsRead(
   71844           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
   71845       );
   71846     }
   71847   }
   71848 
   71849   assert( rc!=SQLITE_OK || nRec>0 );
   71850   pIter->iReadOff += iOff+nRec;
   71851   pIter->nKey = nRec;
   71852   pIter->aKey = &pIter->aAlloc[iOff];
   71853   return rc;
   71854 }
   71855 
   71856 /*
   71857 ** Write a single varint, value iVal, to file-descriptor pFile. Return
   71858 ** SQLITE_OK if successful, or an SQLite error code if some error occurs.
   71859 **
   71860 ** The value of *piOffset when this function is called is used as the byte
   71861 ** offset in file pFile to write to. Before returning, *piOffset is
   71862 ** incremented by the number of bytes written.
   71863 */
   71864 static int vdbeSorterWriteVarint(
   71865   sqlite3_file *pFile,            /* File to write to */
   71866   i64 iVal,                       /* Value to write as a varint */
   71867   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
   71868 ){
   71869   u8 aVarint[9];                  /* Buffer large enough for a varint */
   71870   int nVarint;                    /* Number of used bytes in varint */
   71871   int rc;                         /* Result of write() call */
   71872 
   71873   nVarint = sqlite3PutVarint(aVarint, iVal);
   71874   rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
   71875   *piOffset += nVarint;
   71876 
   71877   return rc;
   71878 }
   71879 
   71880 /*
   71881 ** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
   71882 ** successful, or an SQLite error code if some error occurs.
   71883 **
   71884 ** The value of *piOffset when this function is called is used as the
   71885 ** byte offset in file pFile from whence to read the varint. If successful
   71886 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
   71887 ** the first byte past the end of the varint before returning. *piVal is
   71888 ** set to the integer value read. If an error occurs, the final values of
   71889 ** both *piOffset and *piVal are undefined.
   71890 */
   71891 static int vdbeSorterReadVarint(
   71892   sqlite3_file *pFile,            /* File to read from */
   71893   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
   71894   i64 *piVal                      /* OUT: Value read from file */
   71895 ){
   71896   u8 aVarint[9];                  /* Buffer large enough for a varint */
   71897   i64 iOff = *piOffset;           /* Offset in file to read from */
   71898   int rc;                         /* Return code */
   71899 
   71900   rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
   71901   if( rc==SQLITE_OK ){
   71902     *piOffset += getVarint(aVarint, (u64 *)piVal);
   71903   }
   71904 
   71905   return rc;
   71906 }
   71907 
   71908 /*
   71909 ** Initialize iterator pIter to scan through the PMA stored in file pFile
   71910 ** starting at offset iStart and ending at offset iEof-1. This function
   71911 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
   71912 ** PMA is empty).
   71913 */
   71914 static int vdbeSorterIterInit(
   71915   sqlite3 *db,                    /* Database handle */
   71916   VdbeSorter *pSorter,            /* Sorter object */
   71917   i64 iStart,                     /* Start offset in pFile */
   71918   VdbeSorterIter *pIter,          /* Iterator to populate */
   71919   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
   71920 ){
   71921   int rc;
   71922 
   71923   assert( pSorter->iWriteOff>iStart );
   71924   assert( pIter->aAlloc==0 );
   71925   pIter->pFile = pSorter->pTemp1;
   71926   pIter->iReadOff = iStart;
   71927   pIter->nAlloc = 128;
   71928   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
   71929   if( !pIter->aAlloc ){
   71930     rc = SQLITE_NOMEM;
   71931   }else{
   71932     i64 nByte;                         /* Total size of PMA in bytes */
   71933     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
   71934     *pnByte += nByte;
   71935     pIter->iEof = pIter->iReadOff + nByte;
   71936   }
   71937   if( rc==SQLITE_OK ){
   71938     rc = vdbeSorterIterNext(db, pIter);
   71939   }
   71940   return rc;
   71941 }
   71942 
   71943 
   71944 /*
   71945 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
   71946 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
   71947 ** used by the comparison. If an error occurs, return an SQLite error code.
   71948 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
   71949 ** value, depending on whether key1 is smaller, equal to or larger than key2.
   71950 **
   71951 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
   71952 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
   71953 ** is true and key1 contains even a single NULL value, it is considered to
   71954 ** be less than key2. Even if key2 also contains NULL values.
   71955 **
   71956 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
   71957 ** has been allocated and contains an unpacked record that is used as key2.
   71958 */
   71959 static void vdbeSorterCompare(
   71960   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
   71961   int bOmitRowid,                 /* Ignore rowid field at end of keys */
   71962   void *pKey1, int nKey1,         /* Left side of comparison */
   71963   void *pKey2, int nKey2,         /* Right side of comparison */
   71964   int *pRes                       /* OUT: Result of comparison */
   71965 ){
   71966   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
   71967   VdbeSorter *pSorter = pCsr->pSorter;
   71968   UnpackedRecord *r2 = pSorter->pUnpacked;
   71969   int i;
   71970 
   71971   if( pKey2 ){
   71972     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
   71973   }
   71974 
   71975   if( bOmitRowid ){
   71976     r2->nField = pKeyInfo->nField;
   71977     assert( r2->nField>0 );
   71978     for(i=0; i<r2->nField; i++){
   71979       if( r2->aMem[i].flags & MEM_Null ){
   71980         *pRes = -1;
   71981         return;
   71982       }
   71983     }
   71984     r2->flags |= UNPACKED_PREFIX_MATCH;
   71985   }
   71986 
   71987   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
   71988 }
   71989 
   71990 /*
   71991 ** This function is called to compare two iterator keys when merging
   71992 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
   71993 ** value to recalculate.
   71994 */
   71995 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
   71996   VdbeSorter *pSorter = pCsr->pSorter;
   71997   int i1;
   71998   int i2;
   71999   int iRes;
   72000   VdbeSorterIter *p1;
   72001   VdbeSorterIter *p2;
   72002 
   72003   assert( iOut<pSorter->nTree && iOut>0 );
   72004 
   72005   if( iOut>=(pSorter->nTree/2) ){
   72006     i1 = (iOut - pSorter->nTree/2) * 2;
   72007     i2 = i1 + 1;
   72008   }else{
   72009     i1 = pSorter->aTree[iOut*2];
   72010     i2 = pSorter->aTree[iOut*2+1];
   72011   }
   72012 
   72013   p1 = &pSorter->aIter[i1];
   72014   p2 = &pSorter->aIter[i2];
   72015 
   72016   if( p1->pFile==0 ){
   72017     iRes = i2;
   72018   }else if( p2->pFile==0 ){
   72019     iRes = i1;
   72020   }else{
   72021     int res;
   72022     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
   72023     vdbeSorterCompare(
   72024         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
   72025     );
   72026     if( res<=0 ){
   72027       iRes = i1;
   72028     }else{
   72029       iRes = i2;
   72030     }
   72031   }
   72032 
   72033   pSorter->aTree[iOut] = iRes;
   72034   return SQLITE_OK;
   72035 }
   72036 
   72037 /*
   72038 ** Initialize the temporary index cursor just opened as a sorter cursor.
   72039 */
   72040 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
   72041   int pgsz;                       /* Page size of main database */
   72042   int mxCache;                    /* Cache size */
   72043   VdbeSorter *pSorter;            /* The new sorter */
   72044   char *d;                        /* Dummy */
   72045 
   72046   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
   72047   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
   72048   if( pSorter==0 ){
   72049     return SQLITE_NOMEM;
   72050   }
   72051 
   72052   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
   72053   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
   72054   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
   72055 
   72056   if( !sqlite3TempInMemory(db) ){
   72057     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
   72058     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
   72059     mxCache = db->aDb[0].pSchema->cache_size;
   72060     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
   72061     pSorter->mxPmaSize = mxCache * pgsz;
   72062   }
   72063 
   72064   return SQLITE_OK;
   72065 }
   72066 
   72067 /*
   72068 ** Free the list of sorted records starting at pRecord.
   72069 */
   72070 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
   72071   SorterRecord *p;
   72072   SorterRecord *pNext;
   72073   for(p=pRecord; p; p=pNext){
   72074     pNext = p->pNext;
   72075     sqlite3DbFree(db, p);
   72076   }
   72077 }
   72078 
   72079 /*
   72080 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
   72081 */
   72082 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
   72083   VdbeSorter *pSorter = pCsr->pSorter;
   72084   if( pSorter ){
   72085     if( pSorter->aIter ){
   72086       int i;
   72087       for(i=0; i<pSorter->nTree; i++){
   72088         vdbeSorterIterZero(db, &pSorter->aIter[i]);
   72089       }
   72090       sqlite3DbFree(db, pSorter->aIter);
   72091     }
   72092     if( pSorter->pTemp1 ){
   72093       sqlite3OsCloseFree(pSorter->pTemp1);
   72094     }
   72095     vdbeSorterRecordFree(db, pSorter->pRecord);
   72096     sqlite3DbFree(db, pSorter->pUnpacked);
   72097     sqlite3DbFree(db, pSorter);
   72098     pCsr->pSorter = 0;
   72099   }
   72100 }
   72101 
   72102 /*
   72103 ** Allocate space for a file-handle and open a temporary file. If successful,
   72104 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
   72105 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
   72106 */
   72107 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
   72108   int dummy;
   72109   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
   72110       SQLITE_OPEN_TEMP_JOURNAL |
   72111       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
   72112       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
   72113   );
   72114 }
   72115 
   72116 /*
   72117 ** Merge the two sorted lists p1 and p2 into a single list.
   72118 ** Set *ppOut to the head of the new list.
   72119 */
   72120 static void vdbeSorterMerge(
   72121   VdbeCursor *pCsr,               /* For pKeyInfo */
   72122   SorterRecord *p1,               /* First list to merge */
   72123   SorterRecord *p2,               /* Second list to merge */
   72124   SorterRecord **ppOut            /* OUT: Head of merged list */
   72125 ){
   72126   SorterRecord *pFinal = 0;
   72127   SorterRecord **pp = &pFinal;
   72128   void *pVal2 = p2 ? p2->pVal : 0;
   72129 
   72130   while( p1 && p2 ){
   72131     int res;
   72132     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
   72133     if( res<=0 ){
   72134       *pp = p1;
   72135       pp = &p1->pNext;
   72136       p1 = p1->pNext;
   72137       pVal2 = 0;
   72138     }else{
   72139       *pp = p2;
   72140        pp = &p2->pNext;
   72141       p2 = p2->pNext;
   72142       if( p2==0 ) break;
   72143       pVal2 = p2->pVal;
   72144     }
   72145   }
   72146   *pp = p1 ? p1 : p2;
   72147   *ppOut = pFinal;
   72148 }
   72149 
   72150 /*
   72151 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
   72152 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
   72153 ** occurs.
   72154 */
   72155 static int vdbeSorterSort(VdbeCursor *pCsr){
   72156   int i;
   72157   SorterRecord **aSlot;
   72158   SorterRecord *p;
   72159   VdbeSorter *pSorter = pCsr->pSorter;
   72160 
   72161   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
   72162   if( !aSlot ){
   72163     return SQLITE_NOMEM;
   72164   }
   72165 
   72166   p = pSorter->pRecord;
   72167   while( p ){
   72168     SorterRecord *pNext = p->pNext;
   72169     p->pNext = 0;
   72170     for(i=0; aSlot[i]; i++){
   72171       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   72172       aSlot[i] = 0;
   72173     }
   72174     aSlot[i] = p;
   72175     p = pNext;
   72176   }
   72177 
   72178   p = 0;
   72179   for(i=0; i<64; i++){
   72180     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
   72181   }
   72182   pSorter->pRecord = p;
   72183 
   72184   sqlite3_free(aSlot);
   72185   return SQLITE_OK;
   72186 }
   72187 
   72188 
   72189 /*
   72190 ** Write the current contents of the in-memory linked-list to a PMA. Return
   72191 ** SQLITE_OK if successful, or an SQLite error code otherwise.
   72192 **
   72193 ** The format of a PMA is:
   72194 **
   72195 **     * A varint. This varint contains the total number of bytes of content
   72196 **       in the PMA (not including the varint itself).
   72197 **
   72198 **     * One or more records packed end-to-end in order of ascending keys.
   72199 **       Each record consists of a varint followed by a blob of data (the
   72200 **       key). The varint is the number of bytes in the blob of data.
   72201 */
   72202 static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
   72203   int rc = SQLITE_OK;             /* Return code */
   72204   VdbeSorter *pSorter = pCsr->pSorter;
   72205 
   72206   if( pSorter->nInMemory==0 ){
   72207     assert( pSorter->pRecord==0 );
   72208     return rc;
   72209   }
   72210 
   72211   rc = vdbeSorterSort(pCsr);
   72212 
   72213   /* If the first temporary PMA file has not been opened, open it now. */
   72214   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
   72215     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
   72216     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
   72217     assert( pSorter->iWriteOff==0 );
   72218     assert( pSorter->nPMA==0 );
   72219   }
   72220 
   72221   if( rc==SQLITE_OK ){
   72222     i64 iOff = pSorter->iWriteOff;
   72223     SorterRecord *p;
   72224     SorterRecord *pNext = 0;
   72225     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
   72226 
   72227     pSorter->nPMA++;
   72228     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
   72229     for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
   72230       pNext = p->pNext;
   72231       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
   72232 
   72233       if( rc==SQLITE_OK ){
   72234         rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
   72235         iOff += p->nVal;
   72236       }
   72237 
   72238       sqlite3DbFree(db, p);
   72239     }
   72240 
   72241     /* This assert verifies that unless an error has occurred, the size of
   72242     ** the PMA on disk is the same as the expected size stored in
   72243     ** pSorter->nInMemory. */
   72244     assert( rc!=SQLITE_OK || pSorter->nInMemory==(
   72245           iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
   72246     ));
   72247 
   72248     pSorter->iWriteOff = iOff;
   72249     if( rc==SQLITE_OK ){
   72250       /* Terminate each file with 8 extra bytes so that from any offset
   72251       ** in the file we can always read 9 bytes without a SHORT_READ error */
   72252       rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
   72253     }
   72254     pSorter->pRecord = p;
   72255   }
   72256 
   72257   return rc;
   72258 }
   72259 
   72260 /*
   72261 ** Add a record to the sorter.
   72262 */
   72263 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   72264   sqlite3 *db,                    /* Database handle */
   72265   VdbeCursor *pCsr,               /* Sorter cursor */
   72266   Mem *pVal                       /* Memory cell containing record */
   72267 ){
   72268   VdbeSorter *pSorter = pCsr->pSorter;
   72269   int rc = SQLITE_OK;             /* Return Code */
   72270   SorterRecord *pNew;             /* New list element */
   72271 
   72272   assert( pSorter );
   72273   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
   72274 
   72275   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
   72276   if( pNew==0 ){
   72277     rc = SQLITE_NOMEM;
   72278   }else{
   72279     pNew->pVal = (void *)&pNew[1];
   72280     memcpy(pNew->pVal, pVal->z, pVal->n);
   72281     pNew->nVal = pVal->n;
   72282     pNew->pNext = pSorter->pRecord;
   72283     pSorter->pRecord = pNew;
   72284   }
   72285 
   72286   /* See if the contents of the sorter should now be written out. They
   72287   ** are written out when either of the following are true:
   72288   **
   72289   **   * The total memory allocated for the in-memory list is greater
   72290   **     than (page-size * cache-size), or
   72291   **
   72292   **   * The total memory allocated for the in-memory list is greater
   72293   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   72294   */
   72295   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
   72296         (pSorter->nInMemory>pSorter->mxPmaSize)
   72297      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
   72298   )){
   72299     rc = vdbeSorterListToPMA(db, pCsr);
   72300     pSorter->nInMemory = 0;
   72301   }
   72302 
   72303   return rc;
   72304 }
   72305 
   72306 /*
   72307 ** Helper function for sqlite3VdbeSorterRewind().
   72308 */
   72309 static int vdbeSorterInitMerge(
   72310   sqlite3 *db,                    /* Database handle */
   72311   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
   72312   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
   72313 ){
   72314   VdbeSorter *pSorter = pCsr->pSorter;
   72315   int rc = SQLITE_OK;             /* Return code */
   72316   int i;                          /* Used to iterator through aIter[] */
   72317   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
   72318 
   72319   /* Initialize the iterators. */
   72320   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
   72321     VdbeSorterIter *pIter = &pSorter->aIter[i];
   72322     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
   72323     pSorter->iReadOff = pIter->iEof;
   72324     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
   72325     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
   72326   }
   72327 
   72328   /* Initialize the aTree[] array. */
   72329   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
   72330     rc = vdbeSorterDoCompare(pCsr, i);
   72331   }
   72332 
   72333   *pnByte = nByte;
   72334   return rc;
   72335 }
   72336 
   72337 /*
   72338 ** Once the sorter has been populated, this function is called to prepare
   72339 ** for iterating through its contents in sorted order.
   72340 */
   72341 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
   72342   VdbeSorter *pSorter = pCsr->pSorter;
   72343   int rc;                         /* Return code */
   72344   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
   72345   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
   72346   int nIter;                      /* Number of iterators used */
   72347   int nByte;                      /* Bytes of space required for aIter/aTree */
   72348   int N = 2;                      /* Power of 2 >= nIter */
   72349 
   72350   assert( pSorter );
   72351 
   72352   /* If no data has been written to disk, then do not do so now. Instead,
   72353   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
   72354   ** from the in-memory list.  */
   72355   if( pSorter->nPMA==0 ){
   72356     *pbEof = !pSorter->pRecord;
   72357     assert( pSorter->aTree==0 );
   72358     return vdbeSorterSort(pCsr);
   72359   }
   72360 
   72361   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
   72362   rc = vdbeSorterListToPMA(db, pCsr);
   72363   if( rc!=SQLITE_OK ) return rc;
   72364 
   72365   /* Allocate space for aIter[] and aTree[]. */
   72366   nIter = pSorter->nPMA;
   72367   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
   72368   assert( nIter>0 );
   72369   while( N<nIter ) N += N;
   72370   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
   72371   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
   72372   if( !pSorter->aIter ) return SQLITE_NOMEM;
   72373   pSorter->aTree = (int *)&pSorter->aIter[N];
   72374   pSorter->nTree = N;
   72375 
   72376   do {
   72377     int iNew;                     /* Index of new, merged, PMA */
   72378 
   72379     for(iNew=0;
   72380         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
   72381         iNew++
   72382     ){
   72383       i64 nWrite;                 /* Number of bytes in new PMA */
   72384 
   72385       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
   72386       ** initialize an iterator for each of them and break out of the loop.
   72387       ** These iterators will be incrementally merged as the VDBE layer calls
   72388       ** sqlite3VdbeSorterNext().
   72389       **
   72390       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
   72391       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
   72392       ** are merged into a single PMA that is written to file pTemp2.
   72393       */
   72394       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
   72395       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
   72396       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   72397         break;
   72398       }
   72399 
   72400       /* Open the second temp file, if it is not already open. */
   72401       if( pTemp2==0 ){
   72402         assert( iWrite2==0 );
   72403         rc = vdbeSorterOpenTempFile(db, &pTemp2);
   72404       }
   72405 
   72406       if( rc==SQLITE_OK ){
   72407         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
   72408       }
   72409 
   72410       if( rc==SQLITE_OK ){
   72411         int bEof = 0;
   72412         while( rc==SQLITE_OK && bEof==0 ){
   72413           int nToWrite;
   72414           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   72415           assert( pIter->pFile );
   72416           nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
   72417           rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
   72418           iWrite2 += nToWrite;
   72419           if( rc==SQLITE_OK ){
   72420             rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
   72421           }
   72422         }
   72423       }
   72424     }
   72425 
   72426     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
   72427       break;
   72428     }else{
   72429       sqlite3_file *pTmp = pSorter->pTemp1;
   72430       pSorter->nPMA = iNew;
   72431       pSorter->pTemp1 = pTemp2;
   72432       pTemp2 = pTmp;
   72433       pSorter->iWriteOff = iWrite2;
   72434       pSorter->iReadOff = 0;
   72435       iWrite2 = 0;
   72436     }
   72437   }while( rc==SQLITE_OK );
   72438 
   72439   if( pTemp2 ){
   72440     sqlite3OsCloseFree(pTemp2);
   72441   }
   72442   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   72443   return rc;
   72444 }
   72445 
   72446 /*
   72447 ** Advance to the next element in the sorter.
   72448 */
   72449 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
   72450   VdbeSorter *pSorter = pCsr->pSorter;
   72451   int rc;                         /* Return code */
   72452 
   72453   if( pSorter->aTree ){
   72454     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
   72455     int i;                        /* Index of aTree[] to recalculate */
   72456 
   72457     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
   72458     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
   72459       rc = vdbeSorterDoCompare(pCsr, i);
   72460     }
   72461 
   72462     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
   72463   }else{
   72464     SorterRecord *pFree = pSorter->pRecord;
   72465     pSorter->pRecord = pFree->pNext;
   72466     pFree->pNext = 0;
   72467     vdbeSorterRecordFree(db, pFree);
   72468     *pbEof = !pSorter->pRecord;
   72469     rc = SQLITE_OK;
   72470   }
   72471   return rc;
   72472 }
   72473 
   72474 /*
   72475 ** Return a pointer to a buffer owned by the sorter that contains the
   72476 ** current key.
   72477 */
   72478 static void *vdbeSorterRowkey(
   72479   VdbeSorter *pSorter,            /* Sorter object */
   72480   int *pnKey                      /* OUT: Size of current key in bytes */
   72481 ){
   72482   void *pKey;
   72483   if( pSorter->aTree ){
   72484     VdbeSorterIter *pIter;
   72485     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
   72486     *pnKey = pIter->nKey;
   72487     pKey = pIter->aKey;
   72488   }else{
   72489     *pnKey = pSorter->pRecord->nVal;
   72490     pKey = pSorter->pRecord->pVal;
   72491   }
   72492   return pKey;
   72493 }
   72494 
   72495 /*
   72496 ** Copy the current sorter key into the memory cell pOut.
   72497 */
   72498 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
   72499   VdbeSorter *pSorter = pCsr->pSorter;
   72500   void *pKey; int nKey;           /* Sorter key to copy into pOut */
   72501 
   72502   pKey = vdbeSorterRowkey(pSorter, &nKey);
   72503   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
   72504     return SQLITE_NOMEM;
   72505   }
   72506   pOut->n = nKey;
   72507   MemSetTypeFlag(pOut, MEM_Blob);
   72508   memcpy(pOut->z, pKey, nKey);
   72509 
   72510   return SQLITE_OK;
   72511 }
   72512 
   72513 /*
   72514 ** Compare the key in memory cell pVal with the key that the sorter cursor
   72515 ** passed as the first argument currently points to. For the purposes of
   72516 ** the comparison, ignore the rowid field at the end of each record.
   72517 **
   72518 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
   72519 ** Otherwise, set *pRes to a negative, zero or positive value if the
   72520 ** key in pVal is smaller than, equal to or larger than the current sorter
   72521 ** key.
   72522 */
   72523 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
   72524   VdbeCursor *pCsr,               /* Sorter cursor */
   72525   Mem *pVal,                      /* Value to compare to current sorter key */
   72526   int *pRes                       /* OUT: Result of comparison */
   72527 ){
   72528   VdbeSorter *pSorter = pCsr->pSorter;
   72529   void *pKey; int nKey;           /* Sorter key to compare pVal with */
   72530 
   72531   pKey = vdbeSorterRowkey(pSorter, &nKey);
   72532   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
   72533   return SQLITE_OK;
   72534 }
   72535 
   72536 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
   72537 
   72538 /************** End of vdbesort.c ********************************************/
   72539 /************** Begin file journal.c *****************************************/
   72540 /*
   72541 ** 2007 August 22
   72542 **
   72543 ** The author disclaims copyright to this source code.  In place of
   72544 ** a legal notice, here is a blessing:
   72545 **
   72546 **    May you do good and not evil.
   72547 **    May you find forgiveness for yourself and forgive others.
   72548 **    May you share freely, never taking more than you give.
   72549 **
   72550 *************************************************************************
   72551 **
   72552 ** This file implements a special kind of sqlite3_file object used
   72553 ** by SQLite to create journal files if the atomic-write optimization
   72554 ** is enabled.
   72555 **
   72556 ** The distinctive characteristic of this sqlite3_file is that the
   72557 ** actual on disk file is created lazily. When the file is created,
   72558 ** the caller specifies a buffer size for an in-memory buffer to
   72559 ** be used to service read() and write() requests. The actual file
   72560 ** on disk is not created or populated until either:
   72561 **
   72562 **   1) The in-memory representation grows too large for the allocated
   72563 **      buffer, or
   72564 **   2) The sqlite3JournalCreate() function is called.
   72565 */
   72566 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   72567 
   72568 
   72569 /*
   72570 ** A JournalFile object is a subclass of sqlite3_file used by
   72571 ** as an open file handle for journal files.
   72572 */
   72573 struct JournalFile {
   72574   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   72575   int nBuf;                       /* Size of zBuf[] in bytes */
   72576   char *zBuf;                     /* Space to buffer journal writes */
   72577   int iSize;                      /* Amount of zBuf[] currently used */
   72578   int flags;                      /* xOpen flags */
   72579   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   72580   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   72581   const char *zJournal;           /* Name of the journal file */
   72582 };
   72583 typedef struct JournalFile JournalFile;
   72584 
   72585 /*
   72586 ** If it does not already exists, create and populate the on-disk file
   72587 ** for JournalFile p.
   72588 */
   72589 static int createFile(JournalFile *p){
   72590   int rc = SQLITE_OK;
   72591   if( !p->pReal ){
   72592     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   72593     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   72594     if( rc==SQLITE_OK ){
   72595       p->pReal = pReal;
   72596       if( p->iSize>0 ){
   72597         assert(p->iSize<=p->nBuf);
   72598         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   72599       }
   72600     }
   72601   }
   72602   return rc;
   72603 }
   72604 
   72605 /*
   72606 ** Close the file.
   72607 */
   72608 static int jrnlClose(sqlite3_file *pJfd){
   72609   JournalFile *p = (JournalFile *)pJfd;
   72610   if( p->pReal ){
   72611     sqlite3OsClose(p->pReal);
   72612   }
   72613   sqlite3_free(p->zBuf);
   72614   return SQLITE_OK;
   72615 }
   72616 
   72617 /*
   72618 ** Read data from the file.
   72619 */
   72620 static int jrnlRead(
   72621   sqlite3_file *pJfd,    /* The journal file from which to read */
   72622   void *zBuf,            /* Put the results here */
   72623   int iAmt,              /* Number of bytes to read */
   72624   sqlite_int64 iOfst     /* Begin reading at this offset */
   72625 ){
   72626   int rc = SQLITE_OK;
   72627   JournalFile *p = (JournalFile *)pJfd;
   72628   if( p->pReal ){
   72629     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   72630   }else if( (iAmt+iOfst)>p->iSize ){
   72631     rc = SQLITE_IOERR_SHORT_READ;
   72632   }else{
   72633     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   72634   }
   72635   return rc;
   72636 }
   72637 
   72638 /*
   72639 ** Write data to the file.
   72640 */
   72641 static int jrnlWrite(
   72642   sqlite3_file *pJfd,    /* The journal file into which to write */
   72643   const void *zBuf,      /* Take data to be written from here */
   72644   int iAmt,              /* Number of bytes to write */
   72645   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   72646 ){
   72647   int rc = SQLITE_OK;
   72648   JournalFile *p = (JournalFile *)pJfd;
   72649   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   72650     rc = createFile(p);
   72651   }
   72652   if( rc==SQLITE_OK ){
   72653     if( p->pReal ){
   72654       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   72655     }else{
   72656       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   72657       if( p->iSize<(iOfst+iAmt) ){
   72658         p->iSize = (iOfst+iAmt);
   72659       }
   72660     }
   72661   }
   72662   return rc;
   72663 }
   72664 
   72665 /*
   72666 ** Truncate the file.
   72667 */
   72668 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   72669   int rc = SQLITE_OK;
   72670   JournalFile *p = (JournalFile *)pJfd;
   72671   if( p->pReal ){
   72672     rc = sqlite3OsTruncate(p->pReal, size);
   72673   }else if( size<p->iSize ){
   72674     p->iSize = size;
   72675   }
   72676   return rc;
   72677 }
   72678 
   72679 /*
   72680 ** Sync the file.
   72681 */
   72682 static int jrnlSync(sqlite3_file *pJfd, int flags){
   72683   int rc;
   72684   JournalFile *p = (JournalFile *)pJfd;
   72685   if( p->pReal ){
   72686     rc = sqlite3OsSync(p->pReal, flags);
   72687   }else{
   72688     rc = SQLITE_OK;
   72689   }
   72690   return rc;
   72691 }
   72692 
   72693 /*
   72694 ** Query the size of the file in bytes.
   72695 */
   72696 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   72697   int rc = SQLITE_OK;
   72698   JournalFile *p = (JournalFile *)pJfd;
   72699   if( p->pReal ){
   72700     rc = sqlite3OsFileSize(p->pReal, pSize);
   72701   }else{
   72702     *pSize = (sqlite_int64) p->iSize;
   72703   }
   72704   return rc;
   72705 }
   72706 
   72707 /*
   72708 ** Table of methods for JournalFile sqlite3_file object.
   72709 */
   72710 static struct sqlite3_io_methods JournalFileMethods = {
   72711   1,             /* iVersion */
   72712   jrnlClose,     /* xClose */
   72713   jrnlRead,      /* xRead */
   72714   jrnlWrite,     /* xWrite */
   72715   jrnlTruncate,  /* xTruncate */
   72716   jrnlSync,      /* xSync */
   72717   jrnlFileSize,  /* xFileSize */
   72718   0,             /* xLock */
   72719   0,             /* xUnlock */
   72720   0,             /* xCheckReservedLock */
   72721   0,             /* xFileControl */
   72722   0,             /* xSectorSize */
   72723   0,             /* xDeviceCharacteristics */
   72724   0,             /* xShmMap */
   72725   0,             /* xShmLock */
   72726   0,             /* xShmBarrier */
   72727   0              /* xShmUnmap */
   72728 };
   72729 
   72730 /*
   72731 ** Open a journal file.
   72732 */
   72733 SQLITE_PRIVATE int sqlite3JournalOpen(
   72734   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   72735   const char *zName,         /* Name of the journal file */
   72736   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   72737   int flags,                 /* Opening flags */
   72738   int nBuf                   /* Bytes buffered before opening the file */
   72739 ){
   72740   JournalFile *p = (JournalFile *)pJfd;
   72741   memset(p, 0, sqlite3JournalSize(pVfs));
   72742   if( nBuf>0 ){
   72743     p->zBuf = sqlite3MallocZero(nBuf);
   72744     if( !p->zBuf ){
   72745       return SQLITE_NOMEM;
   72746     }
   72747   }else{
   72748     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   72749   }
   72750   p->pMethod = &JournalFileMethods;
   72751   p->nBuf = nBuf;
   72752   p->flags = flags;
   72753   p->zJournal = zName;
   72754   p->pVfs = pVfs;
   72755   return SQLITE_OK;
   72756 }
   72757 
   72758 /*
   72759 ** If the argument p points to a JournalFile structure, and the underlying
   72760 ** file has not yet been created, create it now.
   72761 */
   72762 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   72763   if( p->pMethods!=&JournalFileMethods ){
   72764     return SQLITE_OK;
   72765   }
   72766   return createFile((JournalFile *)p);
   72767 }
   72768 
   72769 /*
   72770 ** Return the number of bytes required to store a JournalFile that uses vfs
   72771 ** pVfs to create the underlying on-disk files.
   72772 */
   72773 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   72774   return (pVfs->szOsFile+sizeof(JournalFile));
   72775 }
   72776 #endif
   72777 
   72778 /************** End of journal.c *********************************************/
   72779 /************** Begin file memjournal.c **************************************/
   72780 /*
   72781 ** 2008 October 7
   72782 **
   72783 ** The author disclaims copyright to this source code.  In place of
   72784 ** a legal notice, here is a blessing:
   72785 **
   72786 **    May you do good and not evil.
   72787 **    May you find forgiveness for yourself and forgive others.
   72788 **    May you share freely, never taking more than you give.
   72789 **
   72790 *************************************************************************
   72791 **
   72792 ** This file contains code use to implement an in-memory rollback journal.
   72793 ** The in-memory rollback journal is used to journal transactions for
   72794 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   72795 */
   72796 
   72797 /* Forward references to internal structures */
   72798 typedef struct MemJournal MemJournal;
   72799 typedef struct FilePoint FilePoint;
   72800 typedef struct FileChunk FileChunk;
   72801 
   72802 /* Space to hold the rollback journal is allocated in increments of
   72803 ** this many bytes.
   72804 **
   72805 ** The size chosen is a little less than a power of two.  That way,
   72806 ** the FileChunk object will have a size that almost exactly fills
   72807 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   72808 ** memory allocators.
   72809 */
   72810 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   72811 
   72812 /* Macro to find the minimum of two numeric values.
   72813 */
   72814 #ifndef MIN
   72815 # define MIN(x,y) ((x)<(y)?(x):(y))
   72816 #endif
   72817 
   72818 /*
   72819 ** The rollback journal is composed of a linked list of these structures.
   72820 */
   72821 struct FileChunk {
   72822   FileChunk *pNext;               /* Next chunk in the journal */
   72823   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   72824 };
   72825 
   72826 /*
   72827 ** An instance of this object serves as a cursor into the rollback journal.
   72828 ** The cursor can be either for reading or writing.
   72829 */
   72830 struct FilePoint {
   72831   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   72832   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   72833 };
   72834 
   72835 /*
   72836 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   72837 ** is an instance of this class.
   72838 */
   72839 struct MemJournal {
   72840   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   72841   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   72842   FilePoint endpoint;             /* Pointer to the end of the file */
   72843   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   72844 };
   72845 
   72846 /*
   72847 ** Read data from the in-memory journal file.  This is the implementation
   72848 ** of the sqlite3_vfs.xRead method.
   72849 */
   72850 static int memjrnlRead(
   72851   sqlite3_file *pJfd,    /* The journal file from which to read */
   72852   void *zBuf,            /* Put the results here */
   72853   int iAmt,              /* Number of bytes to read */
   72854   sqlite_int64 iOfst     /* Begin reading at this offset */
   72855 ){
   72856   MemJournal *p = (MemJournal *)pJfd;
   72857   u8 *zOut = zBuf;
   72858   int nRead = iAmt;
   72859   int iChunkOffset;
   72860   FileChunk *pChunk;
   72861 
   72862   /* SQLite never tries to read past the end of a rollback journal file */
   72863   assert( iOfst+iAmt<=p->endpoint.iOffset );
   72864 
   72865   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   72866     sqlite3_int64 iOff = 0;
   72867     for(pChunk=p->pFirst;
   72868         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   72869         pChunk=pChunk->pNext
   72870     ){
   72871       iOff += JOURNAL_CHUNKSIZE;
   72872     }
   72873   }else{
   72874     pChunk = p->readpoint.pChunk;
   72875   }
   72876 
   72877   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   72878   do {
   72879     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   72880     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   72881     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   72882     zOut += nCopy;
   72883     nRead -= iSpace;
   72884     iChunkOffset = 0;
   72885   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   72886   p->readpoint.iOffset = iOfst+iAmt;
   72887   p->readpoint.pChunk = pChunk;
   72888 
   72889   return SQLITE_OK;
   72890 }
   72891 
   72892 /*
   72893 ** Write data to the file.
   72894 */
   72895 static int memjrnlWrite(
   72896   sqlite3_file *pJfd,    /* The journal file into which to write */
   72897   const void *zBuf,      /* Take data to be written from here */
   72898   int iAmt,              /* Number of bytes to write */
   72899   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   72900 ){
   72901   MemJournal *p = (MemJournal *)pJfd;
   72902   int nWrite = iAmt;
   72903   u8 *zWrite = (u8 *)zBuf;
   72904 
   72905   /* An in-memory journal file should only ever be appended to. Random
   72906   ** access writes are not required by sqlite.
   72907   */
   72908   assert( iOfst==p->endpoint.iOffset );
   72909   UNUSED_PARAMETER(iOfst);
   72910 
   72911   while( nWrite>0 ){
   72912     FileChunk *pChunk = p->endpoint.pChunk;
   72913     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   72914     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   72915 
   72916     if( iChunkOffset==0 ){
   72917       /* New chunk is required to extend the file. */
   72918       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   72919       if( !pNew ){
   72920         return SQLITE_IOERR_NOMEM;
   72921       }
   72922       pNew->pNext = 0;
   72923       if( pChunk ){
   72924         assert( p->pFirst );
   72925         pChunk->pNext = pNew;
   72926       }else{
   72927         assert( !p->pFirst );
   72928         p->pFirst = pNew;
   72929       }
   72930       p->endpoint.pChunk = pNew;
   72931     }
   72932 
   72933     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   72934     zWrite += iSpace;
   72935     nWrite -= iSpace;
   72936     p->endpoint.iOffset += iSpace;
   72937   }
   72938 
   72939   return SQLITE_OK;
   72940 }
   72941 
   72942 /*
   72943 ** Truncate the file.
   72944 */
   72945 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   72946   MemJournal *p = (MemJournal *)pJfd;
   72947   FileChunk *pChunk;
   72948   assert(size==0);
   72949   UNUSED_PARAMETER(size);
   72950   pChunk = p->pFirst;
   72951   while( pChunk ){
   72952     FileChunk *pTmp = pChunk;
   72953     pChunk = pChunk->pNext;
   72954     sqlite3_free(pTmp);
   72955   }
   72956   sqlite3MemJournalOpen(pJfd);
   72957   return SQLITE_OK;
   72958 }
   72959 
   72960 /*
   72961 ** Close the file.
   72962 */
   72963 static int memjrnlClose(sqlite3_file *pJfd){
   72964   memjrnlTruncate(pJfd, 0);
   72965   return SQLITE_OK;
   72966 }
   72967 
   72968 
   72969 /*
   72970 ** Sync the file.
   72971 **
   72972 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   72973 ** is never called in a working implementation.  This implementation
   72974 ** exists purely as a contingency, in case some malfunction in some other
   72975 ** part of SQLite causes Sync to be called by mistake.
   72976 */
   72977 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
   72978   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   72979   return SQLITE_OK;
   72980 }
   72981 
   72982 /*
   72983 ** Query the size of the file in bytes.
   72984 */
   72985 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   72986   MemJournal *p = (MemJournal *)pJfd;
   72987   *pSize = (sqlite_int64) p->endpoint.iOffset;
   72988   return SQLITE_OK;
   72989 }
   72990 
   72991 /*
   72992 ** Table of methods for MemJournal sqlite3_file object.
   72993 */
   72994 static const struct sqlite3_io_methods MemJournalMethods = {
   72995   1,                /* iVersion */
   72996   memjrnlClose,     /* xClose */
   72997   memjrnlRead,      /* xRead */
   72998   memjrnlWrite,     /* xWrite */
   72999   memjrnlTruncate,  /* xTruncate */
   73000   memjrnlSync,      /* xSync */
   73001   memjrnlFileSize,  /* xFileSize */
   73002   0,                /* xLock */
   73003   0,                /* xUnlock */
   73004   0,                /* xCheckReservedLock */
   73005   0,                /* xFileControl */
   73006   0,                /* xSectorSize */
   73007   0,                /* xDeviceCharacteristics */
   73008   0,                /* xShmMap */
   73009   0,                /* xShmLock */
   73010   0,                /* xShmBarrier */
   73011   0                 /* xShmUnlock */
   73012 };
   73013 
   73014 /*
   73015 ** Open a journal file.
   73016 */
   73017 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   73018   MemJournal *p = (MemJournal *)pJfd;
   73019   assert( EIGHT_BYTE_ALIGNMENT(p) );
   73020   memset(p, 0, sqlite3MemJournalSize());
   73021   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
   73022 }
   73023 
   73024 /*
   73025 ** Return true if the file-handle passed as an argument is
   73026 ** an in-memory journal
   73027 */
   73028 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   73029   return pJfd->pMethods==&MemJournalMethods;
   73030 }
   73031 
   73032 /*
   73033 ** Return the number of bytes required to store a MemJournal file descriptor.
   73034 */
   73035 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   73036   return sizeof(MemJournal);
   73037 }
   73038 
   73039 /************** End of memjournal.c ******************************************/
   73040 /************** Begin file walker.c ******************************************/
   73041 /*
   73042 ** 2008 August 16
   73043 **
   73044 ** The author disclaims copyright to this source code.  In place of
   73045 ** a legal notice, here is a blessing:
   73046 **
   73047 **    May you do good and not evil.
   73048 **    May you find forgiveness for yourself and forgive others.
   73049 **    May you share freely, never taking more than you give.
   73050 **
   73051 *************************************************************************
   73052 ** This file contains routines used for walking the parser tree for
   73053 ** an SQL statement.
   73054 */
   73055 /* #include <stdlib.h> */
   73056 /* #include <string.h> */
   73057 
   73058 
   73059 /*
   73060 ** Walk an expression tree.  Invoke the callback once for each node
   73061 ** of the expression, while decending.  (In other words, the callback
   73062 ** is invoked before visiting children.)
   73063 **
   73064 ** The return value from the callback should be one of the WRC_*
   73065 ** constants to specify how to proceed with the walk.
   73066 **
   73067 **    WRC_Continue      Continue descending down the tree.
   73068 **
   73069 **    WRC_Prune         Do not descend into child nodes.  But allow
   73070 **                      the walk to continue with sibling nodes.
   73071 **
   73072 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   73073 **                      return the top-level walk call.
   73074 **
   73075 ** The return value from this routine is WRC_Abort to abandon the tree walk
   73076 ** and WRC_Continue to continue.
   73077 */
   73078 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   73079   int rc;
   73080   if( pExpr==0 ) return WRC_Continue;
   73081   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   73082   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   73083   rc = pWalker->xExprCallback(pWalker, pExpr);
   73084   if( rc==WRC_Continue
   73085               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
   73086     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   73087     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   73088     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   73089       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   73090     }else{
   73091       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   73092     }
   73093   }
   73094   return rc & WRC_Abort;
   73095 }
   73096 
   73097 /*
   73098 ** Call sqlite3WalkExpr() for every expression in list p or until
   73099 ** an abort request is seen.
   73100 */
   73101 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   73102   int i;
   73103   struct ExprList_item *pItem;
   73104   if( p ){
   73105     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   73106       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   73107     }
   73108   }
   73109   return WRC_Continue;
   73110 }
   73111 
   73112 /*
   73113 ** Walk all expressions associated with SELECT statement p.  Do
   73114 ** not invoke the SELECT callback on p, but do (of course) invoke
   73115 ** any expr callbacks and SELECT callbacks that come from subqueries.
   73116 ** Return WRC_Abort or WRC_Continue.
   73117 */
   73118 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   73119   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   73120   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   73121   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   73122   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   73123   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   73124   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   73125   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   73126   return WRC_Continue;
   73127 }
   73128 
   73129 /*
   73130 ** Walk the parse trees associated with all subqueries in the
   73131 ** FROM clause of SELECT statement p.  Do not invoke the select
   73132 ** callback on p, but do invoke it on each FROM clause subquery
   73133 ** and on any subqueries further down in the tree.  Return
   73134 ** WRC_Abort or WRC_Continue;
   73135 */
   73136 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   73137   SrcList *pSrc;
   73138   int i;
   73139   struct SrcList_item *pItem;
   73140 
   73141   pSrc = p->pSrc;
   73142   if( ALWAYS(pSrc) ){
   73143     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   73144       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   73145         return WRC_Abort;
   73146       }
   73147     }
   73148   }
   73149   return WRC_Continue;
   73150 }
   73151 
   73152 /*
   73153 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   73154 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   73155 ** on the compound select chain, p->pPrior.
   73156 **
   73157 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   73158 ** there is an abort request.
   73159 **
   73160 ** If the Walker does not have an xSelectCallback() then this routine
   73161 ** is a no-op returning WRC_Continue.
   73162 */
   73163 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   73164   int rc;
   73165   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
   73166   rc = WRC_Continue;
   73167   while( p  ){
   73168     rc = pWalker->xSelectCallback(pWalker, p);
   73169     if( rc ) break;
   73170     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
   73171     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
   73172     p = p->pPrior;
   73173   }
   73174   return rc & WRC_Abort;
   73175 }
   73176 
   73177 /************** End of walker.c **********************************************/
   73178 /************** Begin file resolve.c *****************************************/
   73179 /*
   73180 ** 2008 August 18
   73181 **
   73182 ** The author disclaims copyright to this source code.  In place of
   73183 ** a legal notice, here is a blessing:
   73184 **
   73185 **    May you do good and not evil.
   73186 **    May you find forgiveness for yourself and forgive others.
   73187 **    May you share freely, never taking more than you give.
   73188 **
   73189 *************************************************************************
   73190 **
   73191 ** This file contains routines used for walking the parser tree and
   73192 ** resolve all identifiers by associating them with a particular
   73193 ** table and column.
   73194 */
   73195 /* #include <stdlib.h> */
   73196 /* #include <string.h> */
   73197 
   73198 /*
   73199 ** Turn the pExpr expression into an alias for the iCol-th column of the
   73200 ** result set in pEList.
   73201 **
   73202 ** If the result set column is a simple column reference, then this routine
   73203 ** makes an exact copy.  But for any other kind of expression, this
   73204 ** routine make a copy of the result set column as the argument to the
   73205 ** TK_AS operator.  The TK_AS operator causes the expression to be
   73206 ** evaluated just once and then reused for each alias.
   73207 **
   73208 ** The reason for suppressing the TK_AS term when the expression is a simple
   73209 ** column reference is so that the column reference will be recognized as
   73210 ** usable by indices within the WHERE clause processing logic.
   73211 **
   73212 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
   73213 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   73214 **
   73215 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   73216 **
   73217 ** Is equivalent to:
   73218 **
   73219 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   73220 **
   73221 ** The result of random()%5 in the GROUP BY clause is probably different
   73222 ** from the result in the result-set.  We might fix this someday.  Or
   73223 ** then again, we might not...
   73224 */
   73225 static void resolveAlias(
   73226   Parse *pParse,         /* Parsing context */
   73227   ExprList *pEList,      /* A result set */
   73228   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   73229   Expr *pExpr,           /* Transform this into an alias to the result set */
   73230   const char *zType      /* "GROUP" or "ORDER" or "" */
   73231 ){
   73232   Expr *pOrig;           /* The iCol-th column of the result set */
   73233   Expr *pDup;            /* Copy of pOrig */
   73234   sqlite3 *db;           /* The database connection */
   73235 
   73236   assert( iCol>=0 && iCol<pEList->nExpr );
   73237   pOrig = pEList->a[iCol].pExpr;
   73238   assert( pOrig!=0 );
   73239   assert( pOrig->flags & EP_Resolved );
   73240   db = pParse->db;
   73241   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   73242     pDup = sqlite3ExprDup(db, pOrig, 0);
   73243     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   73244     if( pDup==0 ) return;
   73245     if( pEList->a[iCol].iAlias==0 ){
   73246       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
   73247     }
   73248     pDup->iTable = pEList->a[iCol].iAlias;
   73249   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
   73250     pDup = sqlite3ExprDup(db, pOrig, 0);
   73251     if( pDup==0 ) return;
   73252   }else{
   73253     char *zToken = pOrig->u.zToken;
   73254     assert( zToken!=0 );
   73255     pOrig->u.zToken = 0;
   73256     pDup = sqlite3ExprDup(db, pOrig, 0);
   73257     pOrig->u.zToken = zToken;
   73258     if( pDup==0 ) return;
   73259     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
   73260     pDup->flags2 |= EP2_MallocedToken;
   73261     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
   73262   }
   73263   if( pExpr->flags & EP_ExpCollate ){
   73264     pDup->pColl = pExpr->pColl;
   73265     pDup->flags |= EP_ExpCollate;
   73266   }
   73267 
   73268   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   73269   ** prevents ExprDelete() from deleting the Expr structure itself,
   73270   ** allowing it to be repopulated by the memcpy() on the following line.
   73271   */
   73272   ExprSetProperty(pExpr, EP_Static);
   73273   sqlite3ExprDelete(db, pExpr);
   73274   memcpy(pExpr, pDup, sizeof(*pExpr));
   73275   sqlite3DbFree(db, pDup);
   73276 }
   73277 
   73278 
   73279 /*
   73280 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
   73281 **
   73282 ** Return FALSE if the USING clause is NULL or if it does not contain
   73283 ** zCol.
   73284 */
   73285 static int nameInUsingClause(IdList *pUsing, const char *zCol){
   73286   if( pUsing ){
   73287     int k;
   73288     for(k=0; k<pUsing->nId; k++){
   73289       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
   73290     }
   73291   }
   73292   return 0;
   73293 }
   73294 
   73295 
   73296 /*
   73297 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   73298 ** that name in the set of source tables in pSrcList and make the pExpr
   73299 ** expression node refer back to that source column.  The following changes
   73300 ** are made to pExpr:
   73301 **
   73302 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   73303 **                         (even if X is implied).
   73304 **    pExpr->iTable        Set to the cursor number for the table obtained
   73305 **                         from pSrcList.
   73306 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   73307 **                         X and/or Y are implied.)
   73308 **    pExpr->iColumn       Set to the column number within the table.
   73309 **    pExpr->op            Set to TK_COLUMN.
   73310 **    pExpr->pLeft         Any expression this points to is deleted
   73311 **    pExpr->pRight        Any expression this points to is deleted.
   73312 **
   73313 ** The zDb variable is the name of the database (the "X").  This value may be
   73314 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   73315 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   73316 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   73317 ** means that the form of the name is Z and that columns from any table
   73318 ** can be used.
   73319 **
   73320 ** If the name cannot be resolved unambiguously, leave an error message
   73321 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   73322 */
   73323 static int lookupName(
   73324   Parse *pParse,       /* The parsing context */
   73325   const char *zDb,     /* Name of the database containing table, or NULL */
   73326   const char *zTab,    /* Name of table containing column, or NULL */
   73327   const char *zCol,    /* Name of the column. */
   73328   NameContext *pNC,    /* The name context used to resolve the name */
   73329   Expr *pExpr          /* Make this EXPR node point to the selected column */
   73330 ){
   73331   int i, j;            /* Loop counters */
   73332   int cnt = 0;                      /* Number of matching column names */
   73333   int cntTab = 0;                   /* Number of matching table names */
   73334   sqlite3 *db = pParse->db;         /* The database connection */
   73335   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   73336   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   73337   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   73338   Schema *pSchema = 0;              /* Schema of the expression */
   73339   int isTrigger = 0;
   73340 
   73341   assert( pNC );     /* the name context cannot be NULL. */
   73342   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   73343   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   73344 
   73345   /* Initialize the node to no-match */
   73346   pExpr->iTable = -1;
   73347   pExpr->pTab = 0;
   73348   ExprSetIrreducible(pExpr);
   73349 
   73350   /* Start at the inner-most context and move outward until a match is found */
   73351   while( pNC && cnt==0 ){
   73352     ExprList *pEList;
   73353     SrcList *pSrcList = pNC->pSrcList;
   73354 
   73355     if( pSrcList ){
   73356       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   73357         Table *pTab;
   73358         int iDb;
   73359         Column *pCol;
   73360 
   73361         pTab = pItem->pTab;
   73362         assert( pTab!=0 && pTab->zName!=0 );
   73363         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   73364         assert( pTab->nCol>0 );
   73365         if( zTab ){
   73366           if( pItem->zAlias ){
   73367             char *zTabName = pItem->zAlias;
   73368             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   73369           }else{
   73370             char *zTabName = pTab->zName;
   73371             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
   73372               continue;
   73373             }
   73374             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
   73375               continue;
   73376             }
   73377           }
   73378         }
   73379         if( 0==(cntTab++) ){
   73380           pExpr->iTable = pItem->iCursor;
   73381           pExpr->pTab = pTab;
   73382           pSchema = pTab->pSchema;
   73383           pMatch = pItem;
   73384         }
   73385         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   73386           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   73387             /* If there has been exactly one prior match and this match
   73388             ** is for the right-hand table of a NATURAL JOIN or is in a
   73389             ** USING clause, then skip this match.
   73390             */
   73391             if( cnt==1 ){
   73392               if( pItem->jointype & JT_NATURAL ) continue;
   73393               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
   73394             }
   73395             cnt++;
   73396             pExpr->iTable = pItem->iCursor;
   73397             pExpr->pTab = pTab;
   73398             pMatch = pItem;
   73399             pSchema = pTab->pSchema;
   73400             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   73401             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   73402             break;
   73403           }
   73404         }
   73405       }
   73406     }
   73407 
   73408 #ifndef SQLITE_OMIT_TRIGGER
   73409     /* If we have not already resolved the name, then maybe
   73410     ** it is a new.* or old.* trigger argument reference
   73411     */
   73412     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
   73413       int op = pParse->eTriggerOp;
   73414       Table *pTab = 0;
   73415       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   73416       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   73417         pExpr->iTable = 1;
   73418         pTab = pParse->pTriggerTab;
   73419       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   73420         pExpr->iTable = 0;
   73421         pTab = pParse->pTriggerTab;
   73422       }
   73423 
   73424       if( pTab ){
   73425         int iCol;
   73426         pSchema = pTab->pSchema;
   73427         cntTab++;
   73428         for(iCol=0; iCol<pTab->nCol; iCol++){
   73429           Column *pCol = &pTab->aCol[iCol];
   73430           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   73431             if( iCol==pTab->iPKey ){
   73432               iCol = -1;
   73433             }
   73434             break;
   73435           }
   73436         }
   73437         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
   73438           iCol = -1;        /* IMP: R-44911-55124 */
   73439         }
   73440         if( iCol<pTab->nCol ){
   73441           cnt++;
   73442           if( iCol<0 ){
   73443             pExpr->affinity = SQLITE_AFF_INTEGER;
   73444           }else if( pExpr->iTable==0 ){
   73445             testcase( iCol==31 );
   73446             testcase( iCol==32 );
   73447             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   73448           }else{
   73449             testcase( iCol==31 );
   73450             testcase( iCol==32 );
   73451             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   73452           }
   73453           pExpr->iColumn = (i16)iCol;
   73454           pExpr->pTab = pTab;
   73455           isTrigger = 1;
   73456         }
   73457       }
   73458     }
   73459 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   73460 
   73461     /*
   73462     ** Perhaps the name is a reference to the ROWID
   73463     */
   73464     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
   73465       cnt = 1;
   73466       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   73467       pExpr->affinity = SQLITE_AFF_INTEGER;
   73468     }
   73469 
   73470     /*
   73471     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   73472     ** might refer to an result-set alias.  This happens, for example, when
   73473     ** we are resolving names in the WHERE clause of the following command:
   73474     **
   73475     **     SELECT a+b AS x FROM table WHERE x<10;
   73476     **
   73477     ** In cases like this, replace pExpr with a copy of the expression that
   73478     ** forms the result set entry ("a+b" in the example) and return immediately.
   73479     ** Note that the expression in the result set should have already been
   73480     ** resolved by the time the WHERE clause is resolved.
   73481     */
   73482     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
   73483       for(j=0; j<pEList->nExpr; j++){
   73484         char *zAs = pEList->a[j].zName;
   73485         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   73486           Expr *pOrig;
   73487           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   73488           assert( pExpr->x.pList==0 );
   73489           assert( pExpr->x.pSelect==0 );
   73490           pOrig = pEList->a[j].pExpr;
   73491           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
   73492             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   73493             return WRC_Abort;
   73494           }
   73495           resolveAlias(pParse, pEList, j, pExpr, "");
   73496           cnt = 1;
   73497           pMatch = 0;
   73498           assert( zTab==0 && zDb==0 );
   73499           goto lookupname_end;
   73500         }
   73501       }
   73502     }
   73503 
   73504     /* Advance to the next name context.  The loop will exit when either
   73505     ** we have a match (cnt>0) or when we run out of name contexts.
   73506     */
   73507     if( cnt==0 ){
   73508       pNC = pNC->pNext;
   73509     }
   73510   }
   73511 
   73512   /*
   73513   ** If X and Y are NULL (in other words if only the column name Z is
   73514   ** supplied) and the value of Z is enclosed in double-quotes, then
   73515   ** Z is a string literal if it doesn't match any column names.  In that
   73516   ** case, we need to return right away and not make any changes to
   73517   ** pExpr.
   73518   **
   73519   ** Because no reference was made to outer contexts, the pNC->nRef
   73520   ** fields are not changed in any context.
   73521   */
   73522   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   73523     pExpr->op = TK_STRING;
   73524     pExpr->pTab = 0;
   73525     return WRC_Prune;
   73526   }
   73527 
   73528   /*
   73529   ** cnt==0 means there was not match.  cnt>1 means there were two or
   73530   ** more matches.  Either way, we have an error.
   73531   */
   73532   if( cnt!=1 ){
   73533     const char *zErr;
   73534     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   73535     if( zDb ){
   73536       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   73537     }else if( zTab ){
   73538       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   73539     }else{
   73540       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   73541     }
   73542     pParse->checkSchema = 1;
   73543     pTopNC->nErr++;
   73544   }
   73545 
   73546   /* If a column from a table in pSrcList is referenced, then record
   73547   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   73548   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   73549   ** column number is greater than the number of bits in the bitmask
   73550   ** then set the high-order bit of the bitmask.
   73551   */
   73552   if( pExpr->iColumn>=0 && pMatch!=0 ){
   73553     int n = pExpr->iColumn;
   73554     testcase( n==BMS-1 );
   73555     if( n>=BMS ){
   73556       n = BMS-1;
   73557     }
   73558     assert( pMatch->iCursor==pExpr->iTable );
   73559     pMatch->colUsed |= ((Bitmask)1)<<n;
   73560   }
   73561 
   73562   /* Clean up and return
   73563   */
   73564   sqlite3ExprDelete(db, pExpr->pLeft);
   73565   pExpr->pLeft = 0;
   73566   sqlite3ExprDelete(db, pExpr->pRight);
   73567   pExpr->pRight = 0;
   73568   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   73569 lookupname_end:
   73570   if( cnt==1 ){
   73571     assert( pNC!=0 );
   73572     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   73573     /* Increment the nRef value on all name contexts from TopNC up to
   73574     ** the point where the name matched. */
   73575     for(;;){
   73576       assert( pTopNC!=0 );
   73577       pTopNC->nRef++;
   73578       if( pTopNC==pNC ) break;
   73579       pTopNC = pTopNC->pNext;
   73580     }
   73581     return WRC_Prune;
   73582   } else {
   73583     return WRC_Abort;
   73584   }
   73585 }
   73586 
   73587 /*
   73588 ** Allocate and return a pointer to an expression to load the column iCol
   73589 ** from datasource iSrc in SrcList pSrc.
   73590 */
   73591 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   73592   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   73593   if( p ){
   73594     struct SrcList_item *pItem = &pSrc->a[iSrc];
   73595     p->pTab = pItem->pTab;
   73596     p->iTable = pItem->iCursor;
   73597     if( p->pTab->iPKey==iCol ){
   73598       p->iColumn = -1;
   73599     }else{
   73600       p->iColumn = (ynVar)iCol;
   73601       testcase( iCol==BMS );
   73602       testcase( iCol==BMS-1 );
   73603       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   73604     }
   73605     ExprSetProperty(p, EP_Resolved);
   73606   }
   73607   return p;
   73608 }
   73609 
   73610 /*
   73611 ** This routine is callback for sqlite3WalkExpr().
   73612 **
   73613 ** Resolve symbolic names into TK_COLUMN operators for the current
   73614 ** node in the expression tree.  Return 0 to continue the search down
   73615 ** the tree or 2 to abort the tree walk.
   73616 **
   73617 ** This routine also does error checking and name resolution for
   73618 ** function names.  The operator for aggregate functions is changed
   73619 ** to TK_AGG_FUNCTION.
   73620 */
   73621 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   73622   NameContext *pNC;
   73623   Parse *pParse;
   73624 
   73625   pNC = pWalker->u.pNC;
   73626   assert( pNC!=0 );
   73627   pParse = pNC->pParse;
   73628   assert( pParse==pWalker->pParse );
   73629 
   73630   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   73631   ExprSetProperty(pExpr, EP_Resolved);
   73632 #ifndef NDEBUG
   73633   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   73634     SrcList *pSrcList = pNC->pSrcList;
   73635     int i;
   73636     for(i=0; i<pNC->pSrcList->nSrc; i++){
   73637       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   73638     }
   73639   }
   73640 #endif
   73641   switch( pExpr->op ){
   73642 
   73643 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   73644     /* The special operator TK_ROW means use the rowid for the first
   73645     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   73646     ** clause processing on UPDATE and DELETE statements.
   73647     */
   73648     case TK_ROW: {
   73649       SrcList *pSrcList = pNC->pSrcList;
   73650       struct SrcList_item *pItem;
   73651       assert( pSrcList && pSrcList->nSrc==1 );
   73652       pItem = pSrcList->a;
   73653       pExpr->op = TK_COLUMN;
   73654       pExpr->pTab = pItem->pTab;
   73655       pExpr->iTable = pItem->iCursor;
   73656       pExpr->iColumn = -1;
   73657       pExpr->affinity = SQLITE_AFF_INTEGER;
   73658       break;
   73659     }
   73660 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   73661 
   73662     /* A lone identifier is the name of a column.
   73663     */
   73664     case TK_ID: {
   73665       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   73666     }
   73667 
   73668     /* A table name and column name:     ID.ID
   73669     ** Or a database, table and column:  ID.ID.ID
   73670     */
   73671     case TK_DOT: {
   73672       const char *zColumn;
   73673       const char *zTable;
   73674       const char *zDb;
   73675       Expr *pRight;
   73676 
   73677       /* if( pSrcList==0 ) break; */
   73678       pRight = pExpr->pRight;
   73679       if( pRight->op==TK_ID ){
   73680         zDb = 0;
   73681         zTable = pExpr->pLeft->u.zToken;
   73682         zColumn = pRight->u.zToken;
   73683       }else{
   73684         assert( pRight->op==TK_DOT );
   73685         zDb = pExpr->pLeft->u.zToken;
   73686         zTable = pRight->pLeft->u.zToken;
   73687         zColumn = pRight->pRight->u.zToken;
   73688       }
   73689       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   73690     }
   73691 
   73692     /* Resolve function names
   73693     */
   73694     case TK_CONST_FUNC:
   73695     case TK_FUNCTION: {
   73696       ExprList *pList = pExpr->x.pList;    /* The argument list */
   73697       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   73698       int no_such_func = 0;       /* True if no such function exists */
   73699       int wrong_num_args = 0;     /* True if wrong number of arguments */
   73700       int is_agg = 0;             /* True if is an aggregate function */
   73701       int auth;                   /* Authorization to use the function */
   73702       int nId;                    /* Number of characters in function name */
   73703       const char *zId;            /* The function name. */
   73704       FuncDef *pDef;              /* Information about the function */
   73705       u8 enc = ENC(pParse->db);   /* The database encoding */
   73706 
   73707       testcase( pExpr->op==TK_CONST_FUNC );
   73708       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   73709       zId = pExpr->u.zToken;
   73710       nId = sqlite3Strlen30(zId);
   73711       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   73712       if( pDef==0 ){
   73713         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
   73714         if( pDef==0 ){
   73715           no_such_func = 1;
   73716         }else{
   73717           wrong_num_args = 1;
   73718         }
   73719       }else{
   73720         is_agg = pDef->xFunc==0;
   73721       }
   73722 #ifndef SQLITE_OMIT_AUTHORIZATION
   73723       if( pDef ){
   73724         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   73725         if( auth!=SQLITE_OK ){
   73726           if( auth==SQLITE_DENY ){
   73727             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   73728                                     pDef->zName);
   73729             pNC->nErr++;
   73730           }
   73731           pExpr->op = TK_NULL;
   73732           return WRC_Prune;
   73733         }
   73734       }
   73735 #endif
   73736       if( is_agg && !pNC->allowAgg ){
   73737         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   73738         pNC->nErr++;
   73739         is_agg = 0;
   73740       }else if( no_such_func ){
   73741         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   73742         pNC->nErr++;
   73743       }else if( wrong_num_args ){
   73744         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   73745              nId, zId);
   73746         pNC->nErr++;
   73747       }
   73748       if( is_agg ){
   73749         pExpr->op = TK_AGG_FUNCTION;
   73750         pNC->hasAgg = 1;
   73751       }
   73752       if( is_agg ) pNC->allowAgg = 0;
   73753       sqlite3WalkExprList(pWalker, pList);
   73754       if( is_agg ) pNC->allowAgg = 1;
   73755       /* FIX ME:  Compute pExpr->affinity based on the expected return
   73756       ** type of the function
   73757       */
   73758       return WRC_Prune;
   73759     }
   73760 #ifndef SQLITE_OMIT_SUBQUERY
   73761     case TK_SELECT:
   73762     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   73763 #endif
   73764     case TK_IN: {
   73765       testcase( pExpr->op==TK_IN );
   73766       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   73767         int nRef = pNC->nRef;
   73768 #ifndef SQLITE_OMIT_CHECK
   73769         if( pNC->isCheck ){
   73770           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
   73771         }
   73772 #endif
   73773         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   73774         assert( pNC->nRef>=nRef );
   73775         if( nRef!=pNC->nRef ){
   73776           ExprSetProperty(pExpr, EP_VarSelect);
   73777         }
   73778       }
   73779       break;
   73780     }
   73781 #ifndef SQLITE_OMIT_CHECK
   73782     case TK_VARIABLE: {
   73783       if( pNC->isCheck ){
   73784         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
   73785       }
   73786       break;
   73787     }
   73788 #endif
   73789   }
   73790   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   73791 }
   73792 
   73793 /*
   73794 ** pEList is a list of expressions which are really the result set of the
   73795 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   73796 ** This routine checks to see if pE is a simple identifier which corresponds
   73797 ** to the AS-name of one of the terms of the expression list.  If it is,
   73798 ** this routine return an integer between 1 and N where N is the number of
   73799 ** elements in pEList, corresponding to the matching entry.  If there is
   73800 ** no match, or if pE is not a simple identifier, then this routine
   73801 ** return 0.
   73802 **
   73803 ** pEList has been resolved.  pE has not.
   73804 */
   73805 static int resolveAsName(
   73806   Parse *pParse,     /* Parsing context for error messages */
   73807   ExprList *pEList,  /* List of expressions to scan */
   73808   Expr *pE           /* Expression we are trying to match */
   73809 ){
   73810   int i;             /* Loop counter */
   73811 
   73812   UNUSED_PARAMETER(pParse);
   73813 
   73814   if( pE->op==TK_ID ){
   73815     char *zCol = pE->u.zToken;
   73816     for(i=0; i<pEList->nExpr; i++){
   73817       char *zAs = pEList->a[i].zName;
   73818       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   73819         return i+1;
   73820       }
   73821     }
   73822   }
   73823   return 0;
   73824 }
   73825 
   73826 /*
   73827 ** pE is a pointer to an expression which is a single term in the
   73828 ** ORDER BY of a compound SELECT.  The expression has not been
   73829 ** name resolved.
   73830 **
   73831 ** At the point this routine is called, we already know that the
   73832 ** ORDER BY term is not an integer index into the result set.  That
   73833 ** case is handled by the calling routine.
   73834 **
   73835 ** Attempt to match pE against result set columns in the left-most
   73836 ** SELECT statement.  Return the index i of the matching column,
   73837 ** as an indication to the caller that it should sort by the i-th column.
   73838 ** The left-most column is 1.  In other words, the value returned is the
   73839 ** same integer value that would be used in the SQL statement to indicate
   73840 ** the column.
   73841 **
   73842 ** If there is no match, return 0.  Return -1 if an error occurs.
   73843 */
   73844 static int resolveOrderByTermToExprList(
   73845   Parse *pParse,     /* Parsing context for error messages */
   73846   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   73847   Expr *pE           /* The specific ORDER BY term */
   73848 ){
   73849   int i;             /* Loop counter */
   73850   ExprList *pEList;  /* The columns of the result set */
   73851   NameContext nc;    /* Name context for resolving pE */
   73852   sqlite3 *db;       /* Database connection */
   73853   int rc;            /* Return code from subprocedures */
   73854   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   73855 
   73856   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   73857   pEList = pSelect->pEList;
   73858 
   73859   /* Resolve all names in the ORDER BY term expression
   73860   */
   73861   memset(&nc, 0, sizeof(nc));
   73862   nc.pParse = pParse;
   73863   nc.pSrcList = pSelect->pSrc;
   73864   nc.pEList = pEList;
   73865   nc.allowAgg = 1;
   73866   nc.nErr = 0;
   73867   db = pParse->db;
   73868   savedSuppErr = db->suppressErr;
   73869   db->suppressErr = 1;
   73870   rc = sqlite3ResolveExprNames(&nc, pE);
   73871   db->suppressErr = savedSuppErr;
   73872   if( rc ) return 0;
   73873 
   73874   /* Try to match the ORDER BY expression against an expression
   73875   ** in the result set.  Return an 1-based index of the matching
   73876   ** result-set entry.
   73877   */
   73878   for(i=0; i<pEList->nExpr; i++){
   73879     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
   73880       return i+1;
   73881     }
   73882   }
   73883 
   73884   /* If no match, return 0. */
   73885   return 0;
   73886 }
   73887 
   73888 /*
   73889 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   73890 */
   73891 static void resolveOutOfRangeError(
   73892   Parse *pParse,         /* The error context into which to write the error */
   73893   const char *zType,     /* "ORDER" or "GROUP" */
   73894   int i,                 /* The index (1-based) of the term out of range */
   73895   int mx                 /* Largest permissible value of i */
   73896 ){
   73897   sqlite3ErrorMsg(pParse,
   73898     "%r %s BY term out of range - should be "
   73899     "between 1 and %d", i, zType, mx);
   73900 }
   73901 
   73902 /*
   73903 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   73904 ** each term of the ORDER BY clause is a constant integer between 1
   73905 ** and N where N is the number of columns in the compound SELECT.
   73906 **
   73907 ** ORDER BY terms that are already an integer between 1 and N are
   73908 ** unmodified.  ORDER BY terms that are integers outside the range of
   73909 ** 1 through N generate an error.  ORDER BY terms that are expressions
   73910 ** are matched against result set expressions of compound SELECT
   73911 ** beginning with the left-most SELECT and working toward the right.
   73912 ** At the first match, the ORDER BY expression is transformed into
   73913 ** the integer column number.
   73914 **
   73915 ** Return the number of errors seen.
   73916 */
   73917 static int resolveCompoundOrderBy(
   73918   Parse *pParse,        /* Parsing context.  Leave error messages here */
   73919   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   73920 ){
   73921   int i;
   73922   ExprList *pOrderBy;
   73923   ExprList *pEList;
   73924   sqlite3 *db;
   73925   int moreToDo = 1;
   73926 
   73927   pOrderBy = pSelect->pOrderBy;
   73928   if( pOrderBy==0 ) return 0;
   73929   db = pParse->db;
   73930 #if SQLITE_MAX_COLUMN
   73931   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   73932     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   73933     return 1;
   73934   }
   73935 #endif
   73936   for(i=0; i<pOrderBy->nExpr; i++){
   73937     pOrderBy->a[i].done = 0;
   73938   }
   73939   pSelect->pNext = 0;
   73940   while( pSelect->pPrior ){
   73941     pSelect->pPrior->pNext = pSelect;
   73942     pSelect = pSelect->pPrior;
   73943   }
   73944   while( pSelect && moreToDo ){
   73945     struct ExprList_item *pItem;
   73946     moreToDo = 0;
   73947     pEList = pSelect->pEList;
   73948     assert( pEList!=0 );
   73949     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   73950       int iCol = -1;
   73951       Expr *pE, *pDup;
   73952       if( pItem->done ) continue;
   73953       pE = pItem->pExpr;
   73954       if( sqlite3ExprIsInteger(pE, &iCol) ){
   73955         if( iCol<=0 || iCol>pEList->nExpr ){
   73956           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   73957           return 1;
   73958         }
   73959       }else{
   73960         iCol = resolveAsName(pParse, pEList, pE);
   73961         if( iCol==0 ){
   73962           pDup = sqlite3ExprDup(db, pE, 0);
   73963           if( !db->mallocFailed ){
   73964             assert(pDup);
   73965             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   73966           }
   73967           sqlite3ExprDelete(db, pDup);
   73968         }
   73969       }
   73970       if( iCol>0 ){
   73971         CollSeq *pColl = pE->pColl;
   73972         int flags = pE->flags & EP_ExpCollate;
   73973         sqlite3ExprDelete(db, pE);
   73974         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
   73975         if( pE==0 ) return 1;
   73976         pE->pColl = pColl;
   73977         pE->flags |= EP_IntValue | flags;
   73978         pE->u.iValue = iCol;
   73979         pItem->iOrderByCol = (u16)iCol;
   73980         pItem->done = 1;
   73981       }else{
   73982         moreToDo = 1;
   73983       }
   73984     }
   73985     pSelect = pSelect->pNext;
   73986   }
   73987   for(i=0; i<pOrderBy->nExpr; i++){
   73988     if( pOrderBy->a[i].done==0 ){
   73989       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   73990             "column in the result set", i+1);
   73991       return 1;
   73992     }
   73993   }
   73994   return 0;
   73995 }
   73996 
   73997 /*
   73998 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   73999 ** the SELECT statement pSelect.  If any term is reference to a
   74000 ** result set expression (as determined by the ExprList.a.iCol field)
   74001 ** then convert that term into a copy of the corresponding result set
   74002 ** column.
   74003 **
   74004 ** If any errors are detected, add an error message to pParse and
   74005 ** return non-zero.  Return zero if no errors are seen.
   74006 */
   74007 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   74008   Parse *pParse,        /* Parsing context.  Leave error messages here */
   74009   Select *pSelect,      /* The SELECT statement containing the clause */
   74010   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   74011   const char *zType     /* "ORDER" or "GROUP" */
   74012 ){
   74013   int i;
   74014   sqlite3 *db = pParse->db;
   74015   ExprList *pEList;
   74016   struct ExprList_item *pItem;
   74017 
   74018   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   74019 #if SQLITE_MAX_COLUMN
   74020   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   74021     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   74022     return 1;
   74023   }
   74024 #endif
   74025   pEList = pSelect->pEList;
   74026   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   74027   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   74028     if( pItem->iOrderByCol ){
   74029       if( pItem->iOrderByCol>pEList->nExpr ){
   74030         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   74031         return 1;
   74032       }
   74033       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
   74034     }
   74035   }
   74036   return 0;
   74037 }
   74038 
   74039 /*
   74040 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   74041 ** The Name context of the SELECT statement is pNC.  zType is either
   74042 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   74043 **
   74044 ** This routine resolves each term of the clause into an expression.
   74045 ** If the order-by term is an integer I between 1 and N (where N is the
   74046 ** number of columns in the result set of the SELECT) then the expression
   74047 ** in the resolution is a copy of the I-th result-set expression.  If
   74048 ** the order-by term is an identify that corresponds to the AS-name of
   74049 ** a result-set expression, then the term resolves to a copy of the
   74050 ** result-set expression.  Otherwise, the expression is resolved in
   74051 ** the usual way - using sqlite3ResolveExprNames().
   74052 **
   74053 ** This routine returns the number of errors.  If errors occur, then
   74054 ** an appropriate error message might be left in pParse.  (OOM errors
   74055 ** excepted.)
   74056 */
   74057 static int resolveOrderGroupBy(
   74058   NameContext *pNC,     /* The name context of the SELECT statement */
   74059   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   74060   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   74061   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   74062 ){
   74063   int i;                         /* Loop counter */
   74064   int iCol;                      /* Column number */
   74065   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   74066   Parse *pParse;                 /* Parsing context */
   74067   int nResult;                   /* Number of terms in the result set */
   74068 
   74069   if( pOrderBy==0 ) return 0;
   74070   nResult = pSelect->pEList->nExpr;
   74071   pParse = pNC->pParse;
   74072   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   74073     Expr *pE = pItem->pExpr;
   74074     iCol = resolveAsName(pParse, pSelect->pEList, pE);
   74075     if( iCol>0 ){
   74076       /* If an AS-name match is found, mark this ORDER BY column as being
   74077       ** a copy of the iCol-th result-set column.  The subsequent call to
   74078       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   74079       ** copy of the iCol-th result-set expression. */
   74080       pItem->iOrderByCol = (u16)iCol;
   74081       continue;
   74082     }
   74083     if( sqlite3ExprIsInteger(pE, &iCol) ){
   74084       /* The ORDER BY term is an integer constant.  Again, set the column
   74085       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   74086       ** order-by term to a copy of the result-set expression */
   74087       if( iCol<1 ){
   74088         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   74089         return 1;
   74090       }
   74091       pItem->iOrderByCol = (u16)iCol;
   74092       continue;
   74093     }
   74094 
   74095     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   74096     pItem->iOrderByCol = 0;
   74097     if( sqlite3ResolveExprNames(pNC, pE) ){
   74098       return 1;
   74099     }
   74100   }
   74101   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   74102 }
   74103 
   74104 /*
   74105 ** Resolve names in the SELECT statement p and all of its descendents.
   74106 */
   74107 static int resolveSelectStep(Walker *pWalker, Select *p){
   74108   NameContext *pOuterNC;  /* Context that contains this SELECT */
   74109   NameContext sNC;        /* Name context of this SELECT */
   74110   int isCompound;         /* True if p is a compound select */
   74111   int nCompound;          /* Number of compound terms processed so far */
   74112   Parse *pParse;          /* Parsing context */
   74113   ExprList *pEList;       /* Result set expression list */
   74114   int i;                  /* Loop counter */
   74115   ExprList *pGroupBy;     /* The GROUP BY clause */
   74116   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   74117   sqlite3 *db;            /* Database connection */
   74118 
   74119 
   74120   assert( p!=0 );
   74121   if( p->selFlags & SF_Resolved ){
   74122     return WRC_Prune;
   74123   }
   74124   pOuterNC = pWalker->u.pNC;
   74125   pParse = pWalker->pParse;
   74126   db = pParse->db;
   74127 
   74128   /* Normally sqlite3SelectExpand() will be called first and will have
   74129   ** already expanded this SELECT.  However, if this is a subquery within
   74130   ** an expression, sqlite3ResolveExprNames() will be called without a
   74131   ** prior call to sqlite3SelectExpand().  When that happens, let
   74132   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   74133   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   74134   ** this routine in the correct order.
   74135   */
   74136   if( (p->selFlags & SF_Expanded)==0 ){
   74137     sqlite3SelectPrep(pParse, p, pOuterNC);
   74138     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   74139   }
   74140 
   74141   isCompound = p->pPrior!=0;
   74142   nCompound = 0;
   74143   pLeftmost = p;
   74144   while( p ){
   74145     assert( (p->selFlags & SF_Expanded)!=0 );
   74146     assert( (p->selFlags & SF_Resolved)==0 );
   74147     p->selFlags |= SF_Resolved;
   74148 
   74149     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   74150     ** are not allowed to refer to any names, so pass an empty NameContext.
   74151     */
   74152     memset(&sNC, 0, sizeof(sNC));
   74153     sNC.pParse = pParse;
   74154     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   74155         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   74156       return WRC_Abort;
   74157     }
   74158 
   74159     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   74160     ** resolve the result-set expression list.
   74161     */
   74162     sNC.allowAgg = 1;
   74163     sNC.pSrcList = p->pSrc;
   74164     sNC.pNext = pOuterNC;
   74165 
   74166     /* Resolve names in the result set. */
   74167     pEList = p->pEList;
   74168     assert( pEList!=0 );
   74169     for(i=0; i<pEList->nExpr; i++){
   74170       Expr *pX = pEList->a[i].pExpr;
   74171       if( sqlite3ResolveExprNames(&sNC, pX) ){
   74172         return WRC_Abort;
   74173       }
   74174     }
   74175 
   74176     /* Recursively resolve names in all subqueries
   74177     */
   74178     for(i=0; i<p->pSrc->nSrc; i++){
   74179       struct SrcList_item *pItem = &p->pSrc->a[i];
   74180       if( pItem->pSelect ){
   74181         NameContext *pNC;         /* Used to iterate name contexts */
   74182         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
   74183         const char *zSavedContext = pParse->zAuthContext;
   74184 
   74185         /* Count the total number of references to pOuterNC and all of its
   74186         ** parent contexts. After resolving references to expressions in
   74187         ** pItem->pSelect, check if this value has changed. If so, then
   74188         ** SELECT statement pItem->pSelect must be correlated. Set the
   74189         ** pItem->isCorrelated flag if this is the case. */
   74190         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
   74191 
   74192         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   74193         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   74194         pParse->zAuthContext = zSavedContext;
   74195         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   74196 
   74197         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
   74198         assert( pItem->isCorrelated==0 && nRef<=0 );
   74199         pItem->isCorrelated = (nRef!=0);
   74200       }
   74201     }
   74202 
   74203     /* If there are no aggregate functions in the result-set, and no GROUP BY
   74204     ** expression, do not allow aggregates in any of the other expressions.
   74205     */
   74206     assert( (p->selFlags & SF_Aggregate)==0 );
   74207     pGroupBy = p->pGroupBy;
   74208     if( pGroupBy || sNC.hasAgg ){
   74209       p->selFlags |= SF_Aggregate;
   74210     }else{
   74211       sNC.allowAgg = 0;
   74212     }
   74213 
   74214     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   74215     */
   74216     if( p->pHaving && !pGroupBy ){
   74217       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   74218       return WRC_Abort;
   74219     }
   74220 
   74221     /* Add the expression list to the name-context before parsing the
   74222     ** other expressions in the SELECT statement. This is so that
   74223     ** expressions in the WHERE clause (etc.) can refer to expressions by
   74224     ** aliases in the result set.
   74225     **
   74226     ** Minor point: If this is the case, then the expression will be
   74227     ** re-evaluated for each reference to it.
   74228     */
   74229     sNC.pEList = p->pEList;
   74230     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
   74231        sqlite3ResolveExprNames(&sNC, p->pHaving)
   74232     ){
   74233       return WRC_Abort;
   74234     }
   74235 
   74236     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   74237     ** outer queries
   74238     */
   74239     sNC.pNext = 0;
   74240     sNC.allowAgg = 1;
   74241 
   74242     /* Process the ORDER BY clause for singleton SELECT statements.
   74243     ** The ORDER BY clause for compounds SELECT statements is handled
   74244     ** below, after all of the result-sets for all of the elements of
   74245     ** the compound have been resolved.
   74246     */
   74247     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   74248       return WRC_Abort;
   74249     }
   74250     if( db->mallocFailed ){
   74251       return WRC_Abort;
   74252     }
   74253 
   74254     /* Resolve the GROUP BY clause.  At the same time, make sure
   74255     ** the GROUP BY clause does not contain aggregate functions.
   74256     */
   74257     if( pGroupBy ){
   74258       struct ExprList_item *pItem;
   74259 
   74260       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   74261         return WRC_Abort;
   74262       }
   74263       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   74264         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   74265           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   74266               "the GROUP BY clause");
   74267           return WRC_Abort;
   74268         }
   74269       }
   74270     }
   74271 
   74272     /* Advance to the next term of the compound
   74273     */
   74274     p = p->pPrior;
   74275     nCompound++;
   74276   }
   74277 
   74278   /* Resolve the ORDER BY on a compound SELECT after all terms of
   74279   ** the compound have been resolved.
   74280   */
   74281   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   74282     return WRC_Abort;
   74283   }
   74284 
   74285   return WRC_Prune;
   74286 }
   74287 
   74288 /*
   74289 ** This routine walks an expression tree and resolves references to
   74290 ** table columns and result-set columns.  At the same time, do error
   74291 ** checking on function usage and set a flag if any aggregate functions
   74292 ** are seen.
   74293 **
   74294 ** To resolve table columns references we look for nodes (or subtrees) of the
   74295 ** form X.Y.Z or Y.Z or just Z where
   74296 **
   74297 **      X:   The name of a database.  Ex:  "main" or "temp" or
   74298 **           the symbolic name assigned to an ATTACH-ed database.
   74299 **
   74300 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   74301 **           one of the special names "old" or "new".
   74302 **
   74303 **      Z:   The name of a column in table Y.
   74304 **
   74305 ** The node at the root of the subtree is modified as follows:
   74306 **
   74307 **    Expr.op        Changed to TK_COLUMN
   74308 **    Expr.pTab      Points to the Table object for X.Y
   74309 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   74310 **    Expr.iTable    The VDBE cursor number for X.Y
   74311 **
   74312 **
   74313 ** To resolve result-set references, look for expression nodes of the
   74314 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   74315 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   74316 ** is replaced by a copy of the left-hand side of the result-set expression.
   74317 ** Table-name and function resolution occurs on the substituted expression
   74318 ** tree.  For example, in:
   74319 **
   74320 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   74321 **
   74322 ** The "x" term of the order by is replaced by "a+b" to render:
   74323 **
   74324 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   74325 **
   74326 ** Function calls are checked to make sure that the function is
   74327 ** defined and that the correct number of arguments are specified.
   74328 ** If the function is an aggregate function, then the pNC->hasAgg is
   74329 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   74330 ** If an expression contains aggregate functions then the EP_Agg
   74331 ** property on the expression is set.
   74332 **
   74333 ** An error message is left in pParse if anything is amiss.  The number
   74334 ** if errors is returned.
   74335 */
   74336 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   74337   NameContext *pNC,       /* Namespace to resolve expressions in. */
   74338   Expr *pExpr             /* The expression to be analyzed. */
   74339 ){
   74340   int savedHasAgg;
   74341   Walker w;
   74342 
   74343   if( pExpr==0 ) return 0;
   74344 #if SQLITE_MAX_EXPR_DEPTH>0
   74345   {
   74346     Parse *pParse = pNC->pParse;
   74347     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   74348       return 1;
   74349     }
   74350     pParse->nHeight += pExpr->nHeight;
   74351   }
   74352 #endif
   74353   savedHasAgg = pNC->hasAgg;
   74354   pNC->hasAgg = 0;
   74355   w.xExprCallback = resolveExprStep;
   74356   w.xSelectCallback = resolveSelectStep;
   74357   w.pParse = pNC->pParse;
   74358   w.u.pNC = pNC;
   74359   sqlite3WalkExpr(&w, pExpr);
   74360 #if SQLITE_MAX_EXPR_DEPTH>0
   74361   pNC->pParse->nHeight -= pExpr->nHeight;
   74362 #endif
   74363   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   74364     ExprSetProperty(pExpr, EP_Error);
   74365   }
   74366   if( pNC->hasAgg ){
   74367     ExprSetProperty(pExpr, EP_Agg);
   74368   }else if( savedHasAgg ){
   74369     pNC->hasAgg = 1;
   74370   }
   74371   return ExprHasProperty(pExpr, EP_Error);
   74372 }
   74373 
   74374 
   74375 /*
   74376 ** Resolve all names in all expressions of a SELECT and in all
   74377 ** decendents of the SELECT, including compounds off of p->pPrior,
   74378 ** subqueries in expressions, and subqueries used as FROM clause
   74379 ** terms.
   74380 **
   74381 ** See sqlite3ResolveExprNames() for a description of the kinds of
   74382 ** transformations that occur.
   74383 **
   74384 ** All SELECT statements should have been expanded using
   74385 ** sqlite3SelectExpand() prior to invoking this routine.
   74386 */
   74387 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   74388   Parse *pParse,         /* The parser context */
   74389   Select *p,             /* The SELECT statement being coded. */
   74390   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   74391 ){
   74392   Walker w;
   74393 
   74394   assert( p!=0 );
   74395   w.xExprCallback = resolveExprStep;
   74396   w.xSelectCallback = resolveSelectStep;
   74397   w.pParse = pParse;
   74398   w.u.pNC = pOuterNC;
   74399   sqlite3WalkSelect(&w, p);
   74400 }
   74401 
   74402 /************** End of resolve.c *********************************************/
   74403 /************** Begin file expr.c ********************************************/
   74404 /*
   74405 ** 2001 September 15
   74406 **
   74407 ** The author disclaims copyright to this source code.  In place of
   74408 ** a legal notice, here is a blessing:
   74409 **
   74410 **    May you do good and not evil.
   74411 **    May you find forgiveness for yourself and forgive others.
   74412 **    May you share freely, never taking more than you give.
   74413 **
   74414 *************************************************************************
   74415 ** This file contains routines used for analyzing expressions and
   74416 ** for generating VDBE code that evaluates expressions in SQLite.
   74417 */
   74418 
   74419 /*
   74420 ** Return the 'affinity' of the expression pExpr if any.
   74421 **
   74422 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   74423 ** or a sub-select with a column as the return value, then the
   74424 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   74425 ** indicating no affinity for the expression.
   74426 **
   74427 ** i.e. the WHERE clause expresssions in the following statements all
   74428 ** have an affinity:
   74429 **
   74430 ** CREATE TABLE t1(a);
   74431 ** SELECT * FROM t1 WHERE a;
   74432 ** SELECT a AS b FROM t1 WHERE b;
   74433 ** SELECT * FROM t1 WHERE (select a from t1);
   74434 */
   74435 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   74436   int op = pExpr->op;
   74437   if( op==TK_SELECT ){
   74438     assert( pExpr->flags&EP_xIsSelect );
   74439     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   74440   }
   74441 #ifndef SQLITE_OMIT_CAST
   74442   if( op==TK_CAST ){
   74443     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   74444     return sqlite3AffinityType(pExpr->u.zToken);
   74445   }
   74446 #endif
   74447   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   74448    && pExpr->pTab!=0
   74449   ){
   74450     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   74451     ** a TK_COLUMN but was previously evaluated and cached in a register */
   74452     int j = pExpr->iColumn;
   74453     if( j<0 ) return SQLITE_AFF_INTEGER;
   74454     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   74455     return pExpr->pTab->aCol[j].affinity;
   74456   }
   74457   return pExpr->affinity;
   74458 }
   74459 
   74460 /*
   74461 ** Set the explicit collating sequence for an expression to the
   74462 ** collating sequence supplied in the second argument.
   74463 */
   74464 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
   74465   if( pExpr && pColl ){
   74466     pExpr->pColl = pColl;
   74467     pExpr->flags |= EP_ExpCollate;
   74468   }
   74469   return pExpr;
   74470 }
   74471 
   74472 /*
   74473 ** Set the collating sequence for expression pExpr to be the collating
   74474 ** sequence named by pToken.   Return a pointer to the revised expression.
   74475 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
   74476 ** flag.  An explicit collating sequence will override implicit
   74477 ** collating sequences.
   74478 */
   74479 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
   74480   char *zColl = 0;            /* Dequoted name of collation sequence */
   74481   CollSeq *pColl;
   74482   sqlite3 *db = pParse->db;
   74483   zColl = sqlite3NameFromToken(db, pCollName);
   74484   pColl = sqlite3LocateCollSeq(pParse, zColl);
   74485   sqlite3ExprSetColl(pExpr, pColl);
   74486   sqlite3DbFree(db, zColl);
   74487   return pExpr;
   74488 }
   74489 
   74490 /*
   74491 ** Return the default collation sequence for the expression pExpr. If
   74492 ** there is no default collation type, return 0.
   74493 */
   74494 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   74495   CollSeq *pColl = 0;
   74496   Expr *p = pExpr;
   74497   while( p ){
   74498     int op;
   74499     pColl = p->pColl;
   74500     if( pColl ) break;
   74501     op = p->op;
   74502     if( p->pTab!=0 && (
   74503         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
   74504     )){
   74505       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   74506       ** a TK_COLUMN but was previously evaluated and cached in a register */
   74507       const char *zColl;
   74508       int j = p->iColumn;
   74509       if( j>=0 ){
   74510         sqlite3 *db = pParse->db;
   74511         zColl = p->pTab->aCol[j].zColl;
   74512         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   74513         pExpr->pColl = pColl;
   74514       }
   74515       break;
   74516     }
   74517     if( op!=TK_CAST && op!=TK_UPLUS ){
   74518       break;
   74519     }
   74520     p = p->pLeft;
   74521   }
   74522   if( sqlite3CheckCollSeq(pParse, pColl) ){
   74523     pColl = 0;
   74524   }
   74525   return pColl;
   74526 }
   74527 
   74528 /*
   74529 ** pExpr is an operand of a comparison operator.  aff2 is the
   74530 ** type affinity of the other operand.  This routine returns the
   74531 ** type affinity that should be used for the comparison operator.
   74532 */
   74533 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   74534   char aff1 = sqlite3ExprAffinity(pExpr);
   74535   if( aff1 && aff2 ){
   74536     /* Both sides of the comparison are columns. If one has numeric
   74537     ** affinity, use that. Otherwise use no affinity.
   74538     */
   74539     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   74540       return SQLITE_AFF_NUMERIC;
   74541     }else{
   74542       return SQLITE_AFF_NONE;
   74543     }
   74544   }else if( !aff1 && !aff2 ){
   74545     /* Neither side of the comparison is a column.  Compare the
   74546     ** results directly.
   74547     */
   74548     return SQLITE_AFF_NONE;
   74549   }else{
   74550     /* One side is a column, the other is not. Use the columns affinity. */
   74551     assert( aff1==0 || aff2==0 );
   74552     return (aff1 + aff2);
   74553   }
   74554 }
   74555 
   74556 /*
   74557 ** pExpr is a comparison operator.  Return the type affinity that should
   74558 ** be applied to both operands prior to doing the comparison.
   74559 */
   74560 static char comparisonAffinity(Expr *pExpr){
   74561   char aff;
   74562   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   74563           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   74564           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   74565   assert( pExpr->pLeft );
   74566   aff = sqlite3ExprAffinity(pExpr->pLeft);
   74567   if( pExpr->pRight ){
   74568     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   74569   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   74570     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   74571   }else if( !aff ){
   74572     aff = SQLITE_AFF_NONE;
   74573   }
   74574   return aff;
   74575 }
   74576 
   74577 /*
   74578 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   74579 ** idx_affinity is the affinity of an indexed column. Return true
   74580 ** if the index with affinity idx_affinity may be used to implement
   74581 ** the comparison in pExpr.
   74582 */
   74583 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   74584   char aff = comparisonAffinity(pExpr);
   74585   switch( aff ){
   74586     case SQLITE_AFF_NONE:
   74587       return 1;
   74588     case SQLITE_AFF_TEXT:
   74589       return idx_affinity==SQLITE_AFF_TEXT;
   74590     default:
   74591       return sqlite3IsNumericAffinity(idx_affinity);
   74592   }
   74593 }
   74594 
   74595 /*
   74596 ** Return the P5 value that should be used for a binary comparison
   74597 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   74598 */
   74599 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   74600   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   74601   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   74602   return aff;
   74603 }
   74604 
   74605 /*
   74606 ** Return a pointer to the collation sequence that should be used by
   74607 ** a binary comparison operator comparing pLeft and pRight.
   74608 **
   74609 ** If the left hand expression has a collating sequence type, then it is
   74610 ** used. Otherwise the collation sequence for the right hand expression
   74611 ** is used, or the default (BINARY) if neither expression has a collating
   74612 ** type.
   74613 **
   74614 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   74615 ** it is not considered.
   74616 */
   74617 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   74618   Parse *pParse,
   74619   Expr *pLeft,
   74620   Expr *pRight
   74621 ){
   74622   CollSeq *pColl;
   74623   assert( pLeft );
   74624   if( pLeft->flags & EP_ExpCollate ){
   74625     assert( pLeft->pColl );
   74626     pColl = pLeft->pColl;
   74627   }else if( pRight && pRight->flags & EP_ExpCollate ){
   74628     assert( pRight->pColl );
   74629     pColl = pRight->pColl;
   74630   }else{
   74631     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   74632     if( !pColl ){
   74633       pColl = sqlite3ExprCollSeq(pParse, pRight);
   74634     }
   74635   }
   74636   return pColl;
   74637 }
   74638 
   74639 /*
   74640 ** Generate code for a comparison operator.
   74641 */
   74642 static int codeCompare(
   74643   Parse *pParse,    /* The parsing (and code generating) context */
   74644   Expr *pLeft,      /* The left operand */
   74645   Expr *pRight,     /* The right operand */
   74646   int opcode,       /* The comparison opcode */
   74647   int in1, int in2, /* Register holding operands */
   74648   int dest,         /* Jump here if true.  */
   74649   int jumpIfNull    /* If true, jump if either operand is NULL */
   74650 ){
   74651   int p5;
   74652   int addr;
   74653   CollSeq *p4;
   74654 
   74655   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   74656   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   74657   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   74658                            (void*)p4, P4_COLLSEQ);
   74659   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   74660   return addr;
   74661 }
   74662 
   74663 #if SQLITE_MAX_EXPR_DEPTH>0
   74664 /*
   74665 ** Check that argument nHeight is less than or equal to the maximum
   74666 ** expression depth allowed. If it is not, leave an error message in
   74667 ** pParse.
   74668 */
   74669 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   74670   int rc = SQLITE_OK;
   74671   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   74672   if( nHeight>mxHeight ){
   74673     sqlite3ErrorMsg(pParse,
   74674        "Expression tree is too large (maximum depth %d)", mxHeight
   74675     );
   74676     rc = SQLITE_ERROR;
   74677   }
   74678   return rc;
   74679 }
   74680 
   74681 /* The following three functions, heightOfExpr(), heightOfExprList()
   74682 ** and heightOfSelect(), are used to determine the maximum height
   74683 ** of any expression tree referenced by the structure passed as the
   74684 ** first argument.
   74685 **
   74686 ** If this maximum height is greater than the current value pointed
   74687 ** to by pnHeight, the second parameter, then set *pnHeight to that
   74688 ** value.
   74689 */
   74690 static void heightOfExpr(Expr *p, int *pnHeight){
   74691   if( p ){
   74692     if( p->nHeight>*pnHeight ){
   74693       *pnHeight = p->nHeight;
   74694     }
   74695   }
   74696 }
   74697 static void heightOfExprList(ExprList *p, int *pnHeight){
   74698   if( p ){
   74699     int i;
   74700     for(i=0; i<p->nExpr; i++){
   74701       heightOfExpr(p->a[i].pExpr, pnHeight);
   74702     }
   74703   }
   74704 }
   74705 static void heightOfSelect(Select *p, int *pnHeight){
   74706   if( p ){
   74707     heightOfExpr(p->pWhere, pnHeight);
   74708     heightOfExpr(p->pHaving, pnHeight);
   74709     heightOfExpr(p->pLimit, pnHeight);
   74710     heightOfExpr(p->pOffset, pnHeight);
   74711     heightOfExprList(p->pEList, pnHeight);
   74712     heightOfExprList(p->pGroupBy, pnHeight);
   74713     heightOfExprList(p->pOrderBy, pnHeight);
   74714     heightOfSelect(p->pPrior, pnHeight);
   74715   }
   74716 }
   74717 
   74718 /*
   74719 ** Set the Expr.nHeight variable in the structure passed as an
   74720 ** argument. An expression with no children, Expr.pList or
   74721 ** Expr.pSelect member has a height of 1. Any other expression
   74722 ** has a height equal to the maximum height of any other
   74723 ** referenced Expr plus one.
   74724 */
   74725 static void exprSetHeight(Expr *p){
   74726   int nHeight = 0;
   74727   heightOfExpr(p->pLeft, &nHeight);
   74728   heightOfExpr(p->pRight, &nHeight);
   74729   if( ExprHasProperty(p, EP_xIsSelect) ){
   74730     heightOfSelect(p->x.pSelect, &nHeight);
   74731   }else{
   74732     heightOfExprList(p->x.pList, &nHeight);
   74733   }
   74734   p->nHeight = nHeight + 1;
   74735 }
   74736 
   74737 /*
   74738 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   74739 ** the height is greater than the maximum allowed expression depth,
   74740 ** leave an error in pParse.
   74741 */
   74742 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   74743   exprSetHeight(p);
   74744   sqlite3ExprCheckHeight(pParse, p->nHeight);
   74745 }
   74746 
   74747 /*
   74748 ** Return the maximum height of any expression tree referenced
   74749 ** by the select statement passed as an argument.
   74750 */
   74751 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   74752   int nHeight = 0;
   74753   heightOfSelect(p, &nHeight);
   74754   return nHeight;
   74755 }
   74756 #else
   74757   #define exprSetHeight(y)
   74758 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   74759 
   74760 /*
   74761 ** This routine is the core allocator for Expr nodes.
   74762 **
   74763 ** Construct a new expression node and return a pointer to it.  Memory
   74764 ** for this node and for the pToken argument is a single allocation
   74765 ** obtained from sqlite3DbMalloc().  The calling function
   74766 ** is responsible for making sure the node eventually gets freed.
   74767 **
   74768 ** If dequote is true, then the token (if it exists) is dequoted.
   74769 ** If dequote is false, no dequoting is performance.  The deQuote
   74770 ** parameter is ignored if pToken is NULL or if the token does not
   74771 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   74772 ** then the EP_DblQuoted flag is set on the expression node.
   74773 **
   74774 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   74775 ** can be translated into a 32-bit integer, then the token is not
   74776 ** stored in u.zToken.  Instead, the integer values is written
   74777 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   74778 ** is allocated to hold the integer text and the dequote flag is ignored.
   74779 */
   74780 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   74781   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   74782   int op,                 /* Expression opcode */
   74783   const Token *pToken,    /* Token argument.  Might be NULL */
   74784   int dequote             /* True to dequote */
   74785 ){
   74786   Expr *pNew;
   74787   int nExtra = 0;
   74788   int iValue = 0;
   74789 
   74790   if( pToken ){
   74791     if( op!=TK_INTEGER || pToken->z==0
   74792           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   74793       nExtra = pToken->n+1;
   74794       assert( iValue>=0 );
   74795     }
   74796   }
   74797   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   74798   if( pNew ){
   74799     pNew->op = (u8)op;
   74800     pNew->iAgg = -1;
   74801     if( pToken ){
   74802       if( nExtra==0 ){
   74803         pNew->flags |= EP_IntValue;
   74804         pNew->u.iValue = iValue;
   74805       }else{
   74806         int c;
   74807         pNew->u.zToken = (char*)&pNew[1];
   74808         assert( pToken->z!=0 || pToken->n==0 );
   74809         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
   74810         pNew->u.zToken[pToken->n] = 0;
   74811         if( dequote && nExtra>=3
   74812              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   74813           sqlite3Dequote(pNew->u.zToken);
   74814           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   74815         }
   74816       }
   74817     }
   74818 #if SQLITE_MAX_EXPR_DEPTH>0
   74819     pNew->nHeight = 1;
   74820 #endif
   74821   }
   74822   return pNew;
   74823 }
   74824 
   74825 /*
   74826 ** Allocate a new expression node from a zero-terminated token that has
   74827 ** already been dequoted.
   74828 */
   74829 SQLITE_PRIVATE Expr *sqlite3Expr(
   74830   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   74831   int op,                 /* Expression opcode */
   74832   const char *zToken      /* Token argument.  Might be NULL */
   74833 ){
   74834   Token x;
   74835   x.z = zToken;
   74836   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   74837   return sqlite3ExprAlloc(db, op, &x, 0);
   74838 }
   74839 
   74840 /*
   74841 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   74842 **
   74843 ** If pRoot==NULL that means that a memory allocation error has occurred.
   74844 ** In that case, delete the subtrees pLeft and pRight.
   74845 */
   74846 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   74847   sqlite3 *db,
   74848   Expr *pRoot,
   74849   Expr *pLeft,
   74850   Expr *pRight
   74851 ){
   74852   if( pRoot==0 ){
   74853     assert( db->mallocFailed );
   74854     sqlite3ExprDelete(db, pLeft);
   74855     sqlite3ExprDelete(db, pRight);
   74856   }else{
   74857     if( pRight ){
   74858       pRoot->pRight = pRight;
   74859       if( pRight->flags & EP_ExpCollate ){
   74860         pRoot->flags |= EP_ExpCollate;
   74861         pRoot->pColl = pRight->pColl;
   74862       }
   74863     }
   74864     if( pLeft ){
   74865       pRoot->pLeft = pLeft;
   74866       if( pLeft->flags & EP_ExpCollate ){
   74867         pRoot->flags |= EP_ExpCollate;
   74868         pRoot->pColl = pLeft->pColl;
   74869       }
   74870     }
   74871     exprSetHeight(pRoot);
   74872   }
   74873 }
   74874 
   74875 /*
   74876 ** Allocate a Expr node which joins as many as two subtrees.
   74877 **
   74878 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   74879 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   74880 ** free the subtrees and return NULL.
   74881 */
   74882 SQLITE_PRIVATE Expr *sqlite3PExpr(
   74883   Parse *pParse,          /* Parsing context */
   74884   int op,                 /* Expression opcode */
   74885   Expr *pLeft,            /* Left operand */
   74886   Expr *pRight,           /* Right operand */
   74887   const Token *pToken     /* Argument token */
   74888 ){
   74889   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   74890   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   74891   if( p ) {
   74892     sqlite3ExprCheckHeight(pParse, p->nHeight);
   74893   }
   74894   return p;
   74895 }
   74896 
   74897 /*
   74898 ** Join two expressions using an AND operator.  If either expression is
   74899 ** NULL, then just return the other expression.
   74900 */
   74901 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   74902   if( pLeft==0 ){
   74903     return pRight;
   74904   }else if( pRight==0 ){
   74905     return pLeft;
   74906   }else{
   74907     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   74908     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   74909     return pNew;
   74910   }
   74911 }
   74912 
   74913 /*
   74914 ** Construct a new expression node for a function with multiple
   74915 ** arguments.
   74916 */
   74917 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   74918   Expr *pNew;
   74919   sqlite3 *db = pParse->db;
   74920   assert( pToken );
   74921   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   74922   if( pNew==0 ){
   74923     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   74924     return 0;
   74925   }
   74926   pNew->x.pList = pList;
   74927   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   74928   sqlite3ExprSetHeight(pParse, pNew);
   74929   return pNew;
   74930 }
   74931 
   74932 /*
   74933 ** Assign a variable number to an expression that encodes a wildcard
   74934 ** in the original SQL statement.
   74935 **
   74936 ** Wildcards consisting of a single "?" are assigned the next sequential
   74937 ** variable number.
   74938 **
   74939 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   74940 ** sure "nnn" is not too be to avoid a denial of service attack when
   74941 ** the SQL statement comes from an external source.
   74942 **
   74943 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   74944 ** as the previous instance of the same wildcard.  Or if this is the first
   74945 ** instance of the wildcard, the next sequenial variable number is
   74946 ** assigned.
   74947 */
   74948 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   74949   sqlite3 *db = pParse->db;
   74950   const char *z;
   74951 
   74952   if( pExpr==0 ) return;
   74953   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   74954   z = pExpr->u.zToken;
   74955   assert( z!=0 );
   74956   assert( z[0]!=0 );
   74957   if( z[1]==0 ){
   74958     /* Wildcard of the form "?".  Assign the next variable number */
   74959     assert( z[0]=='?' );
   74960     pExpr->iColumn = (ynVar)(++pParse->nVar);
   74961   }else{
   74962     ynVar x = 0;
   74963     u32 n = sqlite3Strlen30(z);
   74964     if( z[0]=='?' ){
   74965       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   74966       ** use it as the variable number */
   74967       i64 i;
   74968       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
   74969       pExpr->iColumn = x = (ynVar)i;
   74970       testcase( i==0 );
   74971       testcase( i==1 );
   74972       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   74973       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   74974       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   74975         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   74976             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   74977         x = 0;
   74978       }
   74979       if( i>pParse->nVar ){
   74980         pParse->nVar = (int)i;
   74981       }
   74982     }else{
   74983       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   74984       ** number as the prior appearance of the same name, or if the name
   74985       ** has never appeared before, reuse the same variable number
   74986       */
   74987       ynVar i;
   74988       for(i=0; i<pParse->nzVar; i++){
   74989         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
   74990           pExpr->iColumn = x = (ynVar)i+1;
   74991           break;
   74992         }
   74993       }
   74994       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
   74995     }
   74996     if( x>0 ){
   74997       if( x>pParse->nzVar ){
   74998         char **a;
   74999         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
   75000         if( a==0 ) return;  /* Error reported through db->mallocFailed */
   75001         pParse->azVar = a;
   75002         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
   75003         pParse->nzVar = x;
   75004       }
   75005       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
   75006         sqlite3DbFree(db, pParse->azVar[x-1]);
   75007         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
   75008       }
   75009     }
   75010   }
   75011   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   75012     sqlite3ErrorMsg(pParse, "too many SQL variables");
   75013   }
   75014 }
   75015 
   75016 /*
   75017 ** Recursively delete an expression tree.
   75018 */
   75019 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   75020   if( p==0 ) return;
   75021   /* Sanity check: Assert that the IntValue is non-negative if it exists */
   75022   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
   75023   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   75024     sqlite3ExprDelete(db, p->pLeft);
   75025     sqlite3ExprDelete(db, p->pRight);
   75026     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
   75027       sqlite3DbFree(db, p->u.zToken);
   75028     }
   75029     if( ExprHasProperty(p, EP_xIsSelect) ){
   75030       sqlite3SelectDelete(db, p->x.pSelect);
   75031     }else{
   75032       sqlite3ExprListDelete(db, p->x.pList);
   75033     }
   75034   }
   75035   if( !ExprHasProperty(p, EP_Static) ){
   75036     sqlite3DbFree(db, p);
   75037   }
   75038 }
   75039 
   75040 /*
   75041 ** Return the number of bytes allocated for the expression structure
   75042 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   75043 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   75044 */
   75045 static int exprStructSize(Expr *p){
   75046   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   75047   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   75048   return EXPR_FULLSIZE;
   75049 }
   75050 
   75051 /*
   75052 ** The dupedExpr*Size() routines each return the number of bytes required
   75053 ** to store a copy of an expression or expression tree.  They differ in
   75054 ** how much of the tree is measured.
   75055 **
   75056 **     dupedExprStructSize()     Size of only the Expr structure
   75057 **     dupedExprNodeSize()       Size of Expr + space for token
   75058 **     dupedExprSize()           Expr + token + subtree components
   75059 **
   75060 ***************************************************************************
   75061 **
   75062 ** The dupedExprStructSize() function returns two values OR-ed together:
   75063 ** (1) the space required for a copy of the Expr structure only and
   75064 ** (2) the EP_xxx flags that indicate what the structure size should be.
   75065 ** The return values is always one of:
   75066 **
   75067 **      EXPR_FULLSIZE
   75068 **      EXPR_REDUCEDSIZE   | EP_Reduced
   75069 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   75070 **
   75071 ** The size of the structure can be found by masking the return value
   75072 ** of this routine with 0xfff.  The flags can be found by masking the
   75073 ** return value with EP_Reduced|EP_TokenOnly.
   75074 **
   75075 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   75076 ** (unreduced) Expr objects as they or originally constructed by the parser.
   75077 ** During expression analysis, extra information is computed and moved into
   75078 ** later parts of teh Expr object and that extra information might get chopped
   75079 ** off if the expression is reduced.  Note also that it does not work to
   75080 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   75081 ** to reduce a pristine expression tree from the parser.  The implementation
   75082 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   75083 ** to enforce this constraint.
   75084 */
   75085 static int dupedExprStructSize(Expr *p, int flags){
   75086   int nSize;
   75087   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   75088   if( 0==(flags&EXPRDUP_REDUCE) ){
   75089     nSize = EXPR_FULLSIZE;
   75090   }else{
   75091     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   75092     assert( !ExprHasProperty(p, EP_FromJoin) );
   75093     assert( (p->flags2 & EP2_MallocedToken)==0 );
   75094     assert( (p->flags2 & EP2_Irreducible)==0 );
   75095     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
   75096       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   75097     }else{
   75098       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   75099     }
   75100   }
   75101   return nSize;
   75102 }
   75103 
   75104 /*
   75105 ** This function returns the space in bytes required to store the copy
   75106 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   75107 ** string is defined.)
   75108 */
   75109 static int dupedExprNodeSize(Expr *p, int flags){
   75110   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   75111   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   75112     nByte += sqlite3Strlen30(p->u.zToken)+1;
   75113   }
   75114   return ROUND8(nByte);
   75115 }
   75116 
   75117 /*
   75118 ** Return the number of bytes required to create a duplicate of the
   75119 ** expression passed as the first argument. The second argument is a
   75120 ** mask containing EXPRDUP_XXX flags.
   75121 **
   75122 ** The value returned includes space to create a copy of the Expr struct
   75123 ** itself and the buffer referred to by Expr.u.zToken, if any.
   75124 **
   75125 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   75126 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   75127 ** and Expr.pRight variables (but not for any structures pointed to or
   75128 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   75129 */
   75130 static int dupedExprSize(Expr *p, int flags){
   75131   int nByte = 0;
   75132   if( p ){
   75133     nByte = dupedExprNodeSize(p, flags);
   75134     if( flags&EXPRDUP_REDUCE ){
   75135       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   75136     }
   75137   }
   75138   return nByte;
   75139 }
   75140 
   75141 /*
   75142 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   75143 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   75144 ** to store the copy of expression p, the copies of p->u.zToken
   75145 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   75146 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   75147 ** portion of the buffer copied into by this function.
   75148 */
   75149 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   75150   Expr *pNew = 0;                      /* Value to return */
   75151   if( p ){
   75152     const int isReduced = (flags&EXPRDUP_REDUCE);
   75153     u8 *zAlloc;
   75154     u32 staticFlag = 0;
   75155 
   75156     assert( pzBuffer==0 || isReduced );
   75157 
   75158     /* Figure out where to write the new Expr structure. */
   75159     if( pzBuffer ){
   75160       zAlloc = *pzBuffer;
   75161       staticFlag = EP_Static;
   75162     }else{
   75163       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   75164     }
   75165     pNew = (Expr *)zAlloc;
   75166 
   75167     if( pNew ){
   75168       /* Set nNewSize to the size allocated for the structure pointed to
   75169       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   75170       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   75171       ** by the copy of the p->u.zToken string (if any).
   75172       */
   75173       const unsigned nStructSize = dupedExprStructSize(p, flags);
   75174       const int nNewSize = nStructSize & 0xfff;
   75175       int nToken;
   75176       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   75177         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   75178       }else{
   75179         nToken = 0;
   75180       }
   75181       if( isReduced ){
   75182         assert( ExprHasProperty(p, EP_Reduced)==0 );
   75183         memcpy(zAlloc, p, nNewSize);
   75184       }else{
   75185         int nSize = exprStructSize(p);
   75186         memcpy(zAlloc, p, nSize);
   75187         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   75188       }
   75189 
   75190       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   75191       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
   75192       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   75193       pNew->flags |= staticFlag;
   75194 
   75195       /* Copy the p->u.zToken string, if any. */
   75196       if( nToken ){
   75197         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   75198         memcpy(zToken, p->u.zToken, nToken);
   75199       }
   75200 
   75201       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   75202         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   75203         if( ExprHasProperty(p, EP_xIsSelect) ){
   75204           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   75205         }else{
   75206           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   75207         }
   75208       }
   75209 
   75210       /* Fill in pNew->pLeft and pNew->pRight. */
   75211       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   75212         zAlloc += dupedExprNodeSize(p, flags);
   75213         if( ExprHasProperty(pNew, EP_Reduced) ){
   75214           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   75215           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   75216         }
   75217         if( pzBuffer ){
   75218           *pzBuffer = zAlloc;
   75219         }
   75220       }else{
   75221         pNew->flags2 = 0;
   75222         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   75223           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   75224           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   75225         }
   75226       }
   75227 
   75228     }
   75229   }
   75230   return pNew;
   75231 }
   75232 
   75233 /*
   75234 ** The following group of routines make deep copies of expressions,
   75235 ** expression lists, ID lists, and select statements.  The copies can
   75236 ** be deleted (by being passed to their respective ...Delete() routines)
   75237 ** without effecting the originals.
   75238 **
   75239 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   75240 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   75241 ** by subsequent calls to sqlite*ListAppend() routines.
   75242 **
   75243 ** Any tables that the SrcList might point to are not duplicated.
   75244 **
   75245 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   75246 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   75247 ** truncated version of the usual Expr structure that will be stored as
   75248 ** part of the in-memory representation of the database schema.
   75249 */
   75250 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   75251   return exprDup(db, p, flags, 0);
   75252 }
   75253 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   75254   ExprList *pNew;
   75255   struct ExprList_item *pItem, *pOldItem;
   75256   int i;
   75257   if( p==0 ) return 0;
   75258   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   75259   if( pNew==0 ) return 0;
   75260   pNew->iECursor = 0;
   75261   pNew->nExpr = i = p->nExpr;
   75262   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
   75263   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
   75264   if( pItem==0 ){
   75265     sqlite3DbFree(db, pNew);
   75266     return 0;
   75267   }
   75268   pOldItem = p->a;
   75269   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   75270     Expr *pOldExpr = pOldItem->pExpr;
   75271     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   75272     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75273     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   75274     pItem->sortOrder = pOldItem->sortOrder;
   75275     pItem->done = 0;
   75276     pItem->iOrderByCol = pOldItem->iOrderByCol;
   75277     pItem->iAlias = pOldItem->iAlias;
   75278   }
   75279   return pNew;
   75280 }
   75281 
   75282 /*
   75283 ** If cursors, triggers, views and subqueries are all omitted from
   75284 ** the build, then none of the following routines, except for
   75285 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   75286 ** called with a NULL argument.
   75287 */
   75288 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   75289  || !defined(SQLITE_OMIT_SUBQUERY)
   75290 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   75291   SrcList *pNew;
   75292   int i;
   75293   int nByte;
   75294   if( p==0 ) return 0;
   75295   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   75296   pNew = sqlite3DbMallocRaw(db, nByte );
   75297   if( pNew==0 ) return 0;
   75298   pNew->nSrc = pNew->nAlloc = p->nSrc;
   75299   for(i=0; i<p->nSrc; i++){
   75300     struct SrcList_item *pNewItem = &pNew->a[i];
   75301     struct SrcList_item *pOldItem = &p->a[i];
   75302     Table *pTab;
   75303     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   75304     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75305     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   75306     pNewItem->jointype = pOldItem->jointype;
   75307     pNewItem->iCursor = pOldItem->iCursor;
   75308     pNewItem->addrFillSub = pOldItem->addrFillSub;
   75309     pNewItem->regReturn = pOldItem->regReturn;
   75310     pNewItem->isCorrelated = pOldItem->isCorrelated;
   75311     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   75312     pNewItem->notIndexed = pOldItem->notIndexed;
   75313     pNewItem->pIndex = pOldItem->pIndex;
   75314     pTab = pNewItem->pTab = pOldItem->pTab;
   75315     if( pTab ){
   75316       pTab->nRef++;
   75317     }
   75318     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   75319     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   75320     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   75321     pNewItem->colUsed = pOldItem->colUsed;
   75322   }
   75323   return pNew;
   75324 }
   75325 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   75326   IdList *pNew;
   75327   int i;
   75328   if( p==0 ) return 0;
   75329   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   75330   if( pNew==0 ) return 0;
   75331   pNew->nId = p->nId;
   75332   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   75333   if( pNew->a==0 ){
   75334     sqlite3DbFree(db, pNew);
   75335     return 0;
   75336   }
   75337   /* Note that because the size of the allocation for p->a[] is not
   75338   ** necessarily a power of two, sqlite3IdListAppend() may not be called
   75339   ** on the duplicate created by this function. */
   75340   for(i=0; i<p->nId; i++){
   75341     struct IdList_item *pNewItem = &pNew->a[i];
   75342     struct IdList_item *pOldItem = &p->a[i];
   75343     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   75344     pNewItem->idx = pOldItem->idx;
   75345   }
   75346   return pNew;
   75347 }
   75348 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   75349   Select *pNew, *pPrior;
   75350   if( p==0 ) return 0;
   75351   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   75352   if( pNew==0 ) return 0;
   75353   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   75354   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   75355   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   75356   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   75357   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   75358   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   75359   pNew->op = p->op;
   75360   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   75361   if( pPrior ) pPrior->pNext = pNew;
   75362   pNew->pNext = 0;
   75363   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   75364   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   75365   pNew->iLimit = 0;
   75366   pNew->iOffset = 0;
   75367   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   75368   pNew->pRightmost = 0;
   75369   pNew->addrOpenEphm[0] = -1;
   75370   pNew->addrOpenEphm[1] = -1;
   75371   pNew->addrOpenEphm[2] = -1;
   75372   return pNew;
   75373 }
   75374 #else
   75375 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   75376   assert( p==0 );
   75377   return 0;
   75378 }
   75379 #endif
   75380 
   75381 
   75382 /*
   75383 ** Add a new element to the end of an expression list.  If pList is
   75384 ** initially NULL, then create a new expression list.
   75385 **
   75386 ** If a memory allocation error occurs, the entire list is freed and
   75387 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   75388 ** that the new entry was successfully appended.
   75389 */
   75390 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   75391   Parse *pParse,          /* Parsing context */
   75392   ExprList *pList,        /* List to which to append. Might be NULL */
   75393   Expr *pExpr             /* Expression to be appended. Might be NULL */
   75394 ){
   75395   sqlite3 *db = pParse->db;
   75396   if( pList==0 ){
   75397     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   75398     if( pList==0 ){
   75399       goto no_mem;
   75400     }
   75401     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
   75402     if( pList->a==0 ) goto no_mem;
   75403   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
   75404     struct ExprList_item *a;
   75405     assert( pList->nExpr>0 );
   75406     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
   75407     if( a==0 ){
   75408       goto no_mem;
   75409     }
   75410     pList->a = a;
   75411   }
   75412   assert( pList->a!=0 );
   75413   if( 1 ){
   75414     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   75415     memset(pItem, 0, sizeof(*pItem));
   75416     pItem->pExpr = pExpr;
   75417   }
   75418   return pList;
   75419 
   75420 no_mem:
   75421   /* Avoid leaking memory if malloc has failed. */
   75422   sqlite3ExprDelete(db, pExpr);
   75423   sqlite3ExprListDelete(db, pList);
   75424   return 0;
   75425 }
   75426 
   75427 /*
   75428 ** Set the ExprList.a[].zName element of the most recently added item
   75429 ** on the expression list.
   75430 **
   75431 ** pList might be NULL following an OOM error.  But pName should never be
   75432 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   75433 ** is set.
   75434 */
   75435 SQLITE_PRIVATE void sqlite3ExprListSetName(
   75436   Parse *pParse,          /* Parsing context */
   75437   ExprList *pList,        /* List to which to add the span. */
   75438   Token *pName,           /* Name to be added */
   75439   int dequote             /* True to cause the name to be dequoted */
   75440 ){
   75441   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   75442   if( pList ){
   75443     struct ExprList_item *pItem;
   75444     assert( pList->nExpr>0 );
   75445     pItem = &pList->a[pList->nExpr-1];
   75446     assert( pItem->zName==0 );
   75447     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   75448     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   75449   }
   75450 }
   75451 
   75452 /*
   75453 ** Set the ExprList.a[].zSpan element of the most recently added item
   75454 ** on the expression list.
   75455 **
   75456 ** pList might be NULL following an OOM error.  But pSpan should never be
   75457 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   75458 ** is set.
   75459 */
   75460 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   75461   Parse *pParse,          /* Parsing context */
   75462   ExprList *pList,        /* List to which to add the span. */
   75463   ExprSpan *pSpan         /* The span to be added */
   75464 ){
   75465   sqlite3 *db = pParse->db;
   75466   assert( pList!=0 || db->mallocFailed!=0 );
   75467   if( pList ){
   75468     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   75469     assert( pList->nExpr>0 );
   75470     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   75471     sqlite3DbFree(db, pItem->zSpan);
   75472     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   75473                                     (int)(pSpan->zEnd - pSpan->zStart));
   75474   }
   75475 }
   75476 
   75477 /*
   75478 ** If the expression list pEList contains more than iLimit elements,
   75479 ** leave an error message in pParse.
   75480 */
   75481 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   75482   Parse *pParse,
   75483   ExprList *pEList,
   75484   const char *zObject
   75485 ){
   75486   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   75487   testcase( pEList && pEList->nExpr==mx );
   75488   testcase( pEList && pEList->nExpr==mx+1 );
   75489   if( pEList && pEList->nExpr>mx ){
   75490     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   75491   }
   75492 }
   75493 
   75494 /*
   75495 ** Delete an entire expression list.
   75496 */
   75497 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   75498   int i;
   75499   struct ExprList_item *pItem;
   75500   if( pList==0 ) return;
   75501   assert( pList->a!=0 || pList->nExpr==0 );
   75502   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   75503     sqlite3ExprDelete(db, pItem->pExpr);
   75504     sqlite3DbFree(db, pItem->zName);
   75505     sqlite3DbFree(db, pItem->zSpan);
   75506   }
   75507   sqlite3DbFree(db, pList->a);
   75508   sqlite3DbFree(db, pList);
   75509 }
   75510 
   75511 /*
   75512 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   75513 ** to an integer.  These routines are checking an expression to see
   75514 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   75515 ** not constant.
   75516 **
   75517 ** These callback routines are used to implement the following:
   75518 **
   75519 **     sqlite3ExprIsConstant()
   75520 **     sqlite3ExprIsConstantNotJoin()
   75521 **     sqlite3ExprIsConstantOrFunction()
   75522 **
   75523 */
   75524 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   75525 
   75526   /* If pWalker->u.i is 3 then any term of the expression that comes from
   75527   ** the ON or USING clauses of a join disqualifies the expression
   75528   ** from being considered constant. */
   75529   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
   75530     pWalker->u.i = 0;
   75531     return WRC_Abort;
   75532   }
   75533 
   75534   switch( pExpr->op ){
   75535     /* Consider functions to be constant if all their arguments are constant
   75536     ** and pWalker->u.i==2 */
   75537     case TK_FUNCTION:
   75538       if( pWalker->u.i==2 ) return 0;
   75539       /* Fall through */
   75540     case TK_ID:
   75541     case TK_COLUMN:
   75542     case TK_AGG_FUNCTION:
   75543     case TK_AGG_COLUMN:
   75544       testcase( pExpr->op==TK_ID );
   75545       testcase( pExpr->op==TK_COLUMN );
   75546       testcase( pExpr->op==TK_AGG_FUNCTION );
   75547       testcase( pExpr->op==TK_AGG_COLUMN );
   75548       pWalker->u.i = 0;
   75549       return WRC_Abort;
   75550     default:
   75551       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   75552       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   75553       return WRC_Continue;
   75554   }
   75555 }
   75556 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   75557   UNUSED_PARAMETER(NotUsed);
   75558   pWalker->u.i = 0;
   75559   return WRC_Abort;
   75560 }
   75561 static int exprIsConst(Expr *p, int initFlag){
   75562   Walker w;
   75563   w.u.i = initFlag;
   75564   w.xExprCallback = exprNodeIsConstant;
   75565   w.xSelectCallback = selectNodeIsConstant;
   75566   sqlite3WalkExpr(&w, p);
   75567   return w.u.i;
   75568 }
   75569 
   75570 /*
   75571 ** Walk an expression tree.  Return 1 if the expression is constant
   75572 ** and 0 if it involves variables or function calls.
   75573 **
   75574 ** For the purposes of this function, a double-quoted string (ex: "abc")
   75575 ** is considered a variable but a single-quoted string (ex: 'abc') is
   75576 ** a constant.
   75577 */
   75578 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   75579   return exprIsConst(p, 1);
   75580 }
   75581 
   75582 /*
   75583 ** Walk an expression tree.  Return 1 if the expression is constant
   75584 ** that does no originate from the ON or USING clauses of a join.
   75585 ** Return 0 if it involves variables or function calls or terms from
   75586 ** an ON or USING clause.
   75587 */
   75588 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   75589   return exprIsConst(p, 3);
   75590 }
   75591 
   75592 /*
   75593 ** Walk an expression tree.  Return 1 if the expression is constant
   75594 ** or a function call with constant arguments.  Return and 0 if there
   75595 ** are any variables.
   75596 **
   75597 ** For the purposes of this function, a double-quoted string (ex: "abc")
   75598 ** is considered a variable but a single-quoted string (ex: 'abc') is
   75599 ** a constant.
   75600 */
   75601 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   75602   return exprIsConst(p, 2);
   75603 }
   75604 
   75605 /*
   75606 ** If the expression p codes a constant integer that is small enough
   75607 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   75608 ** in *pValue.  If the expression is not an integer or if it is too big
   75609 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   75610 */
   75611 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   75612   int rc = 0;
   75613 
   75614   /* If an expression is an integer literal that fits in a signed 32-bit
   75615   ** integer, then the EP_IntValue flag will have already been set */
   75616   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
   75617            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
   75618 
   75619   if( p->flags & EP_IntValue ){
   75620     *pValue = p->u.iValue;
   75621     return 1;
   75622   }
   75623   switch( p->op ){
   75624     case TK_UPLUS: {
   75625       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   75626       break;
   75627     }
   75628     case TK_UMINUS: {
   75629       int v;
   75630       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   75631         *pValue = -v;
   75632         rc = 1;
   75633       }
   75634       break;
   75635     }
   75636     default: break;
   75637   }
   75638   return rc;
   75639 }
   75640 
   75641 /*
   75642 ** Return FALSE if there is no chance that the expression can be NULL.
   75643 **
   75644 ** If the expression might be NULL or if the expression is too complex
   75645 ** to tell return TRUE.
   75646 **
   75647 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   75648 ** when we know that a value cannot be NULL.  Hence, a false positive
   75649 ** (returning TRUE when in fact the expression can never be NULL) might
   75650 ** be a small performance hit but is otherwise harmless.  On the other
   75651 ** hand, a false negative (returning FALSE when the result could be NULL)
   75652 ** will likely result in an incorrect answer.  So when in doubt, return
   75653 ** TRUE.
   75654 */
   75655 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   75656   u8 op;
   75657   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   75658   op = p->op;
   75659   if( op==TK_REGISTER ) op = p->op2;
   75660   switch( op ){
   75661     case TK_INTEGER:
   75662     case TK_STRING:
   75663     case TK_FLOAT:
   75664     case TK_BLOB:
   75665       return 0;
   75666     default:
   75667       return 1;
   75668   }
   75669 }
   75670 
   75671 /*
   75672 ** Generate an OP_IsNull instruction that tests register iReg and jumps
   75673 ** to location iDest if the value in iReg is NULL.  The value in iReg
   75674 ** was computed by pExpr.  If we can look at pExpr at compile-time and
   75675 ** determine that it can never generate a NULL, then the OP_IsNull operation
   75676 ** can be omitted.
   75677 */
   75678 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
   75679   Vdbe *v,            /* The VDBE under construction */
   75680   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
   75681   int iReg,           /* Test the value in this register for NULL */
   75682   int iDest           /* Jump here if the value is null */
   75683 ){
   75684   if( sqlite3ExprCanBeNull(pExpr) ){
   75685     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
   75686   }
   75687 }
   75688 
   75689 /*
   75690 ** Return TRUE if the given expression is a constant which would be
   75691 ** unchanged by OP_Affinity with the affinity given in the second
   75692 ** argument.
   75693 **
   75694 ** This routine is used to determine if the OP_Affinity operation
   75695 ** can be omitted.  When in doubt return FALSE.  A false negative
   75696 ** is harmless.  A false positive, however, can result in the wrong
   75697 ** answer.
   75698 */
   75699 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   75700   u8 op;
   75701   if( aff==SQLITE_AFF_NONE ) return 1;
   75702   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   75703   op = p->op;
   75704   if( op==TK_REGISTER ) op = p->op2;
   75705   switch( op ){
   75706     case TK_INTEGER: {
   75707       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   75708     }
   75709     case TK_FLOAT: {
   75710       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   75711     }
   75712     case TK_STRING: {
   75713       return aff==SQLITE_AFF_TEXT;
   75714     }
   75715     case TK_BLOB: {
   75716       return 1;
   75717     }
   75718     case TK_COLUMN: {
   75719       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   75720       return p->iColumn<0
   75721           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   75722     }
   75723     default: {
   75724       return 0;
   75725     }
   75726   }
   75727 }
   75728 
   75729 /*
   75730 ** Return TRUE if the given string is a row-id column name.
   75731 */
   75732 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   75733   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   75734   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   75735   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   75736   return 0;
   75737 }
   75738 
   75739 /*
   75740 ** Return true if we are able to the IN operator optimization on a
   75741 ** query of the form
   75742 **
   75743 **       x IN (SELECT ...)
   75744 **
   75745 ** Where the SELECT... clause is as specified by the parameter to this
   75746 ** routine.
   75747 **
   75748 ** The Select object passed in has already been preprocessed and no
   75749 ** errors have been found.
   75750 */
   75751 #ifndef SQLITE_OMIT_SUBQUERY
   75752 static int isCandidateForInOpt(Select *p){
   75753   SrcList *pSrc;
   75754   ExprList *pEList;
   75755   Table *pTab;
   75756   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   75757   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   75758   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   75759     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   75760     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   75761     return 0; /* No DISTINCT keyword and no aggregate functions */
   75762   }
   75763   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   75764   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   75765   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   75766   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   75767   pSrc = p->pSrc;
   75768   assert( pSrc!=0 );
   75769   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   75770   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   75771   pTab = pSrc->a[0].pTab;
   75772   if( NEVER(pTab==0) ) return 0;
   75773   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   75774   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   75775   pEList = p->pEList;
   75776   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   75777   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   75778   return 1;
   75779 }
   75780 #endif /* SQLITE_OMIT_SUBQUERY */
   75781 
   75782 /*
   75783 ** Code an OP_Once instruction and allocate space for its flag. Return the
   75784 ** address of the new instruction.
   75785 */
   75786 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
   75787   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   75788   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
   75789 }
   75790 
   75791 /*
   75792 ** This function is used by the implementation of the IN (...) operator.
   75793 ** It's job is to find or create a b-tree structure that may be used
   75794 ** either to test for membership of the (...) set or to iterate through
   75795 ** its members, skipping duplicates.
   75796 **
   75797 ** The index of the cursor opened on the b-tree (database table, database index
   75798 ** or ephermal table) is stored in pX->iTable before this function returns.
   75799 ** The returned value of this function indicates the b-tree type, as follows:
   75800 **
   75801 **   IN_INDEX_ROWID - The cursor was opened on a database table.
   75802 **   IN_INDEX_INDEX - The cursor was opened on a database index.
   75803 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
   75804 **                    populated epheremal table.
   75805 **
   75806 ** An existing b-tree may only be used if the SELECT is of the simple
   75807 ** form:
   75808 **
   75809 **     SELECT <column> FROM <table>
   75810 **
   75811 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
   75812 ** through the set members, skipping any duplicates. In this case an
   75813 ** epheremal table must be used unless the selected <column> is guaranteed
   75814 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   75815 ** has a UNIQUE constraint or UNIQUE index.
   75816 **
   75817 ** If the prNotFound parameter is not 0, then the b-tree will be used
   75818 ** for fast set membership tests. In this case an epheremal table must
   75819 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   75820 ** be found with <column> as its left-most column.
   75821 **
   75822 ** When the b-tree is being used for membership tests, the calling function
   75823 ** needs to know whether or not the structure contains an SQL NULL
   75824 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
   75825 ** If there is any chance that the (...) might contain a NULL value at
   75826 ** runtime, then a register is allocated and the register number written
   75827 ** to *prNotFound. If there is no chance that the (...) contains a
   75828 ** NULL value, then *prNotFound is left unchanged.
   75829 **
   75830 ** If a register is allocated and its location stored in *prNotFound, then
   75831 ** its initial value is NULL.  If the (...) does not remain constant
   75832 ** for the duration of the query (i.e. the SELECT within the (...)
   75833 ** is a correlated subquery) then the value of the allocated register is
   75834 ** reset to NULL each time the subquery is rerun. This allows the
   75835 ** caller to use vdbe code equivalent to the following:
   75836 **
   75837 **   if( register==NULL ){
   75838 **     has_null = <test if data structure contains null>
   75839 **     register = 1
   75840 **   }
   75841 **
   75842 ** in order to avoid running the <test if data structure contains null>
   75843 ** test more often than is necessary.
   75844 */
   75845 #ifndef SQLITE_OMIT_SUBQUERY
   75846 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
   75847   Select *p;                            /* SELECT to the right of IN operator */
   75848   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   75849   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   75850   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
   75851   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
   75852 
   75853   assert( pX->op==TK_IN );
   75854 
   75855   /* Check to see if an existing table or index can be used to
   75856   ** satisfy the query.  This is preferable to generating a new
   75857   ** ephemeral table.
   75858   */
   75859   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   75860   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   75861     sqlite3 *db = pParse->db;              /* Database connection */
   75862     Table *pTab;                           /* Table <table>. */
   75863     Expr *pExpr;                           /* Expression <column> */
   75864     int iCol;                              /* Index of column <column> */
   75865     int iDb;                               /* Database idx for pTab */
   75866 
   75867     assert( p );                        /* Because of isCandidateForInOpt(p) */
   75868     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
   75869     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
   75870     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
   75871     pTab = p->pSrc->a[0].pTab;
   75872     pExpr = p->pEList->a[0].pExpr;
   75873     iCol = pExpr->iColumn;
   75874 
   75875     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
   75876     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   75877     sqlite3CodeVerifySchema(pParse, iDb);
   75878     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   75879 
   75880     /* This function is only called from two places. In both cases the vdbe
   75881     ** has already been allocated. So assume sqlite3GetVdbe() is always
   75882     ** successful here.
   75883     */
   75884     assert(v);
   75885     if( iCol<0 ){
   75886       int iAddr;
   75887 
   75888       iAddr = sqlite3CodeOnce(pParse);
   75889 
   75890       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   75891       eType = IN_INDEX_ROWID;
   75892 
   75893       sqlite3VdbeJumpHere(v, iAddr);
   75894     }else{
   75895       Index *pIdx;                         /* Iterator variable */
   75896 
   75897       /* The collation sequence used by the comparison. If an index is to
   75898       ** be used in place of a temp-table, it must be ordered according
   75899       ** to this collation sequence.  */
   75900       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   75901 
   75902       /* Check that the affinity that will be used to perform the
   75903       ** comparison is the same as the affinity of the column. If
   75904       ** it is not, it is not possible to use any index.
   75905       */
   75906       char aff = comparisonAffinity(pX);
   75907       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
   75908 
   75909       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   75910         if( (pIdx->aiColumn[0]==iCol)
   75911          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   75912          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
   75913         ){
   75914           int iAddr;
   75915           char *pKey;
   75916 
   75917           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
   75918           iAddr = sqlite3CodeOnce(pParse);
   75919 
   75920           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
   75921                                pKey,P4_KEYINFO_HANDOFF);
   75922           VdbeComment((v, "%s", pIdx->zName));
   75923           eType = IN_INDEX_INDEX;
   75924 
   75925           sqlite3VdbeJumpHere(v, iAddr);
   75926           if( prNotFound && !pTab->aCol[iCol].notNull ){
   75927             *prNotFound = ++pParse->nMem;
   75928             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
   75929           }
   75930         }
   75931       }
   75932     }
   75933   }
   75934 
   75935   if( eType==0 ){
   75936     /* Could not found an existing table or index to use as the RHS b-tree.
   75937     ** We will have to generate an ephemeral table to do the job.
   75938     */
   75939     double savedNQueryLoop = pParse->nQueryLoop;
   75940     int rMayHaveNull = 0;
   75941     eType = IN_INDEX_EPH;
   75942     if( prNotFound ){
   75943       *prNotFound = rMayHaveNull = ++pParse->nMem;
   75944       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
   75945     }else{
   75946       testcase( pParse->nQueryLoop>(double)1 );
   75947       pParse->nQueryLoop = (double)1;
   75948       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
   75949         eType = IN_INDEX_ROWID;
   75950       }
   75951     }
   75952     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   75953     pParse->nQueryLoop = savedNQueryLoop;
   75954   }else{
   75955     pX->iTable = iTab;
   75956   }
   75957   return eType;
   75958 }
   75959 #endif
   75960 
   75961 /*
   75962 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   75963 ** or IN operators.  Examples:
   75964 **
   75965 **     (SELECT a FROM b)          -- subquery
   75966 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   75967 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   75968 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   75969 **
   75970 ** The pExpr parameter describes the expression that contains the IN
   75971 ** operator or subquery.
   75972 **
   75973 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   75974 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   75975 ** to some integer key column of a table B-Tree. In this case, use an
   75976 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   75977 ** (slower) variable length keys B-Tree.
   75978 **
   75979 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   75980 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   75981 ** Furthermore, the IN is in a WHERE clause and that we really want
   75982 ** to iterate over the RHS of the IN operator in order to quickly locate
   75983 ** all corresponding LHS elements.  All this routine does is initialize
   75984 ** the register given by rMayHaveNull to NULL.  Calling routines will take
   75985 ** care of changing this register value to non-NULL if the RHS is NULL-free.
   75986 **
   75987 ** If rMayHaveNull is zero, that means that the subquery is being used
   75988 ** for membership testing only.  There is no need to initialize any
   75989 ** registers to indicate the presense or absence of NULLs on the RHS.
   75990 **
   75991 ** For a SELECT or EXISTS operator, return the register that holds the
   75992 ** result.  For IN operators or if an error occurs, the return value is 0.
   75993 */
   75994 #ifndef SQLITE_OMIT_SUBQUERY
   75995 SQLITE_PRIVATE int sqlite3CodeSubselect(
   75996   Parse *pParse,          /* Parsing context */
   75997   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   75998   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
   75999   int isRowid             /* If true, LHS of IN operator is a rowid */
   76000 ){
   76001   int testAddr = -1;                      /* One-time test address */
   76002   int rReg = 0;                           /* Register storing resulting */
   76003   Vdbe *v = sqlite3GetVdbe(pParse);
   76004   if( NEVER(v==0) ) return 0;
   76005   sqlite3ExprCachePush(pParse);
   76006 
   76007   /* This code must be run in its entirety every time it is encountered
   76008   ** if any of the following is true:
   76009   **
   76010   **    *  The right-hand side is a correlated subquery
   76011   **    *  The right-hand side is an expression list containing variables
   76012   **    *  We are inside a trigger
   76013   **
   76014   ** If all of the above are false, then we can run this code just once
   76015   ** save the results, and reuse the same result on subsequent invocations.
   76016   */
   76017   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
   76018     testAddr = sqlite3CodeOnce(pParse);
   76019   }
   76020 
   76021 #ifndef SQLITE_OMIT_EXPLAIN
   76022   if( pParse->explain==2 ){
   76023     char *zMsg = sqlite3MPrintf(
   76024         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
   76025         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
   76026     );
   76027     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   76028   }
   76029 #endif
   76030 
   76031   switch( pExpr->op ){
   76032     case TK_IN: {
   76033       char affinity;              /* Affinity of the LHS of the IN */
   76034       KeyInfo keyInfo;            /* Keyinfo for the generated table */
   76035       int addr;                   /* Address of OP_OpenEphemeral instruction */
   76036       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   76037 
   76038       if( rMayHaveNull ){
   76039         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
   76040       }
   76041 
   76042       affinity = sqlite3ExprAffinity(pLeft);
   76043 
   76044       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   76045       ** expression it is handled the same way.  An ephemeral table is
   76046       ** filled with single-field index keys representing the results
   76047       ** from the SELECT or the <exprlist>.
   76048       **
   76049       ** If the 'x' expression is a column value, or the SELECT...
   76050       ** statement returns a column value, then the affinity of that
   76051       ** column is used to build the index keys. If both 'x' and the
   76052       ** SELECT... statement are columns, then numeric affinity is used
   76053       ** if either column has NUMERIC or INTEGER affinity. If neither
   76054       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   76055       ** is used.
   76056       */
   76057       pExpr->iTable = pParse->nTab++;
   76058       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   76059       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   76060       memset(&keyInfo, 0, sizeof(keyInfo));
   76061       keyInfo.nField = 1;
   76062 
   76063       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   76064         /* Case 1:     expr IN (SELECT ...)
   76065         **
   76066         ** Generate code to write the results of the select into the temporary
   76067         ** table allocated and opened above.
   76068         */
   76069         SelectDest dest;
   76070         ExprList *pEList;
   76071 
   76072         assert( !isRowid );
   76073         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   76074         dest.affinity = (u8)affinity;
   76075         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   76076         pExpr->x.pSelect->iLimit = 0;
   76077         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
   76078           return 0;
   76079         }
   76080         pEList = pExpr->x.pSelect->pEList;
   76081         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
   76082           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   76083               pEList->a[0].pExpr);
   76084         }
   76085       }else if( ALWAYS(pExpr->x.pList!=0) ){
   76086         /* Case 2:     expr IN (exprlist)
   76087         **
   76088         ** For each expression, build an index key from the evaluation and
   76089         ** store it in the temporary table. If <expr> is a column, then use
   76090         ** that columns affinity when building index keys. If <expr> is not
   76091         ** a column, use numeric affinity.
   76092         */
   76093         int i;
   76094         ExprList *pList = pExpr->x.pList;
   76095         struct ExprList_item *pItem;
   76096         int r1, r2, r3;
   76097 
   76098         if( !affinity ){
   76099           affinity = SQLITE_AFF_NONE;
   76100         }
   76101         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   76102 
   76103         /* Loop through each expression in <exprlist>. */
   76104         r1 = sqlite3GetTempReg(pParse);
   76105         r2 = sqlite3GetTempReg(pParse);
   76106         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   76107         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   76108           Expr *pE2 = pItem->pExpr;
   76109           int iValToIns;
   76110 
   76111           /* If the expression is not constant then we will need to
   76112           ** disable the test that was generated above that makes sure
   76113           ** this code only executes once.  Because for a non-constant
   76114           ** expression we need to rerun this code each time.
   76115           */
   76116           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
   76117             sqlite3VdbeChangeToNoop(v, testAddr);
   76118             testAddr = -1;
   76119           }
   76120 
   76121           /* Evaluate the expression and insert it into the temp table */
   76122           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   76123             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   76124           }else{
   76125             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   76126             if( isRowid ){
   76127               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   76128                                 sqlite3VdbeCurrentAddr(v)+2);
   76129               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   76130             }else{
   76131               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   76132               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   76133               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   76134             }
   76135           }
   76136         }
   76137         sqlite3ReleaseTempReg(pParse, r1);
   76138         sqlite3ReleaseTempReg(pParse, r2);
   76139       }
   76140       if( !isRowid ){
   76141         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
   76142       }
   76143       break;
   76144     }
   76145 
   76146     case TK_EXISTS:
   76147     case TK_SELECT:
   76148     default: {
   76149       /* If this has to be a scalar SELECT.  Generate code to put the
   76150       ** value of this select in a memory cell and record the number
   76151       ** of the memory cell in iColumn.  If this is an EXISTS, write
   76152       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   76153       ** and record that memory cell in iColumn.
   76154       */
   76155       Select *pSel;                         /* SELECT statement to encode */
   76156       SelectDest dest;                      /* How to deal with SELECt result */
   76157 
   76158       testcase( pExpr->op==TK_EXISTS );
   76159       testcase( pExpr->op==TK_SELECT );
   76160       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   76161 
   76162       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   76163       pSel = pExpr->x.pSelect;
   76164       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   76165       if( pExpr->op==TK_SELECT ){
   76166         dest.eDest = SRT_Mem;
   76167         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
   76168         VdbeComment((v, "Init subquery result"));
   76169       }else{
   76170         dest.eDest = SRT_Exists;
   76171         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
   76172         VdbeComment((v, "Init EXISTS result"));
   76173       }
   76174       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   76175       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
   76176                                   &sqlite3IntTokens[1]);
   76177       pSel->iLimit = 0;
   76178       if( sqlite3Select(pParse, pSel, &dest) ){
   76179         return 0;
   76180       }
   76181       rReg = dest.iParm;
   76182       ExprSetIrreducible(pExpr);
   76183       break;
   76184     }
   76185   }
   76186 
   76187   if( testAddr>=0 ){
   76188     sqlite3VdbeJumpHere(v, testAddr);
   76189   }
   76190   sqlite3ExprCachePop(pParse, 1);
   76191 
   76192   return rReg;
   76193 }
   76194 #endif /* SQLITE_OMIT_SUBQUERY */
   76195 
   76196 #ifndef SQLITE_OMIT_SUBQUERY
   76197 /*
   76198 ** Generate code for an IN expression.
   76199 **
   76200 **      x IN (SELECT ...)
   76201 **      x IN (value, value, ...)
   76202 **
   76203 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   76204 ** is an array of zero or more values.  The expression is true if the LHS is
   76205 ** contained within the RHS.  The value of the expression is unknown (NULL)
   76206 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   76207 ** RHS contains one or more NULL values.
   76208 **
   76209 ** This routine generates code will jump to destIfFalse if the LHS is not
   76210 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   76211 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   76212 ** within the RHS then fall through.
   76213 */
   76214 static void sqlite3ExprCodeIN(
   76215   Parse *pParse,        /* Parsing and code generating context */
   76216   Expr *pExpr,          /* The IN expression */
   76217   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   76218   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   76219 ){
   76220   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   76221   char affinity;        /* Comparison affinity to use */
   76222   int eType;            /* Type of the RHS */
   76223   int r1;               /* Temporary use register */
   76224   Vdbe *v;              /* Statement under construction */
   76225 
   76226   /* Compute the RHS.   After this step, the table with cursor
   76227   ** pExpr->iTable will contains the values that make up the RHS.
   76228   */
   76229   v = pParse->pVdbe;
   76230   assert( v!=0 );       /* OOM detected prior to this routine */
   76231   VdbeNoopComment((v, "begin IN expr"));
   76232   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
   76233 
   76234   /* Figure out the affinity to use to create a key from the results
   76235   ** of the expression. affinityStr stores a static string suitable for
   76236   ** P4 of OP_MakeRecord.
   76237   */
   76238   affinity = comparisonAffinity(pExpr);
   76239 
   76240   /* Code the LHS, the <expr> from "<expr> IN (...)".
   76241   */
   76242   sqlite3ExprCachePush(pParse);
   76243   r1 = sqlite3GetTempReg(pParse);
   76244   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   76245 
   76246   /* If the LHS is NULL, then the result is either false or NULL depending
   76247   ** on whether the RHS is empty or not, respectively.
   76248   */
   76249   if( destIfNull==destIfFalse ){
   76250     /* Shortcut for the common case where the false and NULL outcomes are
   76251     ** the same. */
   76252     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
   76253   }else{
   76254     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
   76255     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   76256     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   76257     sqlite3VdbeJumpHere(v, addr1);
   76258   }
   76259 
   76260   if( eType==IN_INDEX_ROWID ){
   76261     /* In this case, the RHS is the ROWID of table b-tree
   76262     */
   76263     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
   76264     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   76265   }else{
   76266     /* In this case, the RHS is an index b-tree.
   76267     */
   76268     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   76269 
   76270     /* If the set membership test fails, then the result of the
   76271     ** "x IN (...)" expression must be either 0 or NULL. If the set
   76272     ** contains no NULL values, then the result is 0. If the set
   76273     ** contains one or more NULL values, then the result of the
   76274     ** expression is also NULL.
   76275     */
   76276     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
   76277       /* This branch runs if it is known at compile time that the RHS
   76278       ** cannot contain NULL values. This happens as the result
   76279       ** of a "NOT NULL" constraint in the database schema.
   76280       **
   76281       ** Also run this branch if NULL is equivalent to FALSE
   76282       ** for this particular IN operator.
   76283       */
   76284       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   76285 
   76286     }else{
   76287       /* In this branch, the RHS of the IN might contain a NULL and
   76288       ** the presence of a NULL on the RHS makes a difference in the
   76289       ** outcome.
   76290       */
   76291       int j1, j2, j3;
   76292 
   76293       /* First check to see if the LHS is contained in the RHS.  If so,
   76294       ** then the presence of NULLs in the RHS does not matter, so jump
   76295       ** over all of the code that follows.
   76296       */
   76297       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   76298 
   76299       /* Here we begin generating code that runs if the LHS is not
   76300       ** contained within the RHS.  Generate additional code that
   76301       ** tests the RHS for NULLs.  If the RHS contains a NULL then
   76302       ** jump to destIfNull.  If there are no NULLs in the RHS then
   76303       ** jump to destIfFalse.
   76304       */
   76305       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
   76306       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
   76307       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
   76308       sqlite3VdbeJumpHere(v, j3);
   76309       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
   76310       sqlite3VdbeJumpHere(v, j2);
   76311 
   76312       /* Jump to the appropriate target depending on whether or not
   76313       ** the RHS contains a NULL
   76314       */
   76315       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
   76316       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   76317 
   76318       /* The OP_Found at the top of this branch jumps here when true,
   76319       ** causing the overall IN expression evaluation to fall through.
   76320       */
   76321       sqlite3VdbeJumpHere(v, j1);
   76322     }
   76323   }
   76324   sqlite3ReleaseTempReg(pParse, r1);
   76325   sqlite3ExprCachePop(pParse, 1);
   76326   VdbeComment((v, "end IN expr"));
   76327 }
   76328 #endif /* SQLITE_OMIT_SUBQUERY */
   76329 
   76330 /*
   76331 ** Duplicate an 8-byte value
   76332 */
   76333 static char *dup8bytes(Vdbe *v, const char *in){
   76334   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   76335   if( out ){
   76336     memcpy(out, in, 8);
   76337   }
   76338   return out;
   76339 }
   76340 
   76341 #ifndef SQLITE_OMIT_FLOATING_POINT
   76342 /*
   76343 ** Generate an instruction that will put the floating point
   76344 ** value described by z[0..n-1] into register iMem.
   76345 **
   76346 ** The z[] string will probably not be zero-terminated.  But the
   76347 ** z[n] character is guaranteed to be something that does not look
   76348 ** like the continuation of the number.
   76349 */
   76350 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   76351   if( ALWAYS(z!=0) ){
   76352     double value;
   76353     char *zV;
   76354     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   76355     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   76356     if( negateFlag ) value = -value;
   76357     zV = dup8bytes(v, (char*)&value);
   76358     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   76359   }
   76360 }
   76361 #endif
   76362 
   76363 
   76364 /*
   76365 ** Generate an instruction that will put the integer describe by
   76366 ** text z[0..n-1] into register iMem.
   76367 **
   76368 ** Expr.u.zToken is always UTF8 and zero-terminated.
   76369 */
   76370 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   76371   Vdbe *v = pParse->pVdbe;
   76372   if( pExpr->flags & EP_IntValue ){
   76373     int i = pExpr->u.iValue;
   76374     assert( i>=0 );
   76375     if( negFlag ) i = -i;
   76376     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   76377   }else{
   76378     int c;
   76379     i64 value;
   76380     const char *z = pExpr->u.zToken;
   76381     assert( z!=0 );
   76382     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   76383     if( c==0 || (c==2 && negFlag) ){
   76384       char *zV;
   76385       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
   76386       zV = dup8bytes(v, (char*)&value);
   76387       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   76388     }else{
   76389 #ifdef SQLITE_OMIT_FLOATING_POINT
   76390       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   76391 #else
   76392       codeReal(v, z, negFlag, iMem);
   76393 #endif
   76394     }
   76395   }
   76396 }
   76397 
   76398 /*
   76399 ** Clear a cache entry.
   76400 */
   76401 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   76402   if( p->tempReg ){
   76403     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   76404       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   76405     }
   76406     p->tempReg = 0;
   76407   }
   76408 }
   76409 
   76410 
   76411 /*
   76412 ** Record in the column cache that a particular column from a
   76413 ** particular table is stored in a particular register.
   76414 */
   76415 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   76416   int i;
   76417   int minLru;
   76418   int idxLru;
   76419   struct yColCache *p;
   76420 
   76421   assert( iReg>0 );  /* Register numbers are always positive */
   76422   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   76423 
   76424   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   76425   ** for testing only - to verify that SQLite always gets the same answer
   76426   ** with and without the column cache.
   76427   */
   76428   if( pParse->db->flags & SQLITE_ColumnCache ) return;
   76429 
   76430   /* First replace any existing entry.
   76431   **
   76432   ** Actually, the way the column cache is currently used, we are guaranteed
   76433   ** that the object will never already be in cache.  Verify this guarantee.
   76434   */
   76435 #ifndef NDEBUG
   76436   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76437 #if 0 /* This code wold remove the entry from the cache if it existed */
   76438     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
   76439       cacheEntryClear(pParse, p);
   76440       p->iLevel = pParse->iCacheLevel;
   76441       p->iReg = iReg;
   76442       p->lru = pParse->iCacheCnt++;
   76443       return;
   76444     }
   76445 #endif
   76446     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   76447   }
   76448 #endif
   76449 
   76450   /* Find an empty slot and replace it */
   76451   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76452     if( p->iReg==0 ){
   76453       p->iLevel = pParse->iCacheLevel;
   76454       p->iTable = iTab;
   76455       p->iColumn = iCol;
   76456       p->iReg = iReg;
   76457       p->tempReg = 0;
   76458       p->lru = pParse->iCacheCnt++;
   76459       return;
   76460     }
   76461   }
   76462 
   76463   /* Replace the last recently used */
   76464   minLru = 0x7fffffff;
   76465   idxLru = -1;
   76466   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76467     if( p->lru<minLru ){
   76468       idxLru = i;
   76469       minLru = p->lru;
   76470     }
   76471   }
   76472   if( ALWAYS(idxLru>=0) ){
   76473     p = &pParse->aColCache[idxLru];
   76474     p->iLevel = pParse->iCacheLevel;
   76475     p->iTable = iTab;
   76476     p->iColumn = iCol;
   76477     p->iReg = iReg;
   76478     p->tempReg = 0;
   76479     p->lru = pParse->iCacheCnt++;
   76480     return;
   76481   }
   76482 }
   76483 
   76484 /*
   76485 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   76486 ** Purge the range of registers from the column cache.
   76487 */
   76488 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   76489   int i;
   76490   int iLast = iReg + nReg - 1;
   76491   struct yColCache *p;
   76492   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76493     int r = p->iReg;
   76494     if( r>=iReg && r<=iLast ){
   76495       cacheEntryClear(pParse, p);
   76496       p->iReg = 0;
   76497     }
   76498   }
   76499 }
   76500 
   76501 /*
   76502 ** Remember the current column cache context.  Any new entries added
   76503 ** added to the column cache after this call are removed when the
   76504 ** corresponding pop occurs.
   76505 */
   76506 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   76507   pParse->iCacheLevel++;
   76508 }
   76509 
   76510 /*
   76511 ** Remove from the column cache any entries that were added since the
   76512 ** the previous N Push operations.  In other words, restore the cache
   76513 ** to the state it was in N Pushes ago.
   76514 */
   76515 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
   76516   int i;
   76517   struct yColCache *p;
   76518   assert( N>0 );
   76519   assert( pParse->iCacheLevel>=N );
   76520   pParse->iCacheLevel -= N;
   76521   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76522     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   76523       cacheEntryClear(pParse, p);
   76524       p->iReg = 0;
   76525     }
   76526   }
   76527 }
   76528 
   76529 /*
   76530 ** When a cached column is reused, make sure that its register is
   76531 ** no longer available as a temp register.  ticket #3879:  that same
   76532 ** register might be in the cache in multiple places, so be sure to
   76533 ** get them all.
   76534 */
   76535 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   76536   int i;
   76537   struct yColCache *p;
   76538   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76539     if( p->iReg==iReg ){
   76540       p->tempReg = 0;
   76541     }
   76542   }
   76543 }
   76544 
   76545 /*
   76546 ** Generate code to extract the value of the iCol-th column of a table.
   76547 */
   76548 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   76549   Vdbe *v,        /* The VDBE under construction */
   76550   Table *pTab,    /* The table containing the value */
   76551   int iTabCur,    /* The cursor for this table */
   76552   int iCol,       /* Index of the column to extract */
   76553   int regOut      /* Extract the valud into this register */
   76554 ){
   76555   if( iCol<0 || iCol==pTab->iPKey ){
   76556     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   76557   }else{
   76558     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   76559     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
   76560   }
   76561   if( iCol>=0 ){
   76562     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   76563   }
   76564 }
   76565 
   76566 /*
   76567 ** Generate code that will extract the iColumn-th column from
   76568 ** table pTab and store the column value in a register.  An effort
   76569 ** is made to store the column value in register iReg, but this is
   76570 ** not guaranteed.  The location of the column value is returned.
   76571 **
   76572 ** There must be an open cursor to pTab in iTable when this routine
   76573 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   76574 */
   76575 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   76576   Parse *pParse,   /* Parsing and code generating context */
   76577   Table *pTab,     /* Description of the table we are reading from */
   76578   int iColumn,     /* Index of the table column */
   76579   int iTable,      /* The cursor pointing to the table */
   76580   int iReg         /* Store results here */
   76581 ){
   76582   Vdbe *v = pParse->pVdbe;
   76583   int i;
   76584   struct yColCache *p;
   76585 
   76586   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76587     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   76588       p->lru = pParse->iCacheCnt++;
   76589       sqlite3ExprCachePinRegister(pParse, p->iReg);
   76590       return p->iReg;
   76591     }
   76592   }
   76593   assert( v!=0 );
   76594   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   76595   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   76596   return iReg;
   76597 }
   76598 
   76599 /*
   76600 ** Clear all column cache entries.
   76601 */
   76602 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   76603   int i;
   76604   struct yColCache *p;
   76605 
   76606   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76607     if( p->iReg ){
   76608       cacheEntryClear(pParse, p);
   76609       p->iReg = 0;
   76610     }
   76611   }
   76612 }
   76613 
   76614 /*
   76615 ** Record the fact that an affinity change has occurred on iCount
   76616 ** registers starting with iStart.
   76617 */
   76618 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   76619   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   76620 }
   76621 
   76622 /*
   76623 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   76624 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   76625 */
   76626 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   76627   int i;
   76628   struct yColCache *p;
   76629   if( NEVER(iFrom==iTo) ) return;
   76630   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   76631   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76632     int x = p->iReg;
   76633     if( x>=iFrom && x<iFrom+nReg ){
   76634       p->iReg += iTo-iFrom;
   76635     }
   76636   }
   76637 }
   76638 
   76639 /*
   76640 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
   76641 ** over to iTo..iTo+nReg-1.
   76642 */
   76643 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
   76644   int i;
   76645   if( NEVER(iFrom==iTo) ) return;
   76646   for(i=0; i<nReg; i++){
   76647     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
   76648   }
   76649 }
   76650 
   76651 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   76652 /*
   76653 ** Return true if any register in the range iFrom..iTo (inclusive)
   76654 ** is used as part of the column cache.
   76655 **
   76656 ** This routine is used within assert() and testcase() macros only
   76657 ** and does not appear in a normal build.
   76658 */
   76659 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   76660   int i;
   76661   struct yColCache *p;
   76662   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   76663     int r = p->iReg;
   76664     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   76665   }
   76666   return 0;
   76667 }
   76668 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   76669 
   76670 /*
   76671 ** Generate code into the current Vdbe to evaluate the given
   76672 ** expression.  Attempt to store the results in register "target".
   76673 ** Return the register where results are stored.
   76674 **
   76675 ** With this routine, there is no guarantee that results will
   76676 ** be stored in target.  The result might be stored in some other
   76677 ** register if it is convenient to do so.  The calling function
   76678 ** must check the return code and move the results to the desired
   76679 ** register.
   76680 */
   76681 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   76682   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   76683   int op;                   /* The opcode being coded */
   76684   int inReg = target;       /* Results stored in register inReg */
   76685   int regFree1 = 0;         /* If non-zero free this temporary register */
   76686   int regFree2 = 0;         /* If non-zero free this temporary register */
   76687   int r1, r2, r3, r4;       /* Various register numbers */
   76688   sqlite3 *db = pParse->db; /* The database connection */
   76689 
   76690   assert( target>0 && target<=pParse->nMem );
   76691   if( v==0 ){
   76692     assert( pParse->db->mallocFailed );
   76693     return 0;
   76694   }
   76695 
   76696   if( pExpr==0 ){
   76697     op = TK_NULL;
   76698   }else{
   76699     op = pExpr->op;
   76700   }
   76701   switch( op ){
   76702     case TK_AGG_COLUMN: {
   76703       AggInfo *pAggInfo = pExpr->pAggInfo;
   76704       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   76705       if( !pAggInfo->directMode ){
   76706         assert( pCol->iMem>0 );
   76707         inReg = pCol->iMem;
   76708         break;
   76709       }else if( pAggInfo->useSortingIdx ){
   76710         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
   76711                               pCol->iSorterColumn, target);
   76712         break;
   76713       }
   76714       /* Otherwise, fall thru into the TK_COLUMN case */
   76715     }
   76716     case TK_COLUMN: {
   76717       if( pExpr->iTable<0 ){
   76718         /* This only happens when coding check constraints */
   76719         assert( pParse->ckBase>0 );
   76720         inReg = pExpr->iColumn + pParse->ckBase;
   76721       }else{
   76722         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   76723                                  pExpr->iColumn, pExpr->iTable, target);
   76724       }
   76725       break;
   76726     }
   76727     case TK_INTEGER: {
   76728       codeInteger(pParse, pExpr, 0, target);
   76729       break;
   76730     }
   76731 #ifndef SQLITE_OMIT_FLOATING_POINT
   76732     case TK_FLOAT: {
   76733       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76734       codeReal(v, pExpr->u.zToken, 0, target);
   76735       break;
   76736     }
   76737 #endif
   76738     case TK_STRING: {
   76739       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76740       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   76741       break;
   76742     }
   76743     case TK_NULL: {
   76744       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   76745       break;
   76746     }
   76747 #ifndef SQLITE_OMIT_BLOB_LITERAL
   76748     case TK_BLOB: {
   76749       int n;
   76750       const char *z;
   76751       char *zBlob;
   76752       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76753       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   76754       assert( pExpr->u.zToken[1]=='\'' );
   76755       z = &pExpr->u.zToken[2];
   76756       n = sqlite3Strlen30(z) - 1;
   76757       assert( z[n]=='\'' );
   76758       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   76759       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   76760       break;
   76761     }
   76762 #endif
   76763     case TK_VARIABLE: {
   76764       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76765       assert( pExpr->u.zToken!=0 );
   76766       assert( pExpr->u.zToken[0]!=0 );
   76767       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   76768       if( pExpr->u.zToken[1]!=0 ){
   76769         assert( pExpr->u.zToken[0]=='?'
   76770              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
   76771         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
   76772       }
   76773       break;
   76774     }
   76775     case TK_REGISTER: {
   76776       inReg = pExpr->iTable;
   76777       break;
   76778     }
   76779     case TK_AS: {
   76780       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   76781       break;
   76782     }
   76783 #ifndef SQLITE_OMIT_CAST
   76784     case TK_CAST: {
   76785       /* Expressions of the form:   CAST(pLeft AS token) */
   76786       int aff, to_op;
   76787       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   76788       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76789       aff = sqlite3AffinityType(pExpr->u.zToken);
   76790       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   76791       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   76792       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   76793       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   76794       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   76795       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   76796       testcase( to_op==OP_ToText );
   76797       testcase( to_op==OP_ToBlob );
   76798       testcase( to_op==OP_ToNumeric );
   76799       testcase( to_op==OP_ToInt );
   76800       testcase( to_op==OP_ToReal );
   76801       if( inReg!=target ){
   76802         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   76803         inReg = target;
   76804       }
   76805       sqlite3VdbeAddOp1(v, to_op, inReg);
   76806       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   76807       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   76808       break;
   76809     }
   76810 #endif /* SQLITE_OMIT_CAST */
   76811     case TK_LT:
   76812     case TK_LE:
   76813     case TK_GT:
   76814     case TK_GE:
   76815     case TK_NE:
   76816     case TK_EQ: {
   76817       assert( TK_LT==OP_Lt );
   76818       assert( TK_LE==OP_Le );
   76819       assert( TK_GT==OP_Gt );
   76820       assert( TK_GE==OP_Ge );
   76821       assert( TK_EQ==OP_Eq );
   76822       assert( TK_NE==OP_Ne );
   76823       testcase( op==TK_LT );
   76824       testcase( op==TK_LE );
   76825       testcase( op==TK_GT );
   76826       testcase( op==TK_GE );
   76827       testcase( op==TK_EQ );
   76828       testcase( op==TK_NE );
   76829       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76830       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76831       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   76832                   r1, r2, inReg, SQLITE_STOREP2);
   76833       testcase( regFree1==0 );
   76834       testcase( regFree2==0 );
   76835       break;
   76836     }
   76837     case TK_IS:
   76838     case TK_ISNOT: {
   76839       testcase( op==TK_IS );
   76840       testcase( op==TK_ISNOT );
   76841       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76842       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76843       op = (op==TK_IS) ? TK_EQ : TK_NE;
   76844       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   76845                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   76846       testcase( regFree1==0 );
   76847       testcase( regFree2==0 );
   76848       break;
   76849     }
   76850     case TK_AND:
   76851     case TK_OR:
   76852     case TK_PLUS:
   76853     case TK_STAR:
   76854     case TK_MINUS:
   76855     case TK_REM:
   76856     case TK_BITAND:
   76857     case TK_BITOR:
   76858     case TK_SLASH:
   76859     case TK_LSHIFT:
   76860     case TK_RSHIFT:
   76861     case TK_CONCAT: {
   76862       assert( TK_AND==OP_And );
   76863       assert( TK_OR==OP_Or );
   76864       assert( TK_PLUS==OP_Add );
   76865       assert( TK_MINUS==OP_Subtract );
   76866       assert( TK_REM==OP_Remainder );
   76867       assert( TK_BITAND==OP_BitAnd );
   76868       assert( TK_BITOR==OP_BitOr );
   76869       assert( TK_SLASH==OP_Divide );
   76870       assert( TK_LSHIFT==OP_ShiftLeft );
   76871       assert( TK_RSHIFT==OP_ShiftRight );
   76872       assert( TK_CONCAT==OP_Concat );
   76873       testcase( op==TK_AND );
   76874       testcase( op==TK_OR );
   76875       testcase( op==TK_PLUS );
   76876       testcase( op==TK_MINUS );
   76877       testcase( op==TK_REM );
   76878       testcase( op==TK_BITAND );
   76879       testcase( op==TK_BITOR );
   76880       testcase( op==TK_SLASH );
   76881       testcase( op==TK_LSHIFT );
   76882       testcase( op==TK_RSHIFT );
   76883       testcase( op==TK_CONCAT );
   76884       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76885       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   76886       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   76887       testcase( regFree1==0 );
   76888       testcase( regFree2==0 );
   76889       break;
   76890     }
   76891     case TK_UMINUS: {
   76892       Expr *pLeft = pExpr->pLeft;
   76893       assert( pLeft );
   76894       if( pLeft->op==TK_INTEGER ){
   76895         codeInteger(pParse, pLeft, 1, target);
   76896 #ifndef SQLITE_OMIT_FLOATING_POINT
   76897       }else if( pLeft->op==TK_FLOAT ){
   76898         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76899         codeReal(v, pLeft->u.zToken, 1, target);
   76900 #endif
   76901       }else{
   76902         regFree1 = r1 = sqlite3GetTempReg(pParse);
   76903         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
   76904         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   76905         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   76906         testcase( regFree2==0 );
   76907       }
   76908       inReg = target;
   76909       break;
   76910     }
   76911     case TK_BITNOT:
   76912     case TK_NOT: {
   76913       assert( TK_BITNOT==OP_BitNot );
   76914       assert( TK_NOT==OP_Not );
   76915       testcase( op==TK_BITNOT );
   76916       testcase( op==TK_NOT );
   76917       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76918       testcase( regFree1==0 );
   76919       inReg = target;
   76920       sqlite3VdbeAddOp2(v, op, r1, inReg);
   76921       break;
   76922     }
   76923     case TK_ISNULL:
   76924     case TK_NOTNULL: {
   76925       int addr;
   76926       assert( TK_ISNULL==OP_IsNull );
   76927       assert( TK_NOTNULL==OP_NotNull );
   76928       testcase( op==TK_ISNULL );
   76929       testcase( op==TK_NOTNULL );
   76930       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   76931       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   76932       testcase( regFree1==0 );
   76933       addr = sqlite3VdbeAddOp1(v, op, r1);
   76934       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
   76935       sqlite3VdbeJumpHere(v, addr);
   76936       break;
   76937     }
   76938     case TK_AGG_FUNCTION: {
   76939       AggInfo *pInfo = pExpr->pAggInfo;
   76940       if( pInfo==0 ){
   76941         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76942         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   76943       }else{
   76944         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   76945       }
   76946       break;
   76947     }
   76948     case TK_CONST_FUNC:
   76949     case TK_FUNCTION: {
   76950       ExprList *pFarg;       /* List of function arguments */
   76951       int nFarg;             /* Number of function arguments */
   76952       FuncDef *pDef;         /* The function definition object */
   76953       int nId;               /* Length of the function name in bytes */
   76954       const char *zId;       /* The function name */
   76955       int constMask = 0;     /* Mask of function arguments that are constant */
   76956       int i;                 /* Loop counter */
   76957       u8 enc = ENC(db);      /* The text encoding used by this database */
   76958       CollSeq *pColl = 0;    /* A collating sequence */
   76959 
   76960       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   76961       testcase( op==TK_CONST_FUNC );
   76962       testcase( op==TK_FUNCTION );
   76963       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   76964         pFarg = 0;
   76965       }else{
   76966         pFarg = pExpr->x.pList;
   76967       }
   76968       nFarg = pFarg ? pFarg->nExpr : 0;
   76969       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   76970       zId = pExpr->u.zToken;
   76971       nId = sqlite3Strlen30(zId);
   76972       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   76973       if( pDef==0 ){
   76974         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   76975         break;
   76976       }
   76977 
   76978       /* Attempt a direct implementation of the built-in COALESCE() and
   76979       ** IFNULL() functions.  This avoids unnecessary evalation of
   76980       ** arguments past the first non-NULL argument.
   76981       */
   76982       if( pDef->flags & SQLITE_FUNC_COALESCE ){
   76983         int endCoalesce = sqlite3VdbeMakeLabel(v);
   76984         assert( nFarg>=2 );
   76985         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   76986         for(i=1; i<nFarg; i++){
   76987           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   76988           sqlite3ExprCacheRemove(pParse, target, 1);
   76989           sqlite3ExprCachePush(pParse);
   76990           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   76991           sqlite3ExprCachePop(pParse, 1);
   76992         }
   76993         sqlite3VdbeResolveLabel(v, endCoalesce);
   76994         break;
   76995       }
   76996 
   76997 
   76998       if( pFarg ){
   76999         r1 = sqlite3GetTempRange(pParse, nFarg);
   77000         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   77001         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
   77002         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
   77003       }else{
   77004         r1 = 0;
   77005       }
   77006 #ifndef SQLITE_OMIT_VIRTUALTABLE
   77007       /* Possibly overload the function if the first argument is
   77008       ** a virtual table column.
   77009       **
   77010       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   77011       ** second argument, not the first, as the argument to test to
   77012       ** see if it is a column in a virtual table.  This is done because
   77013       ** the left operand of infix functions (the operand we want to
   77014       ** control overloading) ends up as the second argument to the
   77015       ** function.  The expression "A glob B" is equivalent to
   77016       ** "glob(B,A).  We want to use the A in "A glob B" to test
   77017       ** for function overloading.  But we use the B term in "glob(B,A)".
   77018       */
   77019       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   77020         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   77021       }else if( nFarg>0 ){
   77022         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   77023       }
   77024 #endif
   77025       for(i=0; i<nFarg; i++){
   77026         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   77027           constMask |= (1<<i);
   77028         }
   77029         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   77030           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   77031         }
   77032       }
   77033       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
   77034         if( !pColl ) pColl = db->pDfltColl;
   77035         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   77036       }
   77037       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   77038                         (char*)pDef, P4_FUNCDEF);
   77039       sqlite3VdbeChangeP5(v, (u8)nFarg);
   77040       if( nFarg ){
   77041         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   77042       }
   77043       break;
   77044     }
   77045 #ifndef SQLITE_OMIT_SUBQUERY
   77046     case TK_EXISTS:
   77047     case TK_SELECT: {
   77048       testcase( op==TK_EXISTS );
   77049       testcase( op==TK_SELECT );
   77050       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   77051       break;
   77052     }
   77053     case TK_IN: {
   77054       int destIfFalse = sqlite3VdbeMakeLabel(v);
   77055       int destIfNull = sqlite3VdbeMakeLabel(v);
   77056       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   77057       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   77058       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   77059       sqlite3VdbeResolveLabel(v, destIfFalse);
   77060       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   77061       sqlite3VdbeResolveLabel(v, destIfNull);
   77062       break;
   77063     }
   77064 #endif /* SQLITE_OMIT_SUBQUERY */
   77065 
   77066 
   77067     /*
   77068     **    x BETWEEN y AND z
   77069     **
   77070     ** This is equivalent to
   77071     **
   77072     **    x>=y AND x<=z
   77073     **
   77074     ** X is stored in pExpr->pLeft.
   77075     ** Y is stored in pExpr->pList->a[0].pExpr.
   77076     ** Z is stored in pExpr->pList->a[1].pExpr.
   77077     */
   77078     case TK_BETWEEN: {
   77079       Expr *pLeft = pExpr->pLeft;
   77080       struct ExprList_item *pLItem = pExpr->x.pList->a;
   77081       Expr *pRight = pLItem->pExpr;
   77082 
   77083       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   77084       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   77085       testcase( regFree1==0 );
   77086       testcase( regFree2==0 );
   77087       r3 = sqlite3GetTempReg(pParse);
   77088       r4 = sqlite3GetTempReg(pParse);
   77089       codeCompare(pParse, pLeft, pRight, OP_Ge,
   77090                   r1, r2, r3, SQLITE_STOREP2);
   77091       pLItem++;
   77092       pRight = pLItem->pExpr;
   77093       sqlite3ReleaseTempReg(pParse, regFree2);
   77094       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   77095       testcase( regFree2==0 );
   77096       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   77097       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   77098       sqlite3ReleaseTempReg(pParse, r3);
   77099       sqlite3ReleaseTempReg(pParse, r4);
   77100       break;
   77101     }
   77102     case TK_UPLUS: {
   77103       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   77104       break;
   77105     }
   77106 
   77107     case TK_TRIGGER: {
   77108       /* If the opcode is TK_TRIGGER, then the expression is a reference
   77109       ** to a column in the new.* or old.* pseudo-tables available to
   77110       ** trigger programs. In this case Expr.iTable is set to 1 for the
   77111       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   77112       ** is set to the column of the pseudo-table to read, or to -1 to
   77113       ** read the rowid field.
   77114       **
   77115       ** The expression is implemented using an OP_Param opcode. The p1
   77116       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   77117       ** to reference another column of the old.* pseudo-table, where
   77118       ** i is the index of the column. For a new.rowid reference, p1 is
   77119       ** set to (n+1), where n is the number of columns in each pseudo-table.
   77120       ** For a reference to any other column in the new.* pseudo-table, p1
   77121       ** is set to (n+2+i), where n and i are as defined previously. For
   77122       ** example, if the table on which triggers are being fired is
   77123       ** declared as:
   77124       **
   77125       **   CREATE TABLE t1(a, b);
   77126       **
   77127       ** Then p1 is interpreted as follows:
   77128       **
   77129       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   77130       **   p1==1   ->    old.a         p1==4   ->    new.a
   77131       **   p1==2   ->    old.b         p1==5   ->    new.b
   77132       */
   77133       Table *pTab = pExpr->pTab;
   77134       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   77135 
   77136       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   77137       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   77138       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   77139       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   77140 
   77141       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   77142       VdbeComment((v, "%s.%s -> $%d",
   77143         (pExpr->iTable ? "new" : "old"),
   77144         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   77145         target
   77146       ));
   77147 
   77148 #ifndef SQLITE_OMIT_FLOATING_POINT
   77149       /* If the column has REAL affinity, it may currently be stored as an
   77150       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   77151       if( pExpr->iColumn>=0
   77152        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   77153       ){
   77154         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   77155       }
   77156 #endif
   77157       break;
   77158     }
   77159 
   77160 
   77161     /*
   77162     ** Form A:
   77163     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   77164     **
   77165     ** Form B:
   77166     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   77167     **
   77168     ** Form A is can be transformed into the equivalent form B as follows:
   77169     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   77170     **        WHEN x=eN THEN rN ELSE y END
   77171     **
   77172     ** X (if it exists) is in pExpr->pLeft.
   77173     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
   77174     ** ELSE clause and no other term matches, then the result of the
   77175     ** exprssion is NULL.
   77176     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   77177     **
   77178     ** The result of the expression is the Ri for the first matching Ei,
   77179     ** or if there is no matching Ei, the ELSE term Y, or if there is
   77180     ** no ELSE term, NULL.
   77181     */
   77182     default: assert( op==TK_CASE ); {
   77183       int endLabel;                     /* GOTO label for end of CASE stmt */
   77184       int nextCase;                     /* GOTO label for next WHEN clause */
   77185       int nExpr;                        /* 2x number of WHEN terms */
   77186       int i;                            /* Loop counter */
   77187       ExprList *pEList;                 /* List of WHEN terms */
   77188       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   77189       Expr opCompare;                   /* The X==Ei expression */
   77190       Expr cacheX;                      /* Cached expression X */
   77191       Expr *pX;                         /* The X expression */
   77192       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   77193       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   77194 
   77195       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   77196       assert((pExpr->x.pList->nExpr % 2) == 0);
   77197       assert(pExpr->x.pList->nExpr > 0);
   77198       pEList = pExpr->x.pList;
   77199       aListelem = pEList->a;
   77200       nExpr = pEList->nExpr;
   77201       endLabel = sqlite3VdbeMakeLabel(v);
   77202       if( (pX = pExpr->pLeft)!=0 ){
   77203         cacheX = *pX;
   77204         testcase( pX->op==TK_COLUMN );
   77205         testcase( pX->op==TK_REGISTER );
   77206         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
   77207         testcase( regFree1==0 );
   77208         cacheX.op = TK_REGISTER;
   77209         opCompare.op = TK_EQ;
   77210         opCompare.pLeft = &cacheX;
   77211         pTest = &opCompare;
   77212         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   77213         ** The value in regFree1 might get SCopy-ed into the file result.
   77214         ** So make sure that the regFree1 register is not reused for other
   77215         ** purposes and possibly overwritten.  */
   77216         regFree1 = 0;
   77217       }
   77218       for(i=0; i<nExpr; i=i+2){
   77219         sqlite3ExprCachePush(pParse);
   77220         if( pX ){
   77221           assert( pTest!=0 );
   77222           opCompare.pRight = aListelem[i].pExpr;
   77223         }else{
   77224           pTest = aListelem[i].pExpr;
   77225         }
   77226         nextCase = sqlite3VdbeMakeLabel(v);
   77227         testcase( pTest->op==TK_COLUMN );
   77228         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   77229         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   77230         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
   77231         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   77232         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   77233         sqlite3ExprCachePop(pParse, 1);
   77234         sqlite3VdbeResolveLabel(v, nextCase);
   77235       }
   77236       if( pExpr->pRight ){
   77237         sqlite3ExprCachePush(pParse);
   77238         sqlite3ExprCode(pParse, pExpr->pRight, target);
   77239         sqlite3ExprCachePop(pParse, 1);
   77240       }else{
   77241         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   77242       }
   77243       assert( db->mallocFailed || pParse->nErr>0
   77244            || pParse->iCacheLevel==iCacheLevel );
   77245       sqlite3VdbeResolveLabel(v, endLabel);
   77246       break;
   77247     }
   77248 #ifndef SQLITE_OMIT_TRIGGER
   77249     case TK_RAISE: {
   77250       assert( pExpr->affinity==OE_Rollback
   77251            || pExpr->affinity==OE_Abort
   77252            || pExpr->affinity==OE_Fail
   77253            || pExpr->affinity==OE_Ignore
   77254       );
   77255       if( !pParse->pTriggerTab ){
   77256         sqlite3ErrorMsg(pParse,
   77257                        "RAISE() may only be used within a trigger-program");
   77258         return 0;
   77259       }
   77260       if( pExpr->affinity==OE_Abort ){
   77261         sqlite3MayAbort(pParse);
   77262       }
   77263       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   77264       if( pExpr->affinity==OE_Ignore ){
   77265         sqlite3VdbeAddOp4(
   77266             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   77267       }else{
   77268         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
   77269       }
   77270 
   77271       break;
   77272     }
   77273 #endif
   77274   }
   77275   sqlite3ReleaseTempReg(pParse, regFree1);
   77276   sqlite3ReleaseTempReg(pParse, regFree2);
   77277   return inReg;
   77278 }
   77279 
   77280 /*
   77281 ** Generate code to evaluate an expression and store the results
   77282 ** into a register.  Return the register number where the results
   77283 ** are stored.
   77284 **
   77285 ** If the register is a temporary register that can be deallocated,
   77286 ** then write its number into *pReg.  If the result register is not
   77287 ** a temporary, then set *pReg to zero.
   77288 */
   77289 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   77290   int r1 = sqlite3GetTempReg(pParse);
   77291   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   77292   if( r2==r1 ){
   77293     *pReg = r1;
   77294   }else{
   77295     sqlite3ReleaseTempReg(pParse, r1);
   77296     *pReg = 0;
   77297   }
   77298   return r2;
   77299 }
   77300 
   77301 /*
   77302 ** Generate code that will evaluate expression pExpr and store the
   77303 ** results in register target.  The results are guaranteed to appear
   77304 ** in register target.
   77305 */
   77306 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   77307   int inReg;
   77308 
   77309   assert( target>0 && target<=pParse->nMem );
   77310   if( pExpr && pExpr->op==TK_REGISTER ){
   77311     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   77312   }else{
   77313     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   77314     assert( pParse->pVdbe || pParse->db->mallocFailed );
   77315     if( inReg!=target && pParse->pVdbe ){
   77316       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   77317     }
   77318   }
   77319   return target;
   77320 }
   77321 
   77322 /*
   77323 ** Generate code that evalutes the given expression and puts the result
   77324 ** in register target.
   77325 **
   77326 ** Also make a copy of the expression results into another "cache" register
   77327 ** and modify the expression so that the next time it is evaluated,
   77328 ** the result is a copy of the cache register.
   77329 **
   77330 ** This routine is used for expressions that are used multiple
   77331 ** times.  They are evaluated once and the results of the expression
   77332 ** are reused.
   77333 */
   77334 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   77335   Vdbe *v = pParse->pVdbe;
   77336   int inReg;
   77337   inReg = sqlite3ExprCode(pParse, pExpr, target);
   77338   assert( target>0 );
   77339   /* This routine is called for terms to INSERT or UPDATE.  And the only
   77340   ** other place where expressions can be converted into TK_REGISTER is
   77341   ** in WHERE clause processing.  So as currently implemented, there is
   77342   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
   77343   ** keep the ALWAYS() in case the conditions above change with future
   77344   ** modifications or enhancements. */
   77345   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
   77346     int iMem;
   77347     iMem = ++pParse->nMem;
   77348     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
   77349     pExpr->iTable = iMem;
   77350     pExpr->op2 = pExpr->op;
   77351     pExpr->op = TK_REGISTER;
   77352   }
   77353   return inReg;
   77354 }
   77355 
   77356 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   77357 /*
   77358 ** Generate a human-readable explanation of an expression tree.
   77359 */
   77360 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
   77361   int op;                   /* The opcode being coded */
   77362   const char *zBinOp = 0;   /* Binary operator */
   77363   const char *zUniOp = 0;   /* Unary operator */
   77364   if( pExpr==0 ){
   77365     op = TK_NULL;
   77366   }else{
   77367     op = pExpr->op;
   77368   }
   77369   switch( op ){
   77370     case TK_AGG_COLUMN: {
   77371       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
   77372             pExpr->iTable, pExpr->iColumn);
   77373       break;
   77374     }
   77375     case TK_COLUMN: {
   77376       if( pExpr->iTable<0 ){
   77377         /* This only happens when coding check constraints */
   77378         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
   77379       }else{
   77380         sqlite3ExplainPrintf(pOut, "{%d:%d}",
   77381                              pExpr->iTable, pExpr->iColumn);
   77382       }
   77383       break;
   77384     }
   77385     case TK_INTEGER: {
   77386       if( pExpr->flags & EP_IntValue ){
   77387         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
   77388       }else{
   77389         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
   77390       }
   77391       break;
   77392     }
   77393 #ifndef SQLITE_OMIT_FLOATING_POINT
   77394     case TK_FLOAT: {
   77395       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   77396       break;
   77397     }
   77398 #endif
   77399     case TK_STRING: {
   77400       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
   77401       break;
   77402     }
   77403     case TK_NULL: {
   77404       sqlite3ExplainPrintf(pOut,"NULL");
   77405       break;
   77406     }
   77407 #ifndef SQLITE_OMIT_BLOB_LITERAL
   77408     case TK_BLOB: {
   77409       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
   77410       break;
   77411     }
   77412 #endif
   77413     case TK_VARIABLE: {
   77414       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
   77415                            pExpr->u.zToken, pExpr->iColumn);
   77416       break;
   77417     }
   77418     case TK_REGISTER: {
   77419       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
   77420       break;
   77421     }
   77422     case TK_AS: {
   77423       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77424       break;
   77425     }
   77426 #ifndef SQLITE_OMIT_CAST
   77427     case TK_CAST: {
   77428       /* Expressions of the form:   CAST(pLeft AS token) */
   77429       const char *zAff = "unk";
   77430       switch( sqlite3AffinityType(pExpr->u.zToken) ){
   77431         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
   77432         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
   77433         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
   77434         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
   77435         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
   77436       }
   77437       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
   77438       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77439       sqlite3ExplainPrintf(pOut, ")");
   77440       break;
   77441     }
   77442 #endif /* SQLITE_OMIT_CAST */
   77443     case TK_LT:      zBinOp = "LT";     break;
   77444     case TK_LE:      zBinOp = "LE";     break;
   77445     case TK_GT:      zBinOp = "GT";     break;
   77446     case TK_GE:      zBinOp = "GE";     break;
   77447     case TK_NE:      zBinOp = "NE";     break;
   77448     case TK_EQ:      zBinOp = "EQ";     break;
   77449     case TK_IS:      zBinOp = "IS";     break;
   77450     case TK_ISNOT:   zBinOp = "ISNOT";  break;
   77451     case TK_AND:     zBinOp = "AND";    break;
   77452     case TK_OR:      zBinOp = "OR";     break;
   77453     case TK_PLUS:    zBinOp = "ADD";    break;
   77454     case TK_STAR:    zBinOp = "MUL";    break;
   77455     case TK_MINUS:   zBinOp = "SUB";    break;
   77456     case TK_REM:     zBinOp = "REM";    break;
   77457     case TK_BITAND:  zBinOp = "BITAND"; break;
   77458     case TK_BITOR:   zBinOp = "BITOR";  break;
   77459     case TK_SLASH:   zBinOp = "DIV";    break;
   77460     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
   77461     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
   77462     case TK_CONCAT:  zBinOp = "CONCAT"; break;
   77463 
   77464     case TK_UMINUS:  zUniOp = "UMINUS"; break;
   77465     case TK_UPLUS:   zUniOp = "UPLUS";  break;
   77466     case TK_BITNOT:  zUniOp = "BITNOT"; break;
   77467     case TK_NOT:     zUniOp = "NOT";    break;
   77468     case TK_ISNULL:  zUniOp = "ISNULL"; break;
   77469     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
   77470 
   77471     case TK_AGG_FUNCTION:
   77472     case TK_CONST_FUNC:
   77473     case TK_FUNCTION: {
   77474       ExprList *pFarg;       /* List of function arguments */
   77475       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   77476         pFarg = 0;
   77477       }else{
   77478         pFarg = pExpr->x.pList;
   77479       }
   77480       sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
   77481                            op==TK_AGG_FUNCTION ? "AGG_" : "",
   77482                            pExpr->u.zToken);
   77483       if( pFarg ){
   77484         sqlite3ExplainExprList(pOut, pFarg);
   77485       }
   77486       sqlite3ExplainPrintf(pOut, ")");
   77487       break;
   77488     }
   77489 #ifndef SQLITE_OMIT_SUBQUERY
   77490     case TK_EXISTS: {
   77491       sqlite3ExplainPrintf(pOut, "EXISTS(");
   77492       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77493       sqlite3ExplainPrintf(pOut,")");
   77494       break;
   77495     }
   77496     case TK_SELECT: {
   77497       sqlite3ExplainPrintf(pOut, "(");
   77498       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77499       sqlite3ExplainPrintf(pOut, ")");
   77500       break;
   77501     }
   77502     case TK_IN: {
   77503       sqlite3ExplainPrintf(pOut, "IN(");
   77504       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77505       sqlite3ExplainPrintf(pOut, ",");
   77506       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   77507         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
   77508       }else{
   77509         sqlite3ExplainExprList(pOut, pExpr->x.pList);
   77510       }
   77511       sqlite3ExplainPrintf(pOut, ")");
   77512       break;
   77513     }
   77514 #endif /* SQLITE_OMIT_SUBQUERY */
   77515 
   77516     /*
   77517     **    x BETWEEN y AND z
   77518     **
   77519     ** This is equivalent to
   77520     **
   77521     **    x>=y AND x<=z
   77522     **
   77523     ** X is stored in pExpr->pLeft.
   77524     ** Y is stored in pExpr->pList->a[0].pExpr.
   77525     ** Z is stored in pExpr->pList->a[1].pExpr.
   77526     */
   77527     case TK_BETWEEN: {
   77528       Expr *pX = pExpr->pLeft;
   77529       Expr *pY = pExpr->x.pList->a[0].pExpr;
   77530       Expr *pZ = pExpr->x.pList->a[1].pExpr;
   77531       sqlite3ExplainPrintf(pOut, "BETWEEN(");
   77532       sqlite3ExplainExpr(pOut, pX);
   77533       sqlite3ExplainPrintf(pOut, ",");
   77534       sqlite3ExplainExpr(pOut, pY);
   77535       sqlite3ExplainPrintf(pOut, ",");
   77536       sqlite3ExplainExpr(pOut, pZ);
   77537       sqlite3ExplainPrintf(pOut, ")");
   77538       break;
   77539     }
   77540     case TK_TRIGGER: {
   77541       /* If the opcode is TK_TRIGGER, then the expression is a reference
   77542       ** to a column in the new.* or old.* pseudo-tables available to
   77543       ** trigger programs. In this case Expr.iTable is set to 1 for the
   77544       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   77545       ** is set to the column of the pseudo-table to read, or to -1 to
   77546       ** read the rowid field.
   77547       */
   77548       sqlite3ExplainPrintf(pOut, "%s(%d)",
   77549           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
   77550       break;
   77551     }
   77552     case TK_CASE: {
   77553       sqlite3ExplainPrintf(pOut, "CASE(");
   77554       sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77555       sqlite3ExplainPrintf(pOut, ",");
   77556       sqlite3ExplainExprList(pOut, pExpr->x.pList);
   77557       break;
   77558     }
   77559 #ifndef SQLITE_OMIT_TRIGGER
   77560     case TK_RAISE: {
   77561       const char *zType = "unk";
   77562       switch( pExpr->affinity ){
   77563         case OE_Rollback:   zType = "rollback";  break;
   77564         case OE_Abort:      zType = "abort";     break;
   77565         case OE_Fail:       zType = "fail";      break;
   77566         case OE_Ignore:     zType = "ignore";    break;
   77567       }
   77568       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
   77569       break;
   77570     }
   77571 #endif
   77572   }
   77573   if( zBinOp ){
   77574     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
   77575     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77576     sqlite3ExplainPrintf(pOut,",");
   77577     sqlite3ExplainExpr(pOut, pExpr->pRight);
   77578     sqlite3ExplainPrintf(pOut,")");
   77579   }else if( zUniOp ){
   77580     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
   77581     sqlite3ExplainExpr(pOut, pExpr->pLeft);
   77582     sqlite3ExplainPrintf(pOut,")");
   77583   }
   77584 }
   77585 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   77586 
   77587 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   77588 /*
   77589 ** Generate a human-readable explanation of an expression list.
   77590 */
   77591 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
   77592   int i;
   77593   if( pList==0 || pList->nExpr==0 ){
   77594     sqlite3ExplainPrintf(pOut, "(empty-list)");
   77595     return;
   77596   }else if( pList->nExpr==1 ){
   77597     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
   77598   }else{
   77599     sqlite3ExplainPush(pOut);
   77600     for(i=0; i<pList->nExpr; i++){
   77601       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
   77602       sqlite3ExplainPush(pOut);
   77603       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
   77604       sqlite3ExplainPop(pOut);
   77605       if( i<pList->nExpr-1 ){
   77606         sqlite3ExplainNL(pOut);
   77607       }
   77608     }
   77609     sqlite3ExplainPop(pOut);
   77610   }
   77611 }
   77612 #endif /* SQLITE_DEBUG */
   77613 
   77614 /*
   77615 ** Return TRUE if pExpr is an constant expression that is appropriate
   77616 ** for factoring out of a loop.  Appropriate expressions are:
   77617 **
   77618 **    *  Any expression that evaluates to two or more opcodes.
   77619 **
   77620 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
   77621 **       or OP_Variable that does not need to be placed in a
   77622 **       specific register.
   77623 **
   77624 ** There is no point in factoring out single-instruction constant
   77625 ** expressions that need to be placed in a particular register.
   77626 ** We could factor them out, but then we would end up adding an
   77627 ** OP_SCopy instruction to move the value into the correct register
   77628 ** later.  We might as well just use the original instruction and
   77629 ** avoid the OP_SCopy.
   77630 */
   77631 static int isAppropriateForFactoring(Expr *p){
   77632   if( !sqlite3ExprIsConstantNotJoin(p) ){
   77633     return 0;  /* Only constant expressions are appropriate for factoring */
   77634   }
   77635   if( (p->flags & EP_FixedDest)==0 ){
   77636     return 1;  /* Any constant without a fixed destination is appropriate */
   77637   }
   77638   while( p->op==TK_UPLUS ) p = p->pLeft;
   77639   switch( p->op ){
   77640 #ifndef SQLITE_OMIT_BLOB_LITERAL
   77641     case TK_BLOB:
   77642 #endif
   77643     case TK_VARIABLE:
   77644     case TK_INTEGER:
   77645     case TK_FLOAT:
   77646     case TK_NULL:
   77647     case TK_STRING: {
   77648       testcase( p->op==TK_BLOB );
   77649       testcase( p->op==TK_VARIABLE );
   77650       testcase( p->op==TK_INTEGER );
   77651       testcase( p->op==TK_FLOAT );
   77652       testcase( p->op==TK_NULL );
   77653       testcase( p->op==TK_STRING );
   77654       /* Single-instruction constants with a fixed destination are
   77655       ** better done in-line.  If we factor them, they will just end
   77656       ** up generating an OP_SCopy to move the value to the destination
   77657       ** register. */
   77658       return 0;
   77659     }
   77660     case TK_UMINUS: {
   77661       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
   77662         return 0;
   77663       }
   77664       break;
   77665     }
   77666     default: {
   77667       break;
   77668     }
   77669   }
   77670   return 1;
   77671 }
   77672 
   77673 /*
   77674 ** If pExpr is a constant expression that is appropriate for
   77675 ** factoring out of a loop, then evaluate the expression
   77676 ** into a register and convert the expression into a TK_REGISTER
   77677 ** expression.
   77678 */
   77679 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
   77680   Parse *pParse = pWalker->pParse;
   77681   switch( pExpr->op ){
   77682     case TK_IN:
   77683     case TK_REGISTER: {
   77684       return WRC_Prune;
   77685     }
   77686     case TK_FUNCTION:
   77687     case TK_AGG_FUNCTION:
   77688     case TK_CONST_FUNC: {
   77689       /* The arguments to a function have a fixed destination.
   77690       ** Mark them this way to avoid generated unneeded OP_SCopy
   77691       ** instructions.
   77692       */
   77693       ExprList *pList = pExpr->x.pList;
   77694       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77695       if( pList ){
   77696         int i = pList->nExpr;
   77697         struct ExprList_item *pItem = pList->a;
   77698         for(; i>0; i--, pItem++){
   77699           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
   77700         }
   77701       }
   77702       break;
   77703     }
   77704   }
   77705   if( isAppropriateForFactoring(pExpr) ){
   77706     int r1 = ++pParse->nMem;
   77707     int r2;
   77708     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   77709     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
   77710     pExpr->op2 = pExpr->op;
   77711     pExpr->op = TK_REGISTER;
   77712     pExpr->iTable = r2;
   77713     return WRC_Prune;
   77714   }
   77715   return WRC_Continue;
   77716 }
   77717 
   77718 /*
   77719 ** Preevaluate constant subexpressions within pExpr and store the
   77720 ** results in registers.  Modify pExpr so that the constant subexpresions
   77721 ** are TK_REGISTER opcodes that refer to the precomputed values.
   77722 **
   77723 ** This routine is a no-op if the jump to the cookie-check code has
   77724 ** already occur.  Since the cookie-check jump is generated prior to
   77725 ** any other serious processing, this check ensures that there is no
   77726 ** way to accidently bypass the constant initializations.
   77727 **
   77728 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
   77729 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
   77730 ** interface.  This allows test logic to verify that the same answer is
   77731 ** obtained for queries regardless of whether or not constants are
   77732 ** precomputed into registers or if they are inserted in-line.
   77733 */
   77734 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
   77735   Walker w;
   77736   if( pParse->cookieGoto ) return;
   77737   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
   77738   w.xExprCallback = evalConstExpr;
   77739   w.xSelectCallback = 0;
   77740   w.pParse = pParse;
   77741   sqlite3WalkExpr(&w, pExpr);
   77742 }
   77743 
   77744 
   77745 /*
   77746 ** Generate code that pushes the value of every element of the given
   77747 ** expression list into a sequence of registers beginning at target.
   77748 **
   77749 ** Return the number of elements evaluated.
   77750 */
   77751 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   77752   Parse *pParse,     /* Parsing context */
   77753   ExprList *pList,   /* The expression list to be coded */
   77754   int target,        /* Where to write results */
   77755   int doHardCopy     /* Make a hard copy of every element */
   77756 ){
   77757   struct ExprList_item *pItem;
   77758   int i, n;
   77759   assert( pList!=0 );
   77760   assert( target>0 );
   77761   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   77762   n = pList->nExpr;
   77763   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   77764     Expr *pExpr = pItem->pExpr;
   77765     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   77766     if( inReg!=target+i ){
   77767       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
   77768                         inReg, target+i);
   77769     }
   77770   }
   77771   return n;
   77772 }
   77773 
   77774 /*
   77775 ** Generate code for a BETWEEN operator.
   77776 **
   77777 **    x BETWEEN y AND z
   77778 **
   77779 ** The above is equivalent to
   77780 **
   77781 **    x>=y AND x<=z
   77782 **
   77783 ** Code it as such, taking care to do the common subexpression
   77784 ** elementation of x.
   77785 */
   77786 static void exprCodeBetween(
   77787   Parse *pParse,    /* Parsing and code generating context */
   77788   Expr *pExpr,      /* The BETWEEN expression */
   77789   int dest,         /* Jump here if the jump is taken */
   77790   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   77791   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   77792 ){
   77793   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   77794   Expr compLeft;    /* The  x>=y  term */
   77795   Expr compRight;   /* The  x<=z  term */
   77796   Expr exprX;       /* The  x  subexpression */
   77797   int regFree1 = 0; /* Temporary use register */
   77798 
   77799   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   77800   exprX = *pExpr->pLeft;
   77801   exprAnd.op = TK_AND;
   77802   exprAnd.pLeft = &compLeft;
   77803   exprAnd.pRight = &compRight;
   77804   compLeft.op = TK_GE;
   77805   compLeft.pLeft = &exprX;
   77806   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   77807   compRight.op = TK_LE;
   77808   compRight.pLeft = &exprX;
   77809   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   77810   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
   77811   exprX.op = TK_REGISTER;
   77812   if( jumpIfTrue ){
   77813     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   77814   }else{
   77815     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   77816   }
   77817   sqlite3ReleaseTempReg(pParse, regFree1);
   77818 
   77819   /* Ensure adequate test coverage */
   77820   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   77821   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   77822   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   77823   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   77824   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   77825   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   77826   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   77827   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   77828 }
   77829 
   77830 /*
   77831 ** Generate code for a boolean expression such that a jump is made
   77832 ** to the label "dest" if the expression is true but execution
   77833 ** continues straight thru if the expression is false.
   77834 **
   77835 ** If the expression evaluates to NULL (neither true nor false), then
   77836 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   77837 **
   77838 ** This code depends on the fact that certain token values (ex: TK_EQ)
   77839 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   77840 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   77841 ** the make process cause these values to align.  Assert()s in the code
   77842 ** below verify that the numbers are aligned correctly.
   77843 */
   77844 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   77845   Vdbe *v = pParse->pVdbe;
   77846   int op = 0;
   77847   int regFree1 = 0;
   77848   int regFree2 = 0;
   77849   int r1, r2;
   77850 
   77851   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   77852   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
   77853   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   77854   op = pExpr->op;
   77855   switch( op ){
   77856     case TK_AND: {
   77857       int d2 = sqlite3VdbeMakeLabel(v);
   77858       testcase( jumpIfNull==0 );
   77859       sqlite3ExprCachePush(pParse);
   77860       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   77861       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   77862       sqlite3VdbeResolveLabel(v, d2);
   77863       sqlite3ExprCachePop(pParse, 1);
   77864       break;
   77865     }
   77866     case TK_OR: {
   77867       testcase( jumpIfNull==0 );
   77868       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   77869       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   77870       break;
   77871     }
   77872     case TK_NOT: {
   77873       testcase( jumpIfNull==0 );
   77874       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   77875       break;
   77876     }
   77877     case TK_LT:
   77878     case TK_LE:
   77879     case TK_GT:
   77880     case TK_GE:
   77881     case TK_NE:
   77882     case TK_EQ: {
   77883       assert( TK_LT==OP_Lt );
   77884       assert( TK_LE==OP_Le );
   77885       assert( TK_GT==OP_Gt );
   77886       assert( TK_GE==OP_Ge );
   77887       assert( TK_EQ==OP_Eq );
   77888       assert( TK_NE==OP_Ne );
   77889       testcase( op==TK_LT );
   77890       testcase( op==TK_LE );
   77891       testcase( op==TK_GT );
   77892       testcase( op==TK_GE );
   77893       testcase( op==TK_EQ );
   77894       testcase( op==TK_NE );
   77895       testcase( jumpIfNull==0 );
   77896       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77897       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   77898       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   77899                   r1, r2, dest, jumpIfNull);
   77900       testcase( regFree1==0 );
   77901       testcase( regFree2==0 );
   77902       break;
   77903     }
   77904     case TK_IS:
   77905     case TK_ISNOT: {
   77906       testcase( op==TK_IS );
   77907       testcase( op==TK_ISNOT );
   77908       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77909       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   77910       op = (op==TK_IS) ? TK_EQ : TK_NE;
   77911       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   77912                   r1, r2, dest, SQLITE_NULLEQ);
   77913       testcase( regFree1==0 );
   77914       testcase( regFree2==0 );
   77915       break;
   77916     }
   77917     case TK_ISNULL:
   77918     case TK_NOTNULL: {
   77919       assert( TK_ISNULL==OP_IsNull );
   77920       assert( TK_NOTNULL==OP_NotNull );
   77921       testcase( op==TK_ISNULL );
   77922       testcase( op==TK_NOTNULL );
   77923       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   77924       sqlite3VdbeAddOp2(v, op, r1, dest);
   77925       testcase( regFree1==0 );
   77926       break;
   77927     }
   77928     case TK_BETWEEN: {
   77929       testcase( jumpIfNull==0 );
   77930       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   77931       break;
   77932     }
   77933 #ifndef SQLITE_OMIT_SUBQUERY
   77934     case TK_IN: {
   77935       int destIfFalse = sqlite3VdbeMakeLabel(v);
   77936       int destIfNull = jumpIfNull ? dest : destIfFalse;
   77937       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   77938       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   77939       sqlite3VdbeResolveLabel(v, destIfFalse);
   77940       break;
   77941     }
   77942 #endif
   77943     default: {
   77944       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   77945       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   77946       testcase( regFree1==0 );
   77947       testcase( jumpIfNull==0 );
   77948       break;
   77949     }
   77950   }
   77951   sqlite3ReleaseTempReg(pParse, regFree1);
   77952   sqlite3ReleaseTempReg(pParse, regFree2);
   77953 }
   77954 
   77955 /*
   77956 ** Generate code for a boolean expression such that a jump is made
   77957 ** to the label "dest" if the expression is false but execution
   77958 ** continues straight thru if the expression is true.
   77959 **
   77960 ** If the expression evaluates to NULL (neither true nor false) then
   77961 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   77962 ** is 0.
   77963 */
   77964 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   77965   Vdbe *v = pParse->pVdbe;
   77966   int op = 0;
   77967   int regFree1 = 0;
   77968   int regFree2 = 0;
   77969   int r1, r2;
   77970 
   77971   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   77972   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
   77973   if( pExpr==0 )    return;
   77974 
   77975   /* The value of pExpr->op and op are related as follows:
   77976   **
   77977   **       pExpr->op            op
   77978   **       ---------          ----------
   77979   **       TK_ISNULL          OP_NotNull
   77980   **       TK_NOTNULL         OP_IsNull
   77981   **       TK_NE              OP_Eq
   77982   **       TK_EQ              OP_Ne
   77983   **       TK_GT              OP_Le
   77984   **       TK_LE              OP_Gt
   77985   **       TK_GE              OP_Lt
   77986   **       TK_LT              OP_Ge
   77987   **
   77988   ** For other values of pExpr->op, op is undefined and unused.
   77989   ** The value of TK_ and OP_ constants are arranged such that we
   77990   ** can compute the mapping above using the following expression.
   77991   ** Assert()s verify that the computation is correct.
   77992   */
   77993   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   77994 
   77995   /* Verify correct alignment of TK_ and OP_ constants
   77996   */
   77997   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   77998   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   77999   assert( pExpr->op!=TK_NE || op==OP_Eq );
   78000   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   78001   assert( pExpr->op!=TK_LT || op==OP_Ge );
   78002   assert( pExpr->op!=TK_LE || op==OP_Gt );
   78003   assert( pExpr->op!=TK_GT || op==OP_Le );
   78004   assert( pExpr->op!=TK_GE || op==OP_Lt );
   78005 
   78006   switch( pExpr->op ){
   78007     case TK_AND: {
   78008       testcase( jumpIfNull==0 );
   78009       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   78010       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   78011       break;
   78012     }
   78013     case TK_OR: {
   78014       int d2 = sqlite3VdbeMakeLabel(v);
   78015       testcase( jumpIfNull==0 );
   78016       sqlite3ExprCachePush(pParse);
   78017       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   78018       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   78019       sqlite3VdbeResolveLabel(v, d2);
   78020       sqlite3ExprCachePop(pParse, 1);
   78021       break;
   78022     }
   78023     case TK_NOT: {
   78024       testcase( jumpIfNull==0 );
   78025       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   78026       break;
   78027     }
   78028     case TK_LT:
   78029     case TK_LE:
   78030     case TK_GT:
   78031     case TK_GE:
   78032     case TK_NE:
   78033     case TK_EQ: {
   78034       testcase( op==TK_LT );
   78035       testcase( op==TK_LE );
   78036       testcase( op==TK_GT );
   78037       testcase( op==TK_GE );
   78038       testcase( op==TK_EQ );
   78039       testcase( op==TK_NE );
   78040       testcase( jumpIfNull==0 );
   78041       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78042       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   78043       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   78044                   r1, r2, dest, jumpIfNull);
   78045       testcase( regFree1==0 );
   78046       testcase( regFree2==0 );
   78047       break;
   78048     }
   78049     case TK_IS:
   78050     case TK_ISNOT: {
   78051       testcase( pExpr->op==TK_IS );
   78052       testcase( pExpr->op==TK_ISNOT );
   78053       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78054       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   78055       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   78056       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   78057                   r1, r2, dest, SQLITE_NULLEQ);
   78058       testcase( regFree1==0 );
   78059       testcase( regFree2==0 );
   78060       break;
   78061     }
   78062     case TK_ISNULL:
   78063     case TK_NOTNULL: {
   78064       testcase( op==TK_ISNULL );
   78065       testcase( op==TK_NOTNULL );
   78066       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   78067       sqlite3VdbeAddOp2(v, op, r1, dest);
   78068       testcase( regFree1==0 );
   78069       break;
   78070     }
   78071     case TK_BETWEEN: {
   78072       testcase( jumpIfNull==0 );
   78073       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   78074       break;
   78075     }
   78076 #ifndef SQLITE_OMIT_SUBQUERY
   78077     case TK_IN: {
   78078       if( jumpIfNull ){
   78079         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   78080       }else{
   78081         int destIfNull = sqlite3VdbeMakeLabel(v);
   78082         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   78083         sqlite3VdbeResolveLabel(v, destIfNull);
   78084       }
   78085       break;
   78086     }
   78087 #endif
   78088     default: {
   78089       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   78090       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   78091       testcase( regFree1==0 );
   78092       testcase( jumpIfNull==0 );
   78093       break;
   78094     }
   78095   }
   78096   sqlite3ReleaseTempReg(pParse, regFree1);
   78097   sqlite3ReleaseTempReg(pParse, regFree2);
   78098 }
   78099 
   78100 /*
   78101 ** Do a deep comparison of two expression trees.  Return 0 if the two
   78102 ** expressions are completely identical.  Return 1 if they differ only
   78103 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   78104 ** other than the top-level COLLATE operator.
   78105 **
   78106 ** Sometimes this routine will return 2 even if the two expressions
   78107 ** really are equivalent.  If we cannot prove that the expressions are
   78108 ** identical, we return 2 just to be safe.  So if this routine
   78109 ** returns 2, then you do not really know for certain if the two
   78110 ** expressions are the same.  But if you get a 0 or 1 return, then you
   78111 ** can be sure the expressions are the same.  In the places where
   78112 ** this routine is used, it does not hurt to get an extra 2 - that
   78113 ** just might result in some slightly slower code.  But returning
   78114 ** an incorrect 0 or 1 could lead to a malfunction.
   78115 */
   78116 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
   78117   if( pA==0||pB==0 ){
   78118     return pB==pA ? 0 : 2;
   78119   }
   78120   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
   78121   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
   78122   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
   78123     return 2;
   78124   }
   78125   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   78126   if( pA->op!=pB->op ) return 2;
   78127   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
   78128   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
   78129   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
   78130   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
   78131   if( ExprHasProperty(pA, EP_IntValue) ){
   78132     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
   78133       return 2;
   78134     }
   78135   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
   78136     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
   78137     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
   78138       return 2;
   78139     }
   78140   }
   78141   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
   78142   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
   78143   return 0;
   78144 }
   78145 
   78146 /*
   78147 ** Compare two ExprList objects.  Return 0 if they are identical and
   78148 ** non-zero if they differ in any way.
   78149 **
   78150 ** This routine might return non-zero for equivalent ExprLists.  The
   78151 ** only consequence will be disabled optimizations.  But this routine
   78152 ** must never return 0 if the two ExprList objects are different, or
   78153 ** a malfunction will result.
   78154 **
   78155 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   78156 ** always differs from a non-NULL pointer.
   78157 */
   78158 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
   78159   int i;
   78160   if( pA==0 && pB==0 ) return 0;
   78161   if( pA==0 || pB==0 ) return 1;
   78162   if( pA->nExpr!=pB->nExpr ) return 1;
   78163   for(i=0; i<pA->nExpr; i++){
   78164     Expr *pExprA = pA->a[i].pExpr;
   78165     Expr *pExprB = pB->a[i].pExpr;
   78166     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   78167     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
   78168   }
   78169   return 0;
   78170 }
   78171 
   78172 /*
   78173 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   78174 ** the new element.  Return a negative number if malloc fails.
   78175 */
   78176 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   78177   int i;
   78178   pInfo->aCol = sqlite3ArrayAllocate(
   78179        db,
   78180        pInfo->aCol,
   78181        sizeof(pInfo->aCol[0]),
   78182        &pInfo->nColumn,
   78183        &i
   78184   );
   78185   return i;
   78186 }
   78187 
   78188 /*
   78189 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   78190 ** the new element.  Return a negative number if malloc fails.
   78191 */
   78192 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   78193   int i;
   78194   pInfo->aFunc = sqlite3ArrayAllocate(
   78195        db,
   78196        pInfo->aFunc,
   78197        sizeof(pInfo->aFunc[0]),
   78198        &pInfo->nFunc,
   78199        &i
   78200   );
   78201   return i;
   78202 }
   78203 
   78204 /*
   78205 ** This is the xExprCallback for a tree walker.  It is used to
   78206 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   78207 ** for additional information.
   78208 */
   78209 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   78210   int i;
   78211   NameContext *pNC = pWalker->u.pNC;
   78212   Parse *pParse = pNC->pParse;
   78213   SrcList *pSrcList = pNC->pSrcList;
   78214   AggInfo *pAggInfo = pNC->pAggInfo;
   78215 
   78216   switch( pExpr->op ){
   78217     case TK_AGG_COLUMN:
   78218     case TK_COLUMN: {
   78219       testcase( pExpr->op==TK_AGG_COLUMN );
   78220       testcase( pExpr->op==TK_COLUMN );
   78221       /* Check to see if the column is in one of the tables in the FROM
   78222       ** clause of the aggregate query */
   78223       if( ALWAYS(pSrcList!=0) ){
   78224         struct SrcList_item *pItem = pSrcList->a;
   78225         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   78226           struct AggInfo_col *pCol;
   78227           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   78228           if( pExpr->iTable==pItem->iCursor ){
   78229             /* If we reach this point, it means that pExpr refers to a table
   78230             ** that is in the FROM clause of the aggregate query.
   78231             **
   78232             ** Make an entry for the column in pAggInfo->aCol[] if there
   78233             ** is not an entry there already.
   78234             */
   78235             int k;
   78236             pCol = pAggInfo->aCol;
   78237             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   78238               if( pCol->iTable==pExpr->iTable &&
   78239                   pCol->iColumn==pExpr->iColumn ){
   78240                 break;
   78241               }
   78242             }
   78243             if( (k>=pAggInfo->nColumn)
   78244              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   78245             ){
   78246               pCol = &pAggInfo->aCol[k];
   78247               pCol->pTab = pExpr->pTab;
   78248               pCol->iTable = pExpr->iTable;
   78249               pCol->iColumn = pExpr->iColumn;
   78250               pCol->iMem = ++pParse->nMem;
   78251               pCol->iSorterColumn = -1;
   78252               pCol->pExpr = pExpr;
   78253               if( pAggInfo->pGroupBy ){
   78254                 int j, n;
   78255                 ExprList *pGB = pAggInfo->pGroupBy;
   78256                 struct ExprList_item *pTerm = pGB->a;
   78257                 n = pGB->nExpr;
   78258                 for(j=0; j<n; j++, pTerm++){
   78259                   Expr *pE = pTerm->pExpr;
   78260                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   78261                       pE->iColumn==pExpr->iColumn ){
   78262                     pCol->iSorterColumn = j;
   78263                     break;
   78264                   }
   78265                 }
   78266               }
   78267               if( pCol->iSorterColumn<0 ){
   78268                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   78269               }
   78270             }
   78271             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   78272             ** because it was there before or because we just created it).
   78273             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   78274             ** pAggInfo->aCol[] entry.
   78275             */
   78276             ExprSetIrreducible(pExpr);
   78277             pExpr->pAggInfo = pAggInfo;
   78278             pExpr->op = TK_AGG_COLUMN;
   78279             pExpr->iAgg = (i16)k;
   78280             break;
   78281           } /* endif pExpr->iTable==pItem->iCursor */
   78282         } /* end loop over pSrcList */
   78283       }
   78284       return WRC_Prune;
   78285     }
   78286     case TK_AGG_FUNCTION: {
   78287       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
   78288       ** to be ignored */
   78289       if( pNC->nDepth==0 ){
   78290         /* Check to see if pExpr is a duplicate of another aggregate
   78291         ** function that is already in the pAggInfo structure
   78292         */
   78293         struct AggInfo_func *pItem = pAggInfo->aFunc;
   78294         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   78295           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
   78296             break;
   78297           }
   78298         }
   78299         if( i>=pAggInfo->nFunc ){
   78300           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   78301           */
   78302           u8 enc = ENC(pParse->db);
   78303           i = addAggInfoFunc(pParse->db, pAggInfo);
   78304           if( i>=0 ){
   78305             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   78306             pItem = &pAggInfo->aFunc[i];
   78307             pItem->pExpr = pExpr;
   78308             pItem->iMem = ++pParse->nMem;
   78309             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   78310             pItem->pFunc = sqlite3FindFunction(pParse->db,
   78311                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   78312                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   78313             if( pExpr->flags & EP_Distinct ){
   78314               pItem->iDistinct = pParse->nTab++;
   78315             }else{
   78316               pItem->iDistinct = -1;
   78317             }
   78318           }
   78319         }
   78320         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   78321         */
   78322         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   78323         ExprSetIrreducible(pExpr);
   78324         pExpr->iAgg = (i16)i;
   78325         pExpr->pAggInfo = pAggInfo;
   78326         return WRC_Prune;
   78327       }
   78328     }
   78329   }
   78330   return WRC_Continue;
   78331 }
   78332 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   78333   NameContext *pNC = pWalker->u.pNC;
   78334   if( pNC->nDepth==0 ){
   78335     pNC->nDepth++;
   78336     sqlite3WalkSelect(pWalker, pSelect);
   78337     pNC->nDepth--;
   78338     return WRC_Prune;
   78339   }else{
   78340     return WRC_Continue;
   78341   }
   78342 }
   78343 
   78344 /*
   78345 ** Analyze the given expression looking for aggregate functions and
   78346 ** for variables that need to be added to the pParse->aAgg[] array.
   78347 ** Make additional entries to the pParse->aAgg[] array as necessary.
   78348 **
   78349 ** This routine should only be called after the expression has been
   78350 ** analyzed by sqlite3ResolveExprNames().
   78351 */
   78352 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   78353   Walker w;
   78354   w.xExprCallback = analyzeAggregate;
   78355   w.xSelectCallback = analyzeAggregatesInSelect;
   78356   w.u.pNC = pNC;
   78357   assert( pNC->pSrcList!=0 );
   78358   sqlite3WalkExpr(&w, pExpr);
   78359 }
   78360 
   78361 /*
   78362 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   78363 ** expression list.  Return the number of errors.
   78364 **
   78365 ** If an error is found, the analysis is cut short.
   78366 */
   78367 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   78368   struct ExprList_item *pItem;
   78369   int i;
   78370   if( pList ){
   78371     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   78372       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   78373     }
   78374   }
   78375 }
   78376 
   78377 /*
   78378 ** Allocate a single new register for use to hold some intermediate result.
   78379 */
   78380 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   78381   if( pParse->nTempReg==0 ){
   78382     return ++pParse->nMem;
   78383   }
   78384   return pParse->aTempReg[--pParse->nTempReg];
   78385 }
   78386 
   78387 /*
   78388 ** Deallocate a register, making available for reuse for some other
   78389 ** purpose.
   78390 **
   78391 ** If a register is currently being used by the column cache, then
   78392 ** the dallocation is deferred until the column cache line that uses
   78393 ** the register becomes stale.
   78394 */
   78395 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   78396   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   78397     int i;
   78398     struct yColCache *p;
   78399     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   78400       if( p->iReg==iReg ){
   78401         p->tempReg = 1;
   78402         return;
   78403       }
   78404     }
   78405     pParse->aTempReg[pParse->nTempReg++] = iReg;
   78406   }
   78407 }
   78408 
   78409 /*
   78410 ** Allocate or deallocate a block of nReg consecutive registers
   78411 */
   78412 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   78413   int i, n;
   78414   i = pParse->iRangeReg;
   78415   n = pParse->nRangeReg;
   78416   if( nReg<=n ){
   78417     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   78418     pParse->iRangeReg += nReg;
   78419     pParse->nRangeReg -= nReg;
   78420   }else{
   78421     i = pParse->nMem+1;
   78422     pParse->nMem += nReg;
   78423   }
   78424   return i;
   78425 }
   78426 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   78427   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   78428   if( nReg>pParse->nRangeReg ){
   78429     pParse->nRangeReg = nReg;
   78430     pParse->iRangeReg = iReg;
   78431   }
   78432 }
   78433 
   78434 /*
   78435 ** Mark all temporary registers as being unavailable for reuse.
   78436 */
   78437 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
   78438   pParse->nTempReg = 0;
   78439   pParse->nRangeReg = 0;
   78440 }
   78441 
   78442 /************** End of expr.c ************************************************/
   78443 /************** Begin file alter.c *******************************************/
   78444 /*
   78445 ** 2005 February 15
   78446 **
   78447 ** The author disclaims copyright to this source code.  In place of
   78448 ** a legal notice, here is a blessing:
   78449 **
   78450 **    May you do good and not evil.
   78451 **    May you find forgiveness for yourself and forgive others.
   78452 **    May you share freely, never taking more than you give.
   78453 **
   78454 *************************************************************************
   78455 ** This file contains C code routines that used to generate VDBE code
   78456 ** that implements the ALTER TABLE command.
   78457 */
   78458 
   78459 /*
   78460 ** The code in this file only exists if we are not omitting the
   78461 ** ALTER TABLE logic from the build.
   78462 */
   78463 #ifndef SQLITE_OMIT_ALTERTABLE
   78464 
   78465 
   78466 /*
   78467 ** This function is used by SQL generated to implement the
   78468 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   78469 ** CREATE INDEX command. The second is a table name. The table name in
   78470 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   78471 ** argument and the result returned. Examples:
   78472 **
   78473 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   78474 **     -> 'CREATE TABLE def(a, b, c)'
   78475 **
   78476 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   78477 **     -> 'CREATE INDEX i ON def(a, b, c)'
   78478 */
   78479 static void renameTableFunc(
   78480   sqlite3_context *context,
   78481   int NotUsed,
   78482   sqlite3_value **argv
   78483 ){
   78484   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   78485   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   78486 
   78487   int token;
   78488   Token tname;
   78489   unsigned char const *zCsr = zSql;
   78490   int len = 0;
   78491   char *zRet;
   78492 
   78493   sqlite3 *db = sqlite3_context_db_handle(context);
   78494 
   78495   UNUSED_PARAMETER(NotUsed);
   78496 
   78497   /* The principle used to locate the table name in the CREATE TABLE
   78498   ** statement is that the table name is the first non-space token that
   78499   ** is immediately followed by a TK_LP or TK_USING token.
   78500   */
   78501   if( zSql ){
   78502     do {
   78503       if( !*zCsr ){
   78504         /* Ran out of input before finding an opening bracket. Return NULL. */
   78505         return;
   78506       }
   78507 
   78508       /* Store the token that zCsr points to in tname. */
   78509       tname.z = (char*)zCsr;
   78510       tname.n = len;
   78511 
   78512       /* Advance zCsr to the next token. Store that token type in 'token',
   78513       ** and its length in 'len' (to be used next iteration of this loop).
   78514       */
   78515       do {
   78516         zCsr += len;
   78517         len = sqlite3GetToken(zCsr, &token);
   78518       } while( token==TK_SPACE );
   78519       assert( len>0 );
   78520     } while( token!=TK_LP && token!=TK_USING );
   78521 
   78522     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   78523        zTableName, tname.z+tname.n);
   78524     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   78525   }
   78526 }
   78527 
   78528 /*
   78529 ** This C function implements an SQL user function that is used by SQL code
   78530 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   78531 ** of any foreign key constraints that use the table being renamed as the
   78532 ** parent table. It is passed three arguments:
   78533 **
   78534 **   1) The complete text of the CREATE TABLE statement being modified,
   78535 **   2) The old name of the table being renamed, and
   78536 **   3) The new name of the table being renamed.
   78537 **
   78538 ** It returns the new CREATE TABLE statement. For example:
   78539 **
   78540 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   78541 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   78542 */
   78543 #ifndef SQLITE_OMIT_FOREIGN_KEY
   78544 static void renameParentFunc(
   78545   sqlite3_context *context,
   78546   int NotUsed,
   78547   sqlite3_value **argv
   78548 ){
   78549   sqlite3 *db = sqlite3_context_db_handle(context);
   78550   char *zOutput = 0;
   78551   char *zResult;
   78552   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   78553   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   78554   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   78555 
   78556   unsigned const char *z;         /* Pointer to token */
   78557   int n;                          /* Length of token z */
   78558   int token;                      /* Type of token */
   78559 
   78560   UNUSED_PARAMETER(NotUsed);
   78561   for(z=zInput; *z; z=z+n){
   78562     n = sqlite3GetToken(z, &token);
   78563     if( token==TK_REFERENCES ){
   78564       char *zParent;
   78565       do {
   78566         z += n;
   78567         n = sqlite3GetToken(z, &token);
   78568       }while( token==TK_SPACE );
   78569 
   78570       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   78571       if( zParent==0 ) break;
   78572       sqlite3Dequote(zParent);
   78573       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   78574         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   78575             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
   78576         );
   78577         sqlite3DbFree(db, zOutput);
   78578         zOutput = zOut;
   78579         zInput = &z[n];
   78580       }
   78581       sqlite3DbFree(db, zParent);
   78582     }
   78583   }
   78584 
   78585   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   78586   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   78587   sqlite3DbFree(db, zOutput);
   78588 }
   78589 #endif
   78590 
   78591 #ifndef SQLITE_OMIT_TRIGGER
   78592 /* This function is used by SQL generated to implement the
   78593 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   78594 ** statement. The second is a table name. The table name in the CREATE
   78595 ** TRIGGER statement is replaced with the third argument and the result
   78596 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   78597 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   78598 */
   78599 static void renameTriggerFunc(
   78600   sqlite3_context *context,
   78601   int NotUsed,
   78602   sqlite3_value **argv
   78603 ){
   78604   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   78605   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   78606 
   78607   int token;
   78608   Token tname;
   78609   int dist = 3;
   78610   unsigned char const *zCsr = zSql;
   78611   int len = 0;
   78612   char *zRet;
   78613   sqlite3 *db = sqlite3_context_db_handle(context);
   78614 
   78615   UNUSED_PARAMETER(NotUsed);
   78616 
   78617   /* The principle used to locate the table name in the CREATE TRIGGER
   78618   ** statement is that the table name is the first token that is immediatedly
   78619   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   78620   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   78621   */
   78622   if( zSql ){
   78623     do {
   78624 
   78625       if( !*zCsr ){
   78626         /* Ran out of input before finding the table name. Return NULL. */
   78627         return;
   78628       }
   78629 
   78630       /* Store the token that zCsr points to in tname. */
   78631       tname.z = (char*)zCsr;
   78632       tname.n = len;
   78633 
   78634       /* Advance zCsr to the next token. Store that token type in 'token',
   78635       ** and its length in 'len' (to be used next iteration of this loop).
   78636       */
   78637       do {
   78638         zCsr += len;
   78639         len = sqlite3GetToken(zCsr, &token);
   78640       }while( token==TK_SPACE );
   78641       assert( len>0 );
   78642 
   78643       /* Variable 'dist' stores the number of tokens read since the most
   78644       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   78645       ** token is read and 'dist' equals 2, the condition stated above
   78646       ** to be met.
   78647       **
   78648       ** Note that ON cannot be a database, table or column name, so
   78649       ** there is no need to worry about syntax like
   78650       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   78651       */
   78652       dist++;
   78653       if( token==TK_DOT || token==TK_ON ){
   78654         dist = 0;
   78655       }
   78656     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   78657 
   78658     /* Variable tname now contains the token that is the old table-name
   78659     ** in the CREATE TRIGGER statement.
   78660     */
   78661     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   78662        zTableName, tname.z+tname.n);
   78663     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   78664   }
   78665 }
   78666 #endif   /* !SQLITE_OMIT_TRIGGER */
   78667 
   78668 /*
   78669 ** Register built-in functions used to help implement ALTER TABLE
   78670 */
   78671 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   78672   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
   78673     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   78674 #ifndef SQLITE_OMIT_TRIGGER
   78675     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   78676 #endif
   78677 #ifndef SQLITE_OMIT_FOREIGN_KEY
   78678     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   78679 #endif
   78680   };
   78681   int i;
   78682   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   78683   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
   78684 
   78685   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
   78686     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   78687   }
   78688 }
   78689 
   78690 /*
   78691 ** This function is used to create the text of expressions of the form:
   78692 **
   78693 **   name=<constant1> OR name=<constant2> OR ...
   78694 **
   78695 ** If argument zWhere is NULL, then a pointer string containing the text
   78696 ** "name=<constant>" is returned, where <constant> is the quoted version
   78697 ** of the string passed as argument zConstant. The returned buffer is
   78698 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   78699 ** caller to ensure that it is eventually freed.
   78700 **
   78701 ** If argument zWhere is not NULL, then the string returned is
   78702 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   78703 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   78704 **
   78705 */
   78706 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   78707   char *zNew;
   78708   if( !zWhere ){
   78709     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   78710   }else{
   78711     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   78712     sqlite3DbFree(db, zWhere);
   78713   }
   78714   return zNew;
   78715 }
   78716 
   78717 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   78718 /*
   78719 ** Generate the text of a WHERE expression which can be used to select all
   78720 ** tables that have foreign key constraints that refer to table pTab (i.e.
   78721 ** constraints for which pTab is the parent table) from the sqlite_master
   78722 ** table.
   78723 */
   78724 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   78725   FKey *p;
   78726   char *zWhere = 0;
   78727   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   78728     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   78729   }
   78730   return zWhere;
   78731 }
   78732 #endif
   78733 
   78734 /*
   78735 ** Generate the text of a WHERE expression which can be used to select all
   78736 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   78737 ** table pTab has no temporary triggers, or is itself stored in the
   78738 ** temporary database, NULL is returned.
   78739 */
   78740 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   78741   Trigger *pTrig;
   78742   char *zWhere = 0;
   78743   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   78744 
   78745   /* If the table is not located in the temp-db (in which case NULL is
   78746   ** returned, loop through the tables list of triggers. For each trigger
   78747   ** that is not part of the temp-db schema, add a clause to the WHERE
   78748   ** expression being built up in zWhere.
   78749   */
   78750   if( pTab->pSchema!=pTempSchema ){
   78751     sqlite3 *db = pParse->db;
   78752     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   78753       if( pTrig->pSchema==pTempSchema ){
   78754         zWhere = whereOrName(db, zWhere, pTrig->zName);
   78755       }
   78756     }
   78757   }
   78758   if( zWhere ){
   78759     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   78760     sqlite3DbFree(pParse->db, zWhere);
   78761     zWhere = zNew;
   78762   }
   78763   return zWhere;
   78764 }
   78765 
   78766 /*
   78767 ** Generate code to drop and reload the internal representation of table
   78768 ** pTab from the database, including triggers and temporary triggers.
   78769 ** Argument zName is the name of the table in the database schema at
   78770 ** the time the generated code is executed. This can be different from
   78771 ** pTab->zName if this function is being called to code part of an
   78772 ** "ALTER TABLE RENAME TO" statement.
   78773 */
   78774 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   78775   Vdbe *v;
   78776   char *zWhere;
   78777   int iDb;                   /* Index of database containing pTab */
   78778 #ifndef SQLITE_OMIT_TRIGGER
   78779   Trigger *pTrig;
   78780 #endif
   78781 
   78782   v = sqlite3GetVdbe(pParse);
   78783   if( NEVER(v==0) ) return;
   78784   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   78785   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   78786   assert( iDb>=0 );
   78787 
   78788 #ifndef SQLITE_OMIT_TRIGGER
   78789   /* Drop any table triggers from the internal schema. */
   78790   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   78791     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   78792     assert( iTrigDb==iDb || iTrigDb==1 );
   78793     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   78794   }
   78795 #endif
   78796 
   78797   /* Drop the table and index from the internal schema.  */
   78798   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   78799 
   78800   /* Reload the table, index and permanent trigger schemas. */
   78801   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   78802   if( !zWhere ) return;
   78803   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   78804 
   78805 #ifndef SQLITE_OMIT_TRIGGER
   78806   /* Now, if the table is not stored in the temp database, reload any temp
   78807   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   78808   */
   78809   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   78810     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
   78811   }
   78812 #endif
   78813 }
   78814 
   78815 /*
   78816 ** Parameter zName is the name of a table that is about to be altered
   78817 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
   78818 ** If the table is a system table, this function leaves an error message
   78819 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
   78820 **
   78821 ** Or, if zName is not a system table, zero is returned.
   78822 */
   78823 static int isSystemTable(Parse *pParse, const char *zName){
   78824   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   78825     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
   78826     return 1;
   78827   }
   78828   return 0;
   78829 }
   78830 
   78831 /*
   78832 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   78833 ** command.
   78834 */
   78835 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   78836   Parse *pParse,            /* Parser context. */
   78837   SrcList *pSrc,            /* The table to rename. */
   78838   Token *pName              /* The new table name. */
   78839 ){
   78840   int iDb;                  /* Database that contains the table */
   78841   char *zDb;                /* Name of database iDb */
   78842   Table *pTab;              /* Table being renamed */
   78843   char *zName = 0;          /* NULL-terminated version of pName */
   78844   sqlite3 *db = pParse->db; /* Database connection */
   78845   int nTabName;             /* Number of UTF-8 characters in zTabName */
   78846   const char *zTabName;     /* Original name of the table */
   78847   Vdbe *v;
   78848 #ifndef SQLITE_OMIT_TRIGGER
   78849   char *zWhere = 0;         /* Where clause to locate temp triggers */
   78850 #endif
   78851   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   78852   int savedDbFlags;         /* Saved value of db->flags */
   78853 
   78854   savedDbFlags = db->flags;
   78855   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   78856   assert( pSrc->nSrc==1 );
   78857   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   78858 
   78859   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   78860   if( !pTab ) goto exit_rename_table;
   78861   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   78862   zDb = db->aDb[iDb].zName;
   78863   db->flags |= SQLITE_PreferBuiltin;
   78864 
   78865   /* Get a NULL terminated version of the new table name. */
   78866   zName = sqlite3NameFromToken(db, pName);
   78867   if( !zName ) goto exit_rename_table;
   78868 
   78869   /* Check that a table or index named 'zName' does not already exist
   78870   ** in database iDb. If so, this is an error.
   78871   */
   78872   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   78873     sqlite3ErrorMsg(pParse,
   78874         "there is already another table or index with this name: %s", zName);
   78875     goto exit_rename_table;
   78876   }
   78877 
   78878   /* Make sure it is not a system table being altered, or a reserved name
   78879   ** that the table is being renamed to.
   78880   */
   78881   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   78882     goto exit_rename_table;
   78883   }
   78884   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
   78885     exit_rename_table;
   78886   }
   78887 
   78888 #ifndef SQLITE_OMIT_VIEW
   78889   if( pTab->pSelect ){
   78890     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   78891     goto exit_rename_table;
   78892   }
   78893 #endif
   78894 
   78895 #ifndef SQLITE_OMIT_AUTHORIZATION
   78896   /* Invoke the authorization callback. */
   78897   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   78898     goto exit_rename_table;
   78899   }
   78900 #endif
   78901 
   78902 #ifndef SQLITE_OMIT_VIRTUALTABLE
   78903   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   78904     goto exit_rename_table;
   78905   }
   78906   if( IsVirtual(pTab) ){
   78907     pVTab = sqlite3GetVTable(db, pTab);
   78908     if( pVTab->pVtab->pModule->xRename==0 ){
   78909       pVTab = 0;
   78910     }
   78911   }
   78912 #endif
   78913 
   78914   /* Begin a transaction and code the VerifyCookie for database iDb.
   78915   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   78916   ** schema). Open a statement transaction if the table is a virtual
   78917   ** table.
   78918   */
   78919   v = sqlite3GetVdbe(pParse);
   78920   if( v==0 ){
   78921     goto exit_rename_table;
   78922   }
   78923   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   78924   sqlite3ChangeCookie(pParse, iDb);
   78925 
   78926   /* If this is a virtual table, invoke the xRename() function if
   78927   ** one is defined. The xRename() callback will modify the names
   78928   ** of any resources used by the v-table implementation (including other
   78929   ** SQLite tables) that are identified by the name of the virtual table.
   78930   */
   78931 #ifndef SQLITE_OMIT_VIRTUALTABLE
   78932   if( pVTab ){
   78933     int i = ++pParse->nMem;
   78934     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   78935     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   78936     sqlite3MayAbort(pParse);
   78937   }
   78938 #endif
   78939 
   78940   /* figure out how many UTF-8 characters are in zName */
   78941   zTabName = pTab->zName;
   78942   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   78943 
   78944 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   78945   if( db->flags&SQLITE_ForeignKeys ){
   78946     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   78947     ** statements corresponding to all child tables of foreign key constraints
   78948     ** for which the renamed table is the parent table.  */
   78949     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   78950       sqlite3NestedParse(pParse,
   78951           "UPDATE \"%w\".%s SET "
   78952               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   78953               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
   78954       sqlite3DbFree(db, zWhere);
   78955     }
   78956   }
   78957 #endif
   78958 
   78959   /* Modify the sqlite_master table to use the new table name. */
   78960   sqlite3NestedParse(pParse,
   78961       "UPDATE %Q.%s SET "
   78962 #ifdef SQLITE_OMIT_TRIGGER
   78963           "sql = sqlite_rename_table(sql, %Q), "
   78964 #else
   78965           "sql = CASE "
   78966             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   78967             "ELSE sqlite_rename_table(sql, %Q) END, "
   78968 #endif
   78969           "tbl_name = %Q, "
   78970           "name = CASE "
   78971             "WHEN type='table' THEN %Q "
   78972             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   78973              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   78974             "ELSE name END "
   78975       "WHERE tbl_name=%Q COLLATE nocase AND "
   78976           "(type='table' OR type='index' OR type='trigger');",
   78977       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   78978 #ifndef SQLITE_OMIT_TRIGGER
   78979       zName,
   78980 #endif
   78981       zName, nTabName, zTabName
   78982   );
   78983 
   78984 #ifndef SQLITE_OMIT_AUTOINCREMENT
   78985   /* If the sqlite_sequence table exists in this database, then update
   78986   ** it with the new table name.
   78987   */
   78988   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   78989     sqlite3NestedParse(pParse,
   78990         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   78991         zDb, zName, pTab->zName);
   78992   }
   78993 #endif
   78994 
   78995 #ifndef SQLITE_OMIT_TRIGGER
   78996   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   78997   ** table. Don't do this if the table being ALTERed is itself located in
   78998   ** the temp database.
   78999   */
   79000   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   79001     sqlite3NestedParse(pParse,
   79002         "UPDATE sqlite_temp_master SET "
   79003             "sql = sqlite_rename_trigger(sql, %Q), "
   79004             "tbl_name = %Q "
   79005             "WHERE %s;", zName, zName, zWhere);
   79006     sqlite3DbFree(db, zWhere);
   79007   }
   79008 #endif
   79009 
   79010 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   79011   if( db->flags&SQLITE_ForeignKeys ){
   79012     FKey *p;
   79013     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   79014       Table *pFrom = p->pFrom;
   79015       if( pFrom!=pTab ){
   79016         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   79017       }
   79018     }
   79019   }
   79020 #endif
   79021 
   79022   /* Drop and reload the internal table schema. */
   79023   reloadTableSchema(pParse, pTab, zName);
   79024 
   79025 exit_rename_table:
   79026   sqlite3SrcListDelete(db, pSrc);
   79027   sqlite3DbFree(db, zName);
   79028   db->flags = savedDbFlags;
   79029 }
   79030 
   79031 
   79032 /*
   79033 ** Generate code to make sure the file format number is at least minFormat.
   79034 ** The generated code will increase the file format number if necessary.
   79035 */
   79036 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   79037   Vdbe *v;
   79038   v = sqlite3GetVdbe(pParse);
   79039   /* The VDBE should have been allocated before this routine is called.
   79040   ** If that allocation failed, we would have quit before reaching this
   79041   ** point */
   79042   if( ALWAYS(v) ){
   79043     int r1 = sqlite3GetTempReg(pParse);
   79044     int r2 = sqlite3GetTempReg(pParse);
   79045     int j1;
   79046     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   79047     sqlite3VdbeUsesBtree(v, iDb);
   79048     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   79049     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   79050     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   79051     sqlite3VdbeJumpHere(v, j1);
   79052     sqlite3ReleaseTempReg(pParse, r1);
   79053     sqlite3ReleaseTempReg(pParse, r2);
   79054   }
   79055 }
   79056 
   79057 /*
   79058 ** This function is called after an "ALTER TABLE ... ADD" statement
   79059 ** has been parsed. Argument pColDef contains the text of the new
   79060 ** column definition.
   79061 **
   79062 ** The Table structure pParse->pNewTable was extended to include
   79063 ** the new column during parsing.
   79064 */
   79065 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   79066   Table *pNew;              /* Copy of pParse->pNewTable */
   79067   Table *pTab;              /* Table being altered */
   79068   int iDb;                  /* Database number */
   79069   const char *zDb;          /* Database name */
   79070   const char *zTab;         /* Table name */
   79071   char *zCol;               /* Null-terminated column definition */
   79072   Column *pCol;             /* The new column */
   79073   Expr *pDflt;              /* Default value for the new column */
   79074   sqlite3 *db;              /* The database connection; */
   79075 
   79076   db = pParse->db;
   79077   if( pParse->nErr || db->mallocFailed ) return;
   79078   pNew = pParse->pNewTable;
   79079   assert( pNew );
   79080 
   79081   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79082   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   79083   zDb = db->aDb[iDb].zName;
   79084   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   79085   pCol = &pNew->aCol[pNew->nCol-1];
   79086   pDflt = pCol->pDflt;
   79087   pTab = sqlite3FindTable(db, zTab, zDb);
   79088   assert( pTab );
   79089 
   79090 #ifndef SQLITE_OMIT_AUTHORIZATION
   79091   /* Invoke the authorization callback. */
   79092   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   79093     return;
   79094   }
   79095 #endif
   79096 
   79097   /* If the default value for the new column was specified with a
   79098   ** literal NULL, then set pDflt to 0. This simplifies checking
   79099   ** for an SQL NULL default below.
   79100   */
   79101   if( pDflt && pDflt->op==TK_NULL ){
   79102     pDflt = 0;
   79103   }
   79104 
   79105   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   79106   ** If there is a NOT NULL constraint, then the default value for the
   79107   ** column must not be NULL.
   79108   */
   79109   if( pCol->isPrimKey ){
   79110     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   79111     return;
   79112   }
   79113   if( pNew->pIndex ){
   79114     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   79115     return;
   79116   }
   79117   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   79118     sqlite3ErrorMsg(pParse,
   79119         "Cannot add a REFERENCES column with non-NULL default value");
   79120     return;
   79121   }
   79122   if( pCol->notNull && !pDflt ){
   79123     sqlite3ErrorMsg(pParse,
   79124         "Cannot add a NOT NULL column with default value NULL");
   79125     return;
   79126   }
   79127 
   79128   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   79129   ** can handle (i.e. not CURRENT_TIME etc.)
   79130   */
   79131   if( pDflt ){
   79132     sqlite3_value *pVal;
   79133     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   79134       db->mallocFailed = 1;
   79135       return;
   79136     }
   79137     if( !pVal ){
   79138       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   79139       return;
   79140     }
   79141     sqlite3ValueFree(pVal);
   79142   }
   79143 
   79144   /* Modify the CREATE TABLE statement. */
   79145   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   79146   if( zCol ){
   79147     char *zEnd = &zCol[pColDef->n-1];
   79148     int savedDbFlags = db->flags;
   79149     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   79150       *zEnd-- = '\0';
   79151     }
   79152     db->flags |= SQLITE_PreferBuiltin;
   79153     sqlite3NestedParse(pParse,
   79154         "UPDATE \"%w\".%s SET "
   79155           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   79156         "WHERE type = 'table' AND name = %Q",
   79157       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   79158       zTab
   79159     );
   79160     sqlite3DbFree(db, zCol);
   79161     db->flags = savedDbFlags;
   79162   }
   79163 
   79164   /* If the default value of the new column is NULL, then set the file
   79165   ** format to 2. If the default value of the new column is not NULL,
   79166   ** the file format becomes 3.
   79167   */
   79168   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   79169 
   79170   /* Reload the schema of the modified table. */
   79171   reloadTableSchema(pParse, pTab, pTab->zName);
   79172 }
   79173 
   79174 /*
   79175 ** This function is called by the parser after the table-name in
   79176 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   79177 ** pSrc is the full-name of the table being altered.
   79178 **
   79179 ** This routine makes a (partial) copy of the Table structure
   79180 ** for the table being altered and sets Parse.pNewTable to point
   79181 ** to it. Routines called by the parser as the column definition
   79182 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   79183 ** the copy. The copy of the Table structure is deleted by tokenize.c
   79184 ** after parsing is finished.
   79185 **
   79186 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   79187 ** coding the "ALTER TABLE ... ADD" statement.
   79188 */
   79189 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   79190   Table *pNew;
   79191   Table *pTab;
   79192   Vdbe *v;
   79193   int iDb;
   79194   int i;
   79195   int nAlloc;
   79196   sqlite3 *db = pParse->db;
   79197 
   79198   /* Look up the table being altered. */
   79199   assert( pParse->pNewTable==0 );
   79200   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79201   if( db->mallocFailed ) goto exit_begin_add_column;
   79202   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   79203   if( !pTab ) goto exit_begin_add_column;
   79204 
   79205 #ifndef SQLITE_OMIT_VIRTUALTABLE
   79206   if( IsVirtual(pTab) ){
   79207     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   79208     goto exit_begin_add_column;
   79209   }
   79210 #endif
   79211 
   79212   /* Make sure this is not an attempt to ALTER a view. */
   79213   if( pTab->pSelect ){
   79214     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   79215     goto exit_begin_add_column;
   79216   }
   79217   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
   79218     goto exit_begin_add_column;
   79219   }
   79220 
   79221   assert( pTab->addColOffset>0 );
   79222   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79223 
   79224   /* Put a copy of the Table struct in Parse.pNewTable for the
   79225   ** sqlite3AddColumn() function and friends to modify.  But modify
   79226   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   79227   ** prefix, we insure that the name will not collide with an existing
   79228   ** table because user table are not allowed to have the "sqlite_"
   79229   ** prefix on their name.
   79230   */
   79231   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   79232   if( !pNew ) goto exit_begin_add_column;
   79233   pParse->pNewTable = pNew;
   79234   pNew->nRef = 1;
   79235   pNew->nCol = pTab->nCol;
   79236   assert( pNew->nCol>0 );
   79237   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   79238   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   79239   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   79240   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   79241   if( !pNew->aCol || !pNew->zName ){
   79242     db->mallocFailed = 1;
   79243     goto exit_begin_add_column;
   79244   }
   79245   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   79246   for(i=0; i<pNew->nCol; i++){
   79247     Column *pCol = &pNew->aCol[i];
   79248     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   79249     pCol->zColl = 0;
   79250     pCol->zType = 0;
   79251     pCol->pDflt = 0;
   79252     pCol->zDflt = 0;
   79253   }
   79254   pNew->pSchema = db->aDb[iDb].pSchema;
   79255   pNew->addColOffset = pTab->addColOffset;
   79256   pNew->nRef = 1;
   79257 
   79258   /* Begin a transaction and increment the schema cookie.  */
   79259   sqlite3BeginWriteOperation(pParse, 0, iDb);
   79260   v = sqlite3GetVdbe(pParse);
   79261   if( !v ) goto exit_begin_add_column;
   79262   sqlite3ChangeCookie(pParse, iDb);
   79263 
   79264 exit_begin_add_column:
   79265   sqlite3SrcListDelete(db, pSrc);
   79266   return;
   79267 }
   79268 #endif  /* SQLITE_ALTER_TABLE */
   79269 
   79270 /************** End of alter.c ***********************************************/
   79271 /************** Begin file analyze.c *****************************************/
   79272 /*
   79273 ** 2005 July 8
   79274 **
   79275 ** The author disclaims copyright to this source code.  In place of
   79276 ** a legal notice, here is a blessing:
   79277 **
   79278 **    May you do good and not evil.
   79279 **    May you find forgiveness for yourself and forgive others.
   79280 **    May you share freely, never taking more than you give.
   79281 **
   79282 *************************************************************************
   79283 ** This file contains code associated with the ANALYZE command.
   79284 **
   79285 ** The ANALYZE command gather statistics about the content of tables
   79286 ** and indices.  These statistics are made available to the query planner
   79287 ** to help it make better decisions about how to perform queries.
   79288 **
   79289 ** The following system tables are or have been supported:
   79290 **
   79291 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
   79292 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
   79293 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
   79294 **
   79295 ** Additional tables might be added in future releases of SQLite.
   79296 ** The sqlite_stat2 table is not created or used unless the SQLite version
   79297 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
   79298 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
   79299 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
   79300 ** created and used by SQLite versions 3.7.9 and later and with
   79301 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
   79302 ** is a superset of sqlite_stat2.
   79303 **
   79304 ** Format of sqlite_stat1:
   79305 **
   79306 ** There is normally one row per index, with the index identified by the
   79307 ** name in the idx column.  The tbl column is the name of the table to
   79308 ** which the index belongs.  In each such row, the stat column will be
   79309 ** a string consisting of a list of integers.  The first integer in this
   79310 ** list is the number of rows in the index and in the table.  The second
   79311 ** integer is the average number of rows in the index that have the same
   79312 ** value in the first column of the index.  The third integer is the average
   79313 ** number of rows in the index that have the same value for the first two
   79314 ** columns.  The N-th integer (for N>1) is the average number of rows in
   79315 ** the index which have the same value for the first N-1 columns.  For
   79316 ** a K-column index, there will be K+1 integers in the stat column.  If
   79317 ** the index is unique, then the last integer will be 1.
   79318 **
   79319 ** The list of integers in the stat column can optionally be followed
   79320 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
   79321 ** must be separated from the last integer by a single space.  If the
   79322 ** "unordered" keyword is present, then the query planner assumes that
   79323 ** the index is unordered and will not use the index for a range query.
   79324 **
   79325 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
   79326 ** column contains a single integer which is the (estimated) number of
   79327 ** rows in the table identified by sqlite_stat1.tbl.
   79328 **
   79329 ** Format of sqlite_stat2:
   79330 **
   79331 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
   79332 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
   79333 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
   79334 ** about the distribution of keys within an index.  The index is identified by
   79335 ** the "idx" column and the "tbl" column is the name of the table to which
   79336 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
   79337 ** table for each index.
   79338 **
   79339 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
   79340 ** inclusive are samples of the left-most key value in the index taken at
   79341 ** evenly spaced points along the index.  Let the number of samples be S
   79342 ** (10 in the standard build) and let C be the number of rows in the index.
   79343 ** Then the sampled rows are given by:
   79344 **
   79345 **     rownumber = (i*C*2 + C)/(S*2)
   79346 **
   79347 ** For i between 0 and S-1.  Conceptually, the index space is divided into
   79348 ** S uniform buckets and the samples are the middle row from each bucket.
   79349 **
   79350 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
   79351 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
   79352 ** writes the sqlite_stat2 table.  This version of SQLite only supports
   79353 ** sqlite_stat3.
   79354 **
   79355 ** Format for sqlite_stat3:
   79356 **
   79357 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
   79358 ** used to avoid compatibility problems.
   79359 **
   79360 ** The format of the sqlite_stat3 table is similar to the format of
   79361 ** the sqlite_stat2 table.  There are multiple entries for each index.
   79362 ** The idx column names the index and the tbl column is the table of the
   79363 ** index.  If the idx and tbl columns are the same, then the sample is
   79364 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
   79365 ** the left-most column of the index.  The nEq column is the approximate
   79366 ** number of entires in the index whose left-most column exactly matches
   79367 ** the sample.  nLt is the approximate number of entires whose left-most
   79368 ** column is less than the sample.  The nDLt column is the approximate
   79369 ** number of distinct left-most entries in the index that are less than
   79370 ** the sample.
   79371 **
   79372 ** Future versions of SQLite might change to store a string containing
   79373 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
   79374 ** integer will be the number of prior index entires that are distinct in
   79375 ** the left-most column.  The second integer will be the number of prior index
   79376 ** entries that are distinct in the first two columns.  The third integer
   79377 ** will be the number of prior index entries that are distinct in the first
   79378 ** three columns.  And so forth.  With that extension, the nDLt field is
   79379 ** similar in function to the sqlite_stat1.stat field.
   79380 **
   79381 ** There can be an arbitrary number of sqlite_stat3 entries per index.
   79382 ** The ANALYZE command will typically generate sqlite_stat3 tables
   79383 ** that contain between 10 and 40 samples which are distributed across
   79384 ** the key space, though not uniformly, and which include samples with
   79385 ** largest possible nEq values.
   79386 */
   79387 #ifndef SQLITE_OMIT_ANALYZE
   79388 
   79389 /*
   79390 ** This routine generates code that opens the sqlite_stat1 table for
   79391 ** writing with cursor iStatCur. If the library was built with the
   79392 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
   79393 ** opened for writing using cursor (iStatCur+1)
   79394 **
   79395 ** If the sqlite_stat1 tables does not previously exist, it is created.
   79396 ** Similarly, if the sqlite_stat3 table does not exist and the library
   79397 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
   79398 **
   79399 ** Argument zWhere may be a pointer to a buffer containing a table name,
   79400 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   79401 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
   79402 ** with the named table are deleted. If zWhere==0, then code is generated
   79403 ** to delete all stat table entries.
   79404 */
   79405 static void openStatTable(
   79406   Parse *pParse,          /* Parsing context */
   79407   int iDb,                /* The database we are looking in */
   79408   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   79409   const char *zWhere,     /* Delete entries for this table or index */
   79410   const char *zWhereType  /* Either "tbl" or "idx" */
   79411 ){
   79412   static const struct {
   79413     const char *zName;
   79414     const char *zCols;
   79415   } aTable[] = {
   79416     { "sqlite_stat1", "tbl,idx,stat" },
   79417 #ifdef SQLITE_ENABLE_STAT3
   79418     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
   79419 #endif
   79420   };
   79421 
   79422   int aRoot[] = {0, 0};
   79423   u8 aCreateTbl[] = {0, 0};
   79424 
   79425   int i;
   79426   sqlite3 *db = pParse->db;
   79427   Db *pDb;
   79428   Vdbe *v = sqlite3GetVdbe(pParse);
   79429   if( v==0 ) return;
   79430   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79431   assert( sqlite3VdbeDb(v)==db );
   79432   pDb = &db->aDb[iDb];
   79433 
   79434   /* Create new statistic tables if they do not exist, or clear them
   79435   ** if they do already exist.
   79436   */
   79437   for(i=0; i<ArraySize(aTable); i++){
   79438     const char *zTab = aTable[i].zName;
   79439     Table *pStat;
   79440     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   79441       /* The sqlite_stat[12] table does not exist. Create it. Note that a
   79442       ** side-effect of the CREATE TABLE statement is to leave the rootpage
   79443       ** of the new table in register pParse->regRoot. This is important
   79444       ** because the OpenWrite opcode below will be needing it. */
   79445       sqlite3NestedParse(pParse,
   79446           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   79447       );
   79448       aRoot[i] = pParse->regRoot;
   79449       aCreateTbl[i] = 1;
   79450     }else{
   79451       /* The table already exists. If zWhere is not NULL, delete all entries
   79452       ** associated with the table zWhere. If zWhere is NULL, delete the
   79453       ** entire contents of the table. */
   79454       aRoot[i] = pStat->tnum;
   79455       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   79456       if( zWhere ){
   79457         sqlite3NestedParse(pParse,
   79458            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
   79459         );
   79460       }else{
   79461         /* The sqlite_stat[12] table already exists.  Delete all rows. */
   79462         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   79463       }
   79464     }
   79465   }
   79466 
   79467   /* Open the sqlite_stat[13] tables for writing. */
   79468   for(i=0; i<ArraySize(aTable); i++){
   79469     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
   79470     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
   79471     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   79472   }
   79473 }
   79474 
   79475 /*
   79476 ** Recommended number of samples for sqlite_stat3
   79477 */
   79478 #ifndef SQLITE_STAT3_SAMPLES
   79479 # define SQLITE_STAT3_SAMPLES 24
   79480 #endif
   79481 
   79482 /*
   79483 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
   79484 ** share an instance of the following structure to hold their state
   79485 ** information.
   79486 */
   79487 typedef struct Stat3Accum Stat3Accum;
   79488 struct Stat3Accum {
   79489   tRowcnt nRow;             /* Number of rows in the entire table */
   79490   tRowcnt nPSample;         /* How often to do a periodic sample */
   79491   int iMin;                 /* Index of entry with minimum nEq and hash */
   79492   int mxSample;             /* Maximum number of samples to accumulate */
   79493   int nSample;              /* Current number of samples */
   79494   u32 iPrn;                 /* Pseudo-random number used for sampling */
   79495   struct Stat3Sample {
   79496     i64 iRowid;                /* Rowid in main table of the key */
   79497     tRowcnt nEq;               /* sqlite_stat3.nEq */
   79498     tRowcnt nLt;               /* sqlite_stat3.nLt */
   79499     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
   79500     u8 isPSample;              /* True if a periodic sample */
   79501     u32 iHash;                 /* Tiebreaker hash */
   79502   } *a;                     /* An array of samples */
   79503 };
   79504 
   79505 #ifdef SQLITE_ENABLE_STAT3
   79506 /*
   79507 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
   79508 ** are the number of rows in the table or index (C) and the number of samples
   79509 ** to accumulate (S).
   79510 **
   79511 ** This routine allocates the Stat3Accum object.
   79512 **
   79513 ** The return value is the Stat3Accum object (P).
   79514 */
   79515 static void stat3Init(
   79516   sqlite3_context *context,
   79517   int argc,
   79518   sqlite3_value **argv
   79519 ){
   79520   Stat3Accum *p;
   79521   tRowcnt nRow;
   79522   int mxSample;
   79523   int n;
   79524 
   79525   UNUSED_PARAMETER(argc);
   79526   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
   79527   mxSample = sqlite3_value_int(argv[1]);
   79528   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
   79529   p = sqlite3_malloc( n );
   79530   if( p==0 ){
   79531     sqlite3_result_error_nomem(context);
   79532     return;
   79533   }
   79534   memset(p, 0, n);
   79535   p->a = (struct Stat3Sample*)&p[1];
   79536   p->nRow = nRow;
   79537   p->mxSample = mxSample;
   79538   p->nPSample = p->nRow/(mxSample/3+1) + 1;
   79539   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
   79540   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
   79541 }
   79542 static const FuncDef stat3InitFuncdef = {
   79543   2,                /* nArg */
   79544   SQLITE_UTF8,      /* iPrefEnc */
   79545   0,                /* flags */
   79546   0,                /* pUserData */
   79547   0,                /* pNext */
   79548   stat3Init,        /* xFunc */
   79549   0,                /* xStep */
   79550   0,                /* xFinalize */
   79551   "stat3_init",     /* zName */
   79552   0,                /* pHash */
   79553   0                 /* pDestructor */
   79554 };
   79555 
   79556 
   79557 /*
   79558 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
   79559 ** arguments describe a single key instance.  This routine makes the
   79560 ** decision about whether or not to retain this key for the sqlite_stat3
   79561 ** table.
   79562 **
   79563 ** The return value is NULL.
   79564 */
   79565 static void stat3Push(
   79566   sqlite3_context *context,
   79567   int argc,
   79568   sqlite3_value **argv
   79569 ){
   79570   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
   79571   tRowcnt nEq = sqlite3_value_int64(argv[0]);
   79572   tRowcnt nLt = sqlite3_value_int64(argv[1]);
   79573   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
   79574   i64 rowid = sqlite3_value_int64(argv[3]);
   79575   u8 isPSample = 0;
   79576   u8 doInsert = 0;
   79577   int iMin = p->iMin;
   79578   struct Stat3Sample *pSample;
   79579   int i;
   79580   u32 h;
   79581 
   79582   UNUSED_PARAMETER(context);
   79583   UNUSED_PARAMETER(argc);
   79584   if( nEq==0 ) return;
   79585   h = p->iPrn = p->iPrn*1103515245 + 12345;
   79586   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
   79587     doInsert = isPSample = 1;
   79588   }else if( p->nSample<p->mxSample ){
   79589     doInsert = 1;
   79590   }else{
   79591     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
   79592       doInsert = 1;
   79593     }
   79594   }
   79595   if( !doInsert ) return;
   79596   if( p->nSample==p->mxSample ){
   79597     assert( p->nSample - iMin - 1 >= 0 );
   79598     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
   79599     pSample = &p->a[p->nSample-1];
   79600   }else{
   79601     pSample = &p->a[p->nSample++];
   79602   }
   79603   pSample->iRowid = rowid;
   79604   pSample->nEq = nEq;
   79605   pSample->nLt = nLt;
   79606   pSample->nDLt = nDLt;
   79607   pSample->iHash = h;
   79608   pSample->isPSample = isPSample;
   79609 
   79610   /* Find the new minimum */
   79611   if( p->nSample==p->mxSample ){
   79612     pSample = p->a;
   79613     i = 0;
   79614     while( pSample->isPSample ){
   79615       i++;
   79616       pSample++;
   79617       assert( i<p->nSample );
   79618     }
   79619     nEq = pSample->nEq;
   79620     h = pSample->iHash;
   79621     iMin = i;
   79622     for(i++, pSample++; i<p->nSample; i++, pSample++){
   79623       if( pSample->isPSample ) continue;
   79624       if( pSample->nEq<nEq
   79625        || (pSample->nEq==nEq && pSample->iHash<h)
   79626       ){
   79627         iMin = i;
   79628         nEq = pSample->nEq;
   79629         h = pSample->iHash;
   79630       }
   79631     }
   79632     p->iMin = iMin;
   79633   }
   79634 }
   79635 static const FuncDef stat3PushFuncdef = {
   79636   5,                /* nArg */
   79637   SQLITE_UTF8,      /* iPrefEnc */
   79638   0,                /* flags */
   79639   0,                /* pUserData */
   79640   0,                /* pNext */
   79641   stat3Push,        /* xFunc */
   79642   0,                /* xStep */
   79643   0,                /* xFinalize */
   79644   "stat3_push",     /* zName */
   79645   0,                /* pHash */
   79646   0                 /* pDestructor */
   79647 };
   79648 
   79649 /*
   79650 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
   79651 ** used to query the results.  Content is returned for the Nth sqlite_stat3
   79652 ** row where N is between 0 and S-1 and S is the number of samples.  The
   79653 ** value returned depends on the number of arguments.
   79654 **
   79655 **   argc==2    result:  rowid
   79656 **   argc==3    result:  nEq
   79657 **   argc==4    result:  nLt
   79658 **   argc==5    result:  nDLt
   79659 */
   79660 static void stat3Get(
   79661   sqlite3_context *context,
   79662   int argc,
   79663   sqlite3_value **argv
   79664 ){
   79665   int n = sqlite3_value_int(argv[1]);
   79666   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
   79667 
   79668   assert( p!=0 );
   79669   if( p->nSample<=n ) return;
   79670   switch( argc ){
   79671     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
   79672     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
   79673     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
   79674     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
   79675   }
   79676 }
   79677 static const FuncDef stat3GetFuncdef = {
   79678   -1,               /* nArg */
   79679   SQLITE_UTF8,      /* iPrefEnc */
   79680   0,                /* flags */
   79681   0,                /* pUserData */
   79682   0,                /* pNext */
   79683   stat3Get,         /* xFunc */
   79684   0,                /* xStep */
   79685   0,                /* xFinalize */
   79686   "stat3_get",     /* zName */
   79687   0,                /* pHash */
   79688   0                 /* pDestructor */
   79689 };
   79690 #endif /* SQLITE_ENABLE_STAT3 */
   79691 
   79692 
   79693 
   79694 
   79695 /*
   79696 ** Generate code to do an analysis of all indices associated with
   79697 ** a single table.
   79698 */
   79699 static void analyzeOneTable(
   79700   Parse *pParse,   /* Parser context */
   79701   Table *pTab,     /* Table whose indices are to be analyzed */
   79702   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
   79703   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   79704   int iMem         /* Available memory locations begin here */
   79705 ){
   79706   sqlite3 *db = pParse->db;    /* Database handle */
   79707   Index *pIdx;                 /* An index to being analyzed */
   79708   int iIdxCur;                 /* Cursor open on index being analyzed */
   79709   Vdbe *v;                     /* The virtual machine being built up */
   79710   int i;                       /* Loop counter */
   79711   int topOfLoop;               /* The top of the loop */
   79712   int endOfLoop;               /* The end of the loop */
   79713   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   79714   int iDb;                     /* Index of database containing pTab */
   79715   int regTabname = iMem++;     /* Register containing table name */
   79716   int regIdxname = iMem++;     /* Register containing index name */
   79717   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
   79718 #ifdef SQLITE_ENABLE_STAT3
   79719   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
   79720   int regNumLt = iMem++;       /* Number of keys less than regSample */
   79721   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
   79722   int regSample = iMem++;      /* The next sample value */
   79723   int regRowid = regSample;    /* Rowid of a sample */
   79724   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
   79725   int regLoop = iMem++;        /* Loop counter */
   79726   int regCount = iMem++;       /* Number of rows in the table or index */
   79727   int regTemp1 = iMem++;       /* Intermediate register */
   79728   int regTemp2 = iMem++;       /* Intermediate register */
   79729   int once = 1;                /* One-time initialization */
   79730   int shortJump = 0;           /* Instruction address */
   79731   int iTabCur = pParse->nTab++; /* Table cursor */
   79732 #endif
   79733   int regCol = iMem++;         /* Content of a column in analyzed table */
   79734   int regRec = iMem++;         /* Register holding completed record */
   79735   int regTemp = iMem++;        /* Temporary use register */
   79736   int regNewRowid = iMem++;    /* Rowid for the inserted record */
   79737 
   79738 
   79739   v = sqlite3GetVdbe(pParse);
   79740   if( v==0 || NEVER(pTab==0) ){
   79741     return;
   79742   }
   79743   if( pTab->tnum==0 ){
   79744     /* Do not gather statistics on views or virtual tables */
   79745     return;
   79746   }
   79747   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
   79748     /* Do not gather statistics on system tables */
   79749     return;
   79750   }
   79751   assert( sqlite3BtreeHoldsAllMutexes(db) );
   79752   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79753   assert( iDb>=0 );
   79754   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   79755 #ifndef SQLITE_OMIT_AUTHORIZATION
   79756   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   79757       db->aDb[iDb].zName ) ){
   79758     return;
   79759   }
   79760 #endif
   79761 
   79762   /* Establish a read-lock on the table at the shared-cache level. */
   79763   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   79764 
   79765   iIdxCur = pParse->nTab++;
   79766   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   79767   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   79768     int nCol;
   79769     KeyInfo *pKey;
   79770     int addrIfNot = 0;           /* address of OP_IfNot */
   79771     int *aChngAddr;              /* Array of jump instruction addresses */
   79772 
   79773     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
   79774     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
   79775     nCol = pIdx->nColumn;
   79776     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
   79777     if( aChngAddr==0 ) continue;
   79778     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   79779     if( iMem+1+(nCol*2)>pParse->nMem ){
   79780       pParse->nMem = iMem+1+(nCol*2);
   79781     }
   79782 
   79783     /* Open a cursor to the index to be analyzed. */
   79784     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   79785     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
   79786         (char *)pKey, P4_KEYINFO_HANDOFF);
   79787     VdbeComment((v, "%s", pIdx->zName));
   79788 
   79789     /* Populate the register containing the index name. */
   79790     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
   79791 
   79792 #ifdef SQLITE_ENABLE_STAT3
   79793     if( once ){
   79794       once = 0;
   79795       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   79796     }
   79797     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
   79798     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
   79799     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
   79800     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
   79801     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
   79802     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
   79803     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
   79804                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
   79805     sqlite3VdbeChangeP5(v, 2);
   79806 #endif /* SQLITE_ENABLE_STAT3 */
   79807 
   79808     /* The block of memory cells initialized here is used as follows.
   79809     **
   79810     **    iMem:
   79811     **        The total number of rows in the table.
   79812     **
   79813     **    iMem+1 .. iMem+nCol:
   79814     **        Number of distinct entries in index considering the
   79815     **        left-most N columns only, where N is between 1 and nCol,
   79816     **        inclusive.
   79817     **
   79818     **    iMem+nCol+1 .. Mem+2*nCol:
   79819     **        Previous value of indexed columns, from left to right.
   79820     **
   79821     ** Cells iMem through iMem+nCol are initialized to 0. The others are
   79822     ** initialized to contain an SQL NULL.
   79823     */
   79824     for(i=0; i<=nCol; i++){
   79825       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
   79826     }
   79827     for(i=0; i<nCol; i++){
   79828       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
   79829     }
   79830 
   79831     /* Start the analysis loop. This loop runs through all the entries in
   79832     ** the index b-tree.  */
   79833     endOfLoop = sqlite3VdbeMakeLabel(v);
   79834     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
   79835     topOfLoop = sqlite3VdbeCurrentAddr(v);
   79836     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
   79837 
   79838     for(i=0; i<nCol; i++){
   79839       CollSeq *pColl;
   79840       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
   79841       if( i==0 ){
   79842         /* Always record the very first row */
   79843         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
   79844       }
   79845       assert( pIdx->azColl!=0 );
   79846       assert( pIdx->azColl[i]!=0 );
   79847       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
   79848       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
   79849                                       (char*)pColl, P4_COLLSEQ);
   79850       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   79851       VdbeComment((v, "jump if column %d changed", i));
   79852 #ifdef SQLITE_ENABLE_STAT3
   79853       if( i==0 ){
   79854         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
   79855         VdbeComment((v, "incr repeat count"));
   79856       }
   79857 #endif
   79858     }
   79859     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
   79860     for(i=0; i<nCol; i++){
   79861       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
   79862       if( i==0 ){
   79863         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
   79864 #ifdef SQLITE_ENABLE_STAT3
   79865         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
   79866                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
   79867         sqlite3VdbeChangeP5(v, 5);
   79868         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
   79869         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
   79870         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
   79871         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
   79872 #endif
   79873       }
   79874       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
   79875       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
   79876     }
   79877     sqlite3DbFree(db, aChngAddr);
   79878 
   79879     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
   79880     sqlite3VdbeResolveLabel(v, endOfLoop);
   79881 
   79882     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
   79883     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   79884 #ifdef SQLITE_ENABLE_STAT3
   79885     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
   79886                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
   79887     sqlite3VdbeChangeP5(v, 5);
   79888     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
   79889     shortJump =
   79890     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
   79891     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
   79892                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79893     sqlite3VdbeChangeP5(v, 2);
   79894     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
   79895     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
   79896     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
   79897     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
   79898     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
   79899                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79900     sqlite3VdbeChangeP5(v, 3);
   79901     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
   79902                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79903     sqlite3VdbeChangeP5(v, 4);
   79904     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
   79905                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
   79906     sqlite3VdbeChangeP5(v, 5);
   79907     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
   79908     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
   79909     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
   79910     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
   79911     sqlite3VdbeJumpHere(v, shortJump+2);
   79912 #endif
   79913 
   79914     /* Store the results in sqlite_stat1.
   79915     **
   79916     ** The result is a single row of the sqlite_stat1 table.  The first
   79917     ** two columns are the names of the table and index.  The third column
   79918     ** is a string composed of a list of integer statistics about the
   79919     ** index.  The first integer in the list is the total number of entries
   79920     ** in the index.  There is one additional integer in the list for each
   79921     ** column of the table.  This additional integer is a guess of how many
   79922     ** rows of the table the index will select.  If D is the count of distinct
   79923     ** values and K is the total number of rows, then the integer is computed
   79924     ** as:
   79925     **
   79926     **        I = (K+D-1)/D
   79927     **
   79928     ** If K==0 then no entry is made into the sqlite_stat1 table.
   79929     ** If K>0 then it is always the case the D>0 so division by zero
   79930     ** is never possible.
   79931     */
   79932     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
   79933     if( jZeroRows<0 ){
   79934       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   79935     }
   79936     for(i=0; i<nCol; i++){
   79937       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
   79938       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   79939       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
   79940       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   79941       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
   79942       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
   79943       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   79944     }
   79945     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   79946     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   79947     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   79948     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   79949   }
   79950 
   79951   /* If the table has no indices, create a single sqlite_stat1 entry
   79952   ** containing NULL as the index name and the row count as the content.
   79953   */
   79954   if( pTab->pIndex==0 ){
   79955     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
   79956     VdbeComment((v, "%s", pTab->zName));
   79957     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
   79958     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   79959     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
   79960   }else{
   79961     sqlite3VdbeJumpHere(v, jZeroRows);
   79962     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
   79963   }
   79964   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   79965   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   79966   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   79967   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   79968   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   79969   if( pParse->nMem<regRec ) pParse->nMem = regRec;
   79970   sqlite3VdbeJumpHere(v, jZeroRows);
   79971 }
   79972 
   79973 
   79974 /*
   79975 ** Generate code that will cause the most recent index analysis to
   79976 ** be loaded into internal hash tables where is can be used.
   79977 */
   79978 static void loadAnalysis(Parse *pParse, int iDb){
   79979   Vdbe *v = sqlite3GetVdbe(pParse);
   79980   if( v ){
   79981     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   79982   }
   79983 }
   79984 
   79985 /*
   79986 ** Generate code that will do an analysis of an entire database
   79987 */
   79988 static void analyzeDatabase(Parse *pParse, int iDb){
   79989   sqlite3 *db = pParse->db;
   79990   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   79991   HashElem *k;
   79992   int iStatCur;
   79993   int iMem;
   79994 
   79995   sqlite3BeginWriteOperation(pParse, 0, iDb);
   79996   iStatCur = pParse->nTab;
   79997   pParse->nTab += 3;
   79998   openStatTable(pParse, iDb, iStatCur, 0, 0);
   79999   iMem = pParse->nMem+1;
   80000   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   80001   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   80002     Table *pTab = (Table*)sqliteHashData(k);
   80003     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
   80004   }
   80005   loadAnalysis(pParse, iDb);
   80006 }
   80007 
   80008 /*
   80009 ** Generate code that will do an analysis of a single table in
   80010 ** a database.  If pOnlyIdx is not NULL then it is a single index
   80011 ** in pTab that should be analyzed.
   80012 */
   80013 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
   80014   int iDb;
   80015   int iStatCur;
   80016 
   80017   assert( pTab!=0 );
   80018   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   80019   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   80020   sqlite3BeginWriteOperation(pParse, 0, iDb);
   80021   iStatCur = pParse->nTab;
   80022   pParse->nTab += 3;
   80023   if( pOnlyIdx ){
   80024     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
   80025   }else{
   80026     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
   80027   }
   80028   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
   80029   loadAnalysis(pParse, iDb);
   80030 }
   80031 
   80032 /*
   80033 ** Generate code for the ANALYZE command.  The parser calls this routine
   80034 ** when it recognizes an ANALYZE command.
   80035 **
   80036 **        ANALYZE                            -- 1
   80037 **        ANALYZE  <database>                -- 2
   80038 **        ANALYZE  ?<database>.?<tablename>  -- 3
   80039 **
   80040 ** Form 1 causes all indices in all attached databases to be analyzed.
   80041 ** Form 2 analyzes all indices the single database named.
   80042 ** Form 3 analyzes all indices associated with the named table.
   80043 */
   80044 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   80045   sqlite3 *db = pParse->db;
   80046   int iDb;
   80047   int i;
   80048   char *z, *zDb;
   80049   Table *pTab;
   80050   Index *pIdx;
   80051   Token *pTableName;
   80052 
   80053   /* Read the database schema. If an error occurs, leave an error message
   80054   ** and code in pParse and return NULL. */
   80055   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   80056   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   80057     return;
   80058   }
   80059 
   80060   assert( pName2!=0 || pName1==0 );
   80061   if( pName1==0 ){
   80062     /* Form 1:  Analyze everything */
   80063     for(i=0; i<db->nDb; i++){
   80064       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   80065       analyzeDatabase(pParse, i);
   80066     }
   80067   }else if( pName2->n==0 ){
   80068     /* Form 2:  Analyze the database or table named */
   80069     iDb = sqlite3FindDb(db, pName1);
   80070     if( iDb>=0 ){
   80071       analyzeDatabase(pParse, iDb);
   80072     }else{
   80073       z = sqlite3NameFromToken(db, pName1);
   80074       if( z ){
   80075         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
   80076           analyzeTable(pParse, pIdx->pTable, pIdx);
   80077         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
   80078           analyzeTable(pParse, pTab, 0);
   80079         }
   80080         sqlite3DbFree(db, z);
   80081       }
   80082     }
   80083   }else{
   80084     /* Form 3: Analyze the fully qualified table name */
   80085     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   80086     if( iDb>=0 ){
   80087       zDb = db->aDb[iDb].zName;
   80088       z = sqlite3NameFromToken(db, pTableName);
   80089       if( z ){
   80090         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
   80091           analyzeTable(pParse, pIdx->pTable, pIdx);
   80092         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
   80093           analyzeTable(pParse, pTab, 0);
   80094         }
   80095         sqlite3DbFree(db, z);
   80096       }
   80097     }
   80098   }
   80099 }
   80100 
   80101 /*
   80102 ** Used to pass information from the analyzer reader through to the
   80103 ** callback routine.
   80104 */
   80105 typedef struct analysisInfo analysisInfo;
   80106 struct analysisInfo {
   80107   sqlite3 *db;
   80108   const char *zDatabase;
   80109 };
   80110 
   80111 /*
   80112 ** This callback is invoked once for each index when reading the
   80113 ** sqlite_stat1 table.
   80114 **
   80115 **     argv[0] = name of the table
   80116 **     argv[1] = name of the index (might be NULL)
   80117 **     argv[2] = results of analysis - on integer for each column
   80118 **
   80119 ** Entries for which argv[1]==NULL simply record the number of rows in
   80120 ** the table.
   80121 */
   80122 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   80123   analysisInfo *pInfo = (analysisInfo*)pData;
   80124   Index *pIndex;
   80125   Table *pTable;
   80126   int i, c, n;
   80127   tRowcnt v;
   80128   const char *z;
   80129 
   80130   assert( argc==3 );
   80131   UNUSED_PARAMETER2(NotUsed, argc);
   80132 
   80133   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   80134     return 0;
   80135   }
   80136   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   80137   if( pTable==0 ){
   80138     return 0;
   80139   }
   80140   if( argv[1] ){
   80141     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   80142   }else{
   80143     pIndex = 0;
   80144   }
   80145   n = pIndex ? pIndex->nColumn : 0;
   80146   z = argv[2];
   80147   for(i=0; *z && i<=n; i++){
   80148     v = 0;
   80149     while( (c=z[0])>='0' && c<='9' ){
   80150       v = v*10 + c - '0';
   80151       z++;
   80152     }
   80153     if( i==0 ) pTable->nRowEst = v;
   80154     if( pIndex==0 ) break;
   80155     pIndex->aiRowEst[i] = v;
   80156     if( *z==' ' ) z++;
   80157     if( memcmp(z, "unordered", 10)==0 ){
   80158       pIndex->bUnordered = 1;
   80159       break;
   80160     }
   80161   }
   80162   return 0;
   80163 }
   80164 
   80165 /*
   80166 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   80167 ** and its contents.
   80168 */
   80169 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   80170 #ifdef SQLITE_ENABLE_STAT3
   80171   if( pIdx->aSample ){
   80172     int j;
   80173     for(j=0; j<pIdx->nSample; j++){
   80174       IndexSample *p = &pIdx->aSample[j];
   80175       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
   80176         sqlite3DbFree(db, p->u.z);
   80177       }
   80178     }
   80179     sqlite3DbFree(db, pIdx->aSample);
   80180   }
   80181   if( db && db->pnBytesFreed==0 ){
   80182     pIdx->nSample = 0;
   80183     pIdx->aSample = 0;
   80184   }
   80185 #else
   80186   UNUSED_PARAMETER(db);
   80187   UNUSED_PARAMETER(pIdx);
   80188 #endif
   80189 }
   80190 
   80191 #ifdef SQLITE_ENABLE_STAT3
   80192 /*
   80193 ** Load content from the sqlite_stat3 table into the Index.aSample[]
   80194 ** arrays of all indices.
   80195 */
   80196 static int loadStat3(sqlite3 *db, const char *zDb){
   80197   int rc;                       /* Result codes from subroutines */
   80198   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
   80199   char *zSql;                   /* Text of the SQL statement */
   80200   Index *pPrevIdx = 0;          /* Previous index in the loop */
   80201   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
   80202   int eType;                    /* Datatype of a sample */
   80203   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
   80204 
   80205   assert( db->lookaside.bEnabled==0 );
   80206   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
   80207     return SQLITE_OK;
   80208   }
   80209 
   80210   zSql = sqlite3MPrintf(db,
   80211       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
   80212       " GROUP BY idx", zDb);
   80213   if( !zSql ){
   80214     return SQLITE_NOMEM;
   80215   }
   80216   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   80217   sqlite3DbFree(db, zSql);
   80218   if( rc ) return rc;
   80219 
   80220   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   80221     char *zIndex;   /* Index name */
   80222     Index *pIdx;    /* Pointer to the index object */
   80223     int nSample;    /* Number of samples */
   80224 
   80225     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   80226     if( zIndex==0 ) continue;
   80227     nSample = sqlite3_column_int(pStmt, 1);
   80228     pIdx = sqlite3FindIndex(db, zIndex, zDb);
   80229     if( pIdx==0 ) continue;
   80230     assert( pIdx->nSample==0 );
   80231     pIdx->nSample = nSample;
   80232     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
   80233     pIdx->avgEq = pIdx->aiRowEst[1];
   80234     if( pIdx->aSample==0 ){
   80235       db->mallocFailed = 1;
   80236       sqlite3_finalize(pStmt);
   80237       return SQLITE_NOMEM;
   80238     }
   80239   }
   80240   rc = sqlite3_finalize(pStmt);
   80241   if( rc ) return rc;
   80242 
   80243   zSql = sqlite3MPrintf(db,
   80244       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
   80245   if( !zSql ){
   80246     return SQLITE_NOMEM;
   80247   }
   80248   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   80249   sqlite3DbFree(db, zSql);
   80250   if( rc ) return rc;
   80251 
   80252   while( sqlite3_step(pStmt)==SQLITE_ROW ){
   80253     char *zIndex;   /* Index name */
   80254     Index *pIdx;    /* Pointer to the index object */
   80255     int i;          /* Loop counter */
   80256     tRowcnt sumEq;  /* Sum of the nEq values */
   80257 
   80258     zIndex = (char *)sqlite3_column_text(pStmt, 0);
   80259     if( zIndex==0 ) continue;
   80260     pIdx = sqlite3FindIndex(db, zIndex, zDb);
   80261     if( pIdx==0 ) continue;
   80262     if( pIdx==pPrevIdx ){
   80263       idx++;
   80264     }else{
   80265       pPrevIdx = pIdx;
   80266       idx = 0;
   80267     }
   80268     assert( idx<pIdx->nSample );
   80269     pSample = &pIdx->aSample[idx];
   80270     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
   80271     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
   80272     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
   80273     if( idx==pIdx->nSample-1 ){
   80274       if( pSample->nDLt>0 ){
   80275         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
   80276         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
   80277       }
   80278       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
   80279     }
   80280     eType = sqlite3_column_type(pStmt, 4);
   80281     pSample->eType = (u8)eType;
   80282     switch( eType ){
   80283       case SQLITE_INTEGER: {
   80284         pSample->u.i = sqlite3_column_int64(pStmt, 4);
   80285         break;
   80286       }
   80287       case SQLITE_FLOAT: {
   80288         pSample->u.r = sqlite3_column_double(pStmt, 4);
   80289         break;
   80290       }
   80291       case SQLITE_NULL: {
   80292         break;
   80293       }
   80294       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
   80295         const char *z = (const char *)(
   80296               (eType==SQLITE_BLOB) ?
   80297               sqlite3_column_blob(pStmt, 4):
   80298               sqlite3_column_text(pStmt, 4)
   80299            );
   80300         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
   80301         pSample->nByte = n;
   80302         if( n < 1){
   80303           pSample->u.z = 0;
   80304         }else{
   80305           pSample->u.z = sqlite3DbMallocRaw(db, n);
   80306           if( pSample->u.z==0 ){
   80307             db->mallocFailed = 1;
   80308             sqlite3_finalize(pStmt);
   80309             return SQLITE_NOMEM;
   80310           }
   80311           memcpy(pSample->u.z, z, n);
   80312         }
   80313       }
   80314     }
   80315   }
   80316   return sqlite3_finalize(pStmt);
   80317 }
   80318 #endif /* SQLITE_ENABLE_STAT3 */
   80319 
   80320 /*
   80321 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
   80322 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   80323 ** arrays. The contents of sqlite_stat3 are used to populate the
   80324 ** Index.aSample[] arrays.
   80325 **
   80326 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   80327 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
   80328 ** during compilation and the sqlite_stat3 table is present, no data is
   80329 ** read from it.
   80330 **
   80331 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
   80332 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
   80333 ** returned. However, in this case, data is read from the sqlite_stat1
   80334 ** table (if it is present) before returning.
   80335 **
   80336 ** If an OOM error occurs, this function always sets db->mallocFailed.
   80337 ** This means if the caller does not care about other errors, the return
   80338 ** code may be ignored.
   80339 */
   80340 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   80341   analysisInfo sInfo;
   80342   HashElem *i;
   80343   char *zSql;
   80344   int rc;
   80345 
   80346   assert( iDb>=0 && iDb<db->nDb );
   80347   assert( db->aDb[iDb].pBt!=0 );
   80348 
   80349   /* Clear any prior statistics */
   80350   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   80351   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   80352     Index *pIdx = sqliteHashData(i);
   80353     sqlite3DefaultRowEst(pIdx);
   80354 #ifdef SQLITE_ENABLE_STAT3
   80355     sqlite3DeleteIndexSamples(db, pIdx);
   80356     pIdx->aSample = 0;
   80357 #endif
   80358   }
   80359 
   80360   /* Check to make sure the sqlite_stat1 table exists */
   80361   sInfo.db = db;
   80362   sInfo.zDatabase = db->aDb[iDb].zName;
   80363   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   80364     return SQLITE_ERROR;
   80365   }
   80366 
   80367   /* Load new statistics out of the sqlite_stat1 table */
   80368   zSql = sqlite3MPrintf(db,
   80369       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   80370   if( zSql==0 ){
   80371     rc = SQLITE_NOMEM;
   80372   }else{
   80373     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   80374     sqlite3DbFree(db, zSql);
   80375   }
   80376 
   80377 
   80378   /* Load the statistics from the sqlite_stat3 table. */
   80379 #ifdef SQLITE_ENABLE_STAT3
   80380   if( rc==SQLITE_OK ){
   80381     int lookasideEnabled = db->lookaside.bEnabled;
   80382     db->lookaside.bEnabled = 0;
   80383     rc = loadStat3(db, sInfo.zDatabase);
   80384     db->lookaside.bEnabled = lookasideEnabled;
   80385   }
   80386 #endif
   80387 
   80388   if( rc==SQLITE_NOMEM ){
   80389     db->mallocFailed = 1;
   80390   }
   80391   return rc;
   80392 }
   80393 
   80394 
   80395 #endif /* SQLITE_OMIT_ANALYZE */
   80396 
   80397 /************** End of analyze.c *********************************************/
   80398 /************** Begin file attach.c ******************************************/
   80399 /*
   80400 ** 2003 April 6
   80401 **
   80402 ** The author disclaims copyright to this source code.  In place of
   80403 ** a legal notice, here is a blessing:
   80404 **
   80405 **    May you do good and not evil.
   80406 **    May you find forgiveness for yourself and forgive others.
   80407 **    May you share freely, never taking more than you give.
   80408 **
   80409 *************************************************************************
   80410 ** This file contains code used to implement the ATTACH and DETACH commands.
   80411 */
   80412 
   80413 #ifndef SQLITE_OMIT_ATTACH
   80414 /*
   80415 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   80416 ** is slightly different from resolving a normal SQL expression, because simple
   80417 ** identifiers are treated as strings, not possible column names or aliases.
   80418 **
   80419 ** i.e. if the parser sees:
   80420 **
   80421 **     ATTACH DATABASE abc AS def
   80422 **
   80423 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   80424 ** looking for columns of the same name.
   80425 **
   80426 ** This only applies to the root node of pExpr, so the statement:
   80427 **
   80428 **     ATTACH DATABASE abc||def AS 'db2'
   80429 **
   80430 ** will fail because neither abc or def can be resolved.
   80431 */
   80432 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   80433 {
   80434   int rc = SQLITE_OK;
   80435   if( pExpr ){
   80436     if( pExpr->op!=TK_ID ){
   80437       rc = sqlite3ResolveExprNames(pName, pExpr);
   80438       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
   80439         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
   80440         return SQLITE_ERROR;
   80441       }
   80442     }else{
   80443       pExpr->op = TK_STRING;
   80444     }
   80445   }
   80446   return rc;
   80447 }
   80448 
   80449 /*
   80450 ** An SQL user-function registered to do the work of an ATTACH statement. The
   80451 ** three arguments to the function come directly from an attach statement:
   80452 **
   80453 **     ATTACH DATABASE x AS y KEY z
   80454 **
   80455 **     SELECT sqlite_attach(x, y, z)
   80456 **
   80457 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   80458 ** third argument.
   80459 */
   80460 static void attachFunc(
   80461   sqlite3_context *context,
   80462   int NotUsed,
   80463   sqlite3_value **argv
   80464 ){
   80465   int i;
   80466   int rc = 0;
   80467   sqlite3 *db = sqlite3_context_db_handle(context);
   80468   const char *zName;
   80469   const char *zFile;
   80470   char *zPath = 0;
   80471   char *zErr = 0;
   80472   unsigned int flags;
   80473   Db *aNew;
   80474   char *zErrDyn = 0;
   80475   sqlite3_vfs *pVfs;
   80476 
   80477   UNUSED_PARAMETER(NotUsed);
   80478 
   80479   zFile = (const char *)sqlite3_value_text(argv[0]);
   80480   zName = (const char *)sqlite3_value_text(argv[1]);
   80481   if( zFile==0 ) zFile = "";
   80482   if( zName==0 ) zName = "";
   80483 
   80484   /* Check for the following errors:
   80485   **
   80486   **     * Too many attached databases,
   80487   **     * Transaction currently open
   80488   **     * Specified database name already being used.
   80489   */
   80490   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   80491     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   80492       db->aLimit[SQLITE_LIMIT_ATTACHED]
   80493     );
   80494     goto attach_error;
   80495   }
   80496   if( !db->autoCommit ){
   80497     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   80498     goto attach_error;
   80499   }
   80500   for(i=0; i<db->nDb; i++){
   80501     char *z = db->aDb[i].zName;
   80502     assert( z && zName );
   80503     if( sqlite3StrICmp(z, zName)==0 ){
   80504       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   80505       goto attach_error;
   80506     }
   80507   }
   80508 
   80509   /* Allocate the new entry in the db->aDb[] array and initialise the schema
   80510   ** hash tables.
   80511   */
   80512   if( db->aDb==db->aDbStatic ){
   80513     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   80514     if( aNew==0 ) return;
   80515     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   80516   }else{
   80517     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   80518     if( aNew==0 ) return;
   80519   }
   80520   db->aDb = aNew;
   80521   aNew = &db->aDb[db->nDb];
   80522   memset(aNew, 0, sizeof(*aNew));
   80523 
   80524   /* Open the database file. If the btree is successfully opened, use
   80525   ** it to obtain the database schema. At this point the schema may
   80526   ** or may not be initialised.
   80527   */
   80528   flags = db->openFlags;
   80529   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   80530   if( rc!=SQLITE_OK ){
   80531     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   80532     sqlite3_result_error(context, zErr, -1);
   80533     sqlite3_free(zErr);
   80534     return;
   80535   }
   80536   assert( pVfs );
   80537   flags |= SQLITE_OPEN_MAIN_DB;
   80538   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
   80539   sqlite3_free( zPath );
   80540   db->nDb++;
   80541   if( rc==SQLITE_CONSTRAINT ){
   80542     rc = SQLITE_ERROR;
   80543     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   80544   }else if( rc==SQLITE_OK ){
   80545     Pager *pPager;
   80546     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   80547     if( !aNew->pSchema ){
   80548       rc = SQLITE_NOMEM;
   80549     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   80550       zErrDyn = sqlite3MPrintf(db,
   80551         "attached databases must use the same text encoding as main database");
   80552       rc = SQLITE_ERROR;
   80553     }
   80554     pPager = sqlite3BtreePager(aNew->pBt);
   80555     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   80556     sqlite3BtreeSecureDelete(aNew->pBt,
   80557                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   80558   }
   80559   aNew->safety_level = 3;
   80560   aNew->zName = sqlite3DbStrDup(db, zName);
   80561   if( rc==SQLITE_OK && aNew->zName==0 ){
   80562     rc = SQLITE_NOMEM;
   80563   }
   80564 
   80565 
   80566 #ifdef SQLITE_HAS_CODEC
   80567   if( rc==SQLITE_OK ){
   80568     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   80569     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   80570     int nKey;
   80571     char *zKey;
   80572     int t = sqlite3_value_type(argv[2]);
   80573     switch( t ){
   80574       case SQLITE_INTEGER:
   80575       case SQLITE_FLOAT:
   80576         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   80577         rc = SQLITE_ERROR;
   80578         break;
   80579 
   80580       case SQLITE_TEXT:
   80581       case SQLITE_BLOB:
   80582         nKey = sqlite3_value_bytes(argv[2]);
   80583         zKey = (char *)sqlite3_value_blob(argv[2]);
   80584         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   80585         break;
   80586 
   80587       case SQLITE_NULL:
   80588         /* No key specified.  Use the key from the main database */
   80589         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   80590         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
   80591           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   80592         }
   80593         break;
   80594     }
   80595   }
   80596 #endif
   80597 
   80598   /* If the file was opened successfully, read the schema for the new database.
   80599   ** If this fails, or if opening the file failed, then close the file and
   80600   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   80601   ** we found it.
   80602   */
   80603   if( rc==SQLITE_OK ){
   80604     sqlite3BtreeEnterAll(db);
   80605     rc = sqlite3Init(db, &zErrDyn);
   80606     sqlite3BtreeLeaveAll(db);
   80607   }
   80608   if( rc ){
   80609     int iDb = db->nDb - 1;
   80610     assert( iDb>=2 );
   80611     if( db->aDb[iDb].pBt ){
   80612       sqlite3BtreeClose(db->aDb[iDb].pBt);
   80613       db->aDb[iDb].pBt = 0;
   80614       db->aDb[iDb].pSchema = 0;
   80615     }
   80616     sqlite3ResetInternalSchema(db, -1);
   80617     db->nDb = iDb;
   80618     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   80619       db->mallocFailed = 1;
   80620       sqlite3DbFree(db, zErrDyn);
   80621       zErrDyn = sqlite3MPrintf(db, "out of memory");
   80622     }else if( zErrDyn==0 ){
   80623       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   80624     }
   80625     goto attach_error;
   80626   }
   80627 
   80628   return;
   80629 
   80630 attach_error:
   80631   /* Return an error if we get here */
   80632   if( zErrDyn ){
   80633     sqlite3_result_error(context, zErrDyn, -1);
   80634     sqlite3DbFree(db, zErrDyn);
   80635   }
   80636   if( rc ) sqlite3_result_error_code(context, rc);
   80637 }
   80638 
   80639 /*
   80640 ** An SQL user-function registered to do the work of an DETACH statement. The
   80641 ** three arguments to the function come directly from a detach statement:
   80642 **
   80643 **     DETACH DATABASE x
   80644 **
   80645 **     SELECT sqlite_detach(x)
   80646 */
   80647 static void detachFunc(
   80648   sqlite3_context *context,
   80649   int NotUsed,
   80650   sqlite3_value **argv
   80651 ){
   80652   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   80653   sqlite3 *db = sqlite3_context_db_handle(context);
   80654   int i;
   80655   Db *pDb = 0;
   80656   char zErr[128];
   80657 
   80658   UNUSED_PARAMETER(NotUsed);
   80659 
   80660   if( zName==0 ) zName = "";
   80661   for(i=0; i<db->nDb; i++){
   80662     pDb = &db->aDb[i];
   80663     if( pDb->pBt==0 ) continue;
   80664     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   80665   }
   80666 
   80667   if( i>=db->nDb ){
   80668     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   80669     goto detach_error;
   80670   }
   80671   if( i<2 ){
   80672     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   80673     goto detach_error;
   80674   }
   80675   if( !db->autoCommit ){
   80676     sqlite3_snprintf(sizeof(zErr), zErr,
   80677                      "cannot DETACH database within transaction");
   80678     goto detach_error;
   80679   }
   80680   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   80681     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   80682     goto detach_error;
   80683   }
   80684 
   80685   sqlite3BtreeClose(pDb->pBt);
   80686   pDb->pBt = 0;
   80687   pDb->pSchema = 0;
   80688   sqlite3ResetInternalSchema(db, -1);
   80689   return;
   80690 
   80691 detach_error:
   80692   sqlite3_result_error(context, zErr, -1);
   80693 }
   80694 
   80695 /*
   80696 ** This procedure generates VDBE code for a single invocation of either the
   80697 ** sqlite_detach() or sqlite_attach() SQL user functions.
   80698 */
   80699 static void codeAttach(
   80700   Parse *pParse,       /* The parser context */
   80701   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   80702   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   80703   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   80704   Expr *pFilename,     /* Name of database file */
   80705   Expr *pDbname,       /* Name of the database to use internally */
   80706   Expr *pKey           /* Database key for encryption extension */
   80707 ){
   80708   int rc;
   80709   NameContext sName;
   80710   Vdbe *v;
   80711   sqlite3* db = pParse->db;
   80712   int regArgs;
   80713 
   80714   memset(&sName, 0, sizeof(NameContext));
   80715   sName.pParse = pParse;
   80716 
   80717   if(
   80718       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   80719       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   80720       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   80721   ){
   80722     pParse->nErr++;
   80723     goto attach_end;
   80724   }
   80725 
   80726 #ifndef SQLITE_OMIT_AUTHORIZATION
   80727   if( pAuthArg ){
   80728     char *zAuthArg;
   80729     if( pAuthArg->op==TK_STRING ){
   80730       zAuthArg = pAuthArg->u.zToken;
   80731     }else{
   80732       zAuthArg = 0;
   80733     }
   80734     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   80735     if(rc!=SQLITE_OK ){
   80736       goto attach_end;
   80737     }
   80738   }
   80739 #endif /* SQLITE_OMIT_AUTHORIZATION */
   80740 
   80741 
   80742   v = sqlite3GetVdbe(pParse);
   80743   regArgs = sqlite3GetTempRange(pParse, 4);
   80744   sqlite3ExprCode(pParse, pFilename, regArgs);
   80745   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   80746   sqlite3ExprCode(pParse, pKey, regArgs+2);
   80747 
   80748   assert( v || db->mallocFailed );
   80749   if( v ){
   80750     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   80751     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   80752     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   80753     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   80754 
   80755     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   80756     ** statement only). For DETACH, set it to false (expire all existing
   80757     ** statements).
   80758     */
   80759     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   80760   }
   80761 
   80762 attach_end:
   80763   sqlite3ExprDelete(db, pFilename);
   80764   sqlite3ExprDelete(db, pDbname);
   80765   sqlite3ExprDelete(db, pKey);
   80766 }
   80767 
   80768 /*
   80769 ** Called by the parser to compile a DETACH statement.
   80770 **
   80771 **     DETACH pDbname
   80772 */
   80773 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   80774   static const FuncDef detach_func = {
   80775     1,                /* nArg */
   80776     SQLITE_UTF8,      /* iPrefEnc */
   80777     0,                /* flags */
   80778     0,                /* pUserData */
   80779     0,                /* pNext */
   80780     detachFunc,       /* xFunc */
   80781     0,                /* xStep */
   80782     0,                /* xFinalize */
   80783     "sqlite_detach",  /* zName */
   80784     0,                /* pHash */
   80785     0                 /* pDestructor */
   80786   };
   80787   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   80788 }
   80789 
   80790 /*
   80791 ** Called by the parser to compile an ATTACH statement.
   80792 **
   80793 **     ATTACH p AS pDbname KEY pKey
   80794 */
   80795 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   80796   static const FuncDef attach_func = {
   80797     3,                /* nArg */
   80798     SQLITE_UTF8,      /* iPrefEnc */
   80799     0,                /* flags */
   80800     0,                /* pUserData */
   80801     0,                /* pNext */
   80802     attachFunc,       /* xFunc */
   80803     0,                /* xStep */
   80804     0,                /* xFinalize */
   80805     "sqlite_attach",  /* zName */
   80806     0,                /* pHash */
   80807     0                 /* pDestructor */
   80808   };
   80809   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   80810 }
   80811 #endif /* SQLITE_OMIT_ATTACH */
   80812 
   80813 /*
   80814 ** Initialize a DbFixer structure.  This routine must be called prior
   80815 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   80816 **
   80817 ** The return value indicates whether or not fixation is required.  TRUE
   80818 ** means we do need to fix the database references, FALSE means we do not.
   80819 */
   80820 SQLITE_PRIVATE int sqlite3FixInit(
   80821   DbFixer *pFix,      /* The fixer to be initialized */
   80822   Parse *pParse,      /* Error messages will be written here */
   80823   int iDb,            /* This is the database that must be used */
   80824   const char *zType,  /* "view", "trigger", or "index" */
   80825   const Token *pName  /* Name of the view, trigger, or index */
   80826 ){
   80827   sqlite3 *db;
   80828 
   80829   if( NEVER(iDb<0) || iDb==1 ) return 0;
   80830   db = pParse->db;
   80831   assert( db->nDb>iDb );
   80832   pFix->pParse = pParse;
   80833   pFix->zDb = db->aDb[iDb].zName;
   80834   pFix->zType = zType;
   80835   pFix->pName = pName;
   80836   return 1;
   80837 }
   80838 
   80839 /*
   80840 ** The following set of routines walk through the parse tree and assign
   80841 ** a specific database to all table references where the database name
   80842 ** was left unspecified in the original SQL statement.  The pFix structure
   80843 ** must have been initialized by a prior call to sqlite3FixInit().
   80844 **
   80845 ** These routines are used to make sure that an index, trigger, or
   80846 ** view in one database does not refer to objects in a different database.
   80847 ** (Exception: indices, triggers, and views in the TEMP database are
   80848 ** allowed to refer to anything.)  If a reference is explicitly made
   80849 ** to an object in a different database, an error message is added to
   80850 ** pParse->zErrMsg and these routines return non-zero.  If everything
   80851 ** checks out, these routines return 0.
   80852 */
   80853 SQLITE_PRIVATE int sqlite3FixSrcList(
   80854   DbFixer *pFix,       /* Context of the fixation */
   80855   SrcList *pList       /* The Source list to check and modify */
   80856 ){
   80857   int i;
   80858   const char *zDb;
   80859   struct SrcList_item *pItem;
   80860 
   80861   if( NEVER(pList==0) ) return 0;
   80862   zDb = pFix->zDb;
   80863   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   80864     if( pItem->zDatabase==0 ){
   80865       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
   80866     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
   80867       sqlite3ErrorMsg(pFix->pParse,
   80868          "%s %T cannot reference objects in database %s",
   80869          pFix->zType, pFix->pName, pItem->zDatabase);
   80870       return 1;
   80871     }
   80872 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   80873     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   80874     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   80875 #endif
   80876   }
   80877   return 0;
   80878 }
   80879 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   80880 SQLITE_PRIVATE int sqlite3FixSelect(
   80881   DbFixer *pFix,       /* Context of the fixation */
   80882   Select *pSelect      /* The SELECT statement to be fixed to one database */
   80883 ){
   80884   while( pSelect ){
   80885     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   80886       return 1;
   80887     }
   80888     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   80889       return 1;
   80890     }
   80891     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   80892       return 1;
   80893     }
   80894     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   80895       return 1;
   80896     }
   80897     pSelect = pSelect->pPrior;
   80898   }
   80899   return 0;
   80900 }
   80901 SQLITE_PRIVATE int sqlite3FixExpr(
   80902   DbFixer *pFix,     /* Context of the fixation */
   80903   Expr *pExpr        /* The expression to be fixed to one database */
   80904 ){
   80905   while( pExpr ){
   80906     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
   80907     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   80908       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   80909     }else{
   80910       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   80911     }
   80912     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   80913       return 1;
   80914     }
   80915     pExpr = pExpr->pLeft;
   80916   }
   80917   return 0;
   80918 }
   80919 SQLITE_PRIVATE int sqlite3FixExprList(
   80920   DbFixer *pFix,     /* Context of the fixation */
   80921   ExprList *pList    /* The expression to be fixed to one database */
   80922 ){
   80923   int i;
   80924   struct ExprList_item *pItem;
   80925   if( pList==0 ) return 0;
   80926   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   80927     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   80928       return 1;
   80929     }
   80930   }
   80931   return 0;
   80932 }
   80933 #endif
   80934 
   80935 #ifndef SQLITE_OMIT_TRIGGER
   80936 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   80937   DbFixer *pFix,     /* Context of the fixation */
   80938   TriggerStep *pStep /* The trigger step be fixed to one database */
   80939 ){
   80940   while( pStep ){
   80941     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   80942       return 1;
   80943     }
   80944     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   80945       return 1;
   80946     }
   80947     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   80948       return 1;
   80949     }
   80950     pStep = pStep->pNext;
   80951   }
   80952   return 0;
   80953 }
   80954 #endif
   80955 
   80956 /************** End of attach.c **********************************************/
   80957 /************** Begin file auth.c ********************************************/
   80958 /*
   80959 ** 2003 January 11
   80960 **
   80961 ** The author disclaims copyright to this source code.  In place of
   80962 ** a legal notice, here is a blessing:
   80963 **
   80964 **    May you do good and not evil.
   80965 **    May you find forgiveness for yourself and forgive others.
   80966 **    May you share freely, never taking more than you give.
   80967 **
   80968 *************************************************************************
   80969 ** This file contains code used to implement the sqlite3_set_authorizer()
   80970 ** API.  This facility is an optional feature of the library.  Embedded
   80971 ** systems that do not need this facility may omit it by recompiling
   80972 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   80973 */
   80974 
   80975 /*
   80976 ** All of the code in this file may be omitted by defining a single
   80977 ** macro.
   80978 */
   80979 #ifndef SQLITE_OMIT_AUTHORIZATION
   80980 
   80981 /*
   80982 ** Set or clear the access authorization function.
   80983 **
   80984 ** The access authorization function is be called during the compilation
   80985 ** phase to verify that the user has read and/or write access permission on
   80986 ** various fields of the database.  The first argument to the auth function
   80987 ** is a copy of the 3rd argument to this routine.  The second argument
   80988 ** to the auth function is one of these constants:
   80989 **
   80990 **       SQLITE_CREATE_INDEX
   80991 **       SQLITE_CREATE_TABLE
   80992 **       SQLITE_CREATE_TEMP_INDEX
   80993 **       SQLITE_CREATE_TEMP_TABLE
   80994 **       SQLITE_CREATE_TEMP_TRIGGER
   80995 **       SQLITE_CREATE_TEMP_VIEW
   80996 **       SQLITE_CREATE_TRIGGER
   80997 **       SQLITE_CREATE_VIEW
   80998 **       SQLITE_DELETE
   80999 **       SQLITE_DROP_INDEX
   81000 **       SQLITE_DROP_TABLE
   81001 **       SQLITE_DROP_TEMP_INDEX
   81002 **       SQLITE_DROP_TEMP_TABLE
   81003 **       SQLITE_DROP_TEMP_TRIGGER
   81004 **       SQLITE_DROP_TEMP_VIEW
   81005 **       SQLITE_DROP_TRIGGER
   81006 **       SQLITE_DROP_VIEW
   81007 **       SQLITE_INSERT
   81008 **       SQLITE_PRAGMA
   81009 **       SQLITE_READ
   81010 **       SQLITE_SELECT
   81011 **       SQLITE_TRANSACTION
   81012 **       SQLITE_UPDATE
   81013 **
   81014 ** The third and fourth arguments to the auth function are the name of
   81015 ** the table and the column that are being accessed.  The auth function
   81016 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   81017 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   81018 ** means that the SQL statement will never-run - the sqlite3_exec() call
   81019 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   81020 ** should run but attempts to read the specified column will return NULL
   81021 ** and attempts to write the column will be ignored.
   81022 **
   81023 ** Setting the auth function to NULL disables this hook.  The default
   81024 ** setting of the auth function is NULL.
   81025 */
   81026 SQLITE_API int sqlite3_set_authorizer(
   81027   sqlite3 *db,
   81028   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   81029   void *pArg
   81030 ){
   81031   sqlite3_mutex_enter(db->mutex);
   81032   db->xAuth = xAuth;
   81033   db->pAuthArg = pArg;
   81034   sqlite3ExpirePreparedStatements(db);
   81035   sqlite3_mutex_leave(db->mutex);
   81036   return SQLITE_OK;
   81037 }
   81038 
   81039 /*
   81040 ** Write an error message into pParse->zErrMsg that explains that the
   81041 ** user-supplied authorization function returned an illegal value.
   81042 */
   81043 static void sqliteAuthBadReturnCode(Parse *pParse){
   81044   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   81045   pParse->rc = SQLITE_ERROR;
   81046 }
   81047 
   81048 /*
   81049 ** Invoke the authorization callback for permission to read column zCol from
   81050 ** table zTab in database zDb. This function assumes that an authorization
   81051 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   81052 **
   81053 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   81054 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   81055 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   81056 */
   81057 SQLITE_PRIVATE int sqlite3AuthReadCol(
   81058   Parse *pParse,                  /* The parser context */
   81059   const char *zTab,               /* Table name */
   81060   const char *zCol,               /* Column name */
   81061   int iDb                         /* Index of containing database. */
   81062 ){
   81063   sqlite3 *db = pParse->db;       /* Database handle */
   81064   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   81065   int rc;                         /* Auth callback return code */
   81066 
   81067   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   81068   if( rc==SQLITE_DENY ){
   81069     if( db->nDb>2 || iDb!=0 ){
   81070       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   81071     }else{
   81072       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   81073     }
   81074     pParse->rc = SQLITE_AUTH;
   81075   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   81076     sqliteAuthBadReturnCode(pParse);
   81077   }
   81078   return rc;
   81079 }
   81080 
   81081 /*
   81082 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   81083 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   81084 ** Check to see if it is OK to read this particular column.
   81085 **
   81086 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   81087 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   81088 ** then generate an error.
   81089 */
   81090 SQLITE_PRIVATE void sqlite3AuthRead(
   81091   Parse *pParse,        /* The parser context */
   81092   Expr *pExpr,          /* The expression to check authorization on */
   81093   Schema *pSchema,      /* The schema of the expression */
   81094   SrcList *pTabList     /* All table that pExpr might refer to */
   81095 ){
   81096   sqlite3 *db = pParse->db;
   81097   Table *pTab = 0;      /* The table being read */
   81098   const char *zCol;     /* Name of the column of the table */
   81099   int iSrc;             /* Index in pTabList->a[] of table being read */
   81100   int iDb;              /* The index of the database the expression refers to */
   81101   int iCol;             /* Index of column in table */
   81102 
   81103   if( db->xAuth==0 ) return;
   81104   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   81105   if( iDb<0 ){
   81106     /* An attempt to read a column out of a subquery or other
   81107     ** temporary table. */
   81108     return;
   81109   }
   81110 
   81111   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   81112   if( pExpr->op==TK_TRIGGER ){
   81113     pTab = pParse->pTriggerTab;
   81114   }else{
   81115     assert( pTabList );
   81116     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   81117       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   81118         pTab = pTabList->a[iSrc].pTab;
   81119         break;
   81120       }
   81121     }
   81122   }
   81123   iCol = pExpr->iColumn;
   81124   if( NEVER(pTab==0) ) return;
   81125 
   81126   if( iCol>=0 ){
   81127     assert( iCol<pTab->nCol );
   81128     zCol = pTab->aCol[iCol].zName;
   81129   }else if( pTab->iPKey>=0 ){
   81130     assert( pTab->iPKey<pTab->nCol );
   81131     zCol = pTab->aCol[pTab->iPKey].zName;
   81132   }else{
   81133     zCol = "ROWID";
   81134   }
   81135   assert( iDb>=0 && iDb<db->nDb );
   81136   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   81137     pExpr->op = TK_NULL;
   81138   }
   81139 }
   81140 
   81141 /*
   81142 ** Do an authorization check using the code and arguments given.  Return
   81143 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   81144 ** is returned, then the error count and error message in pParse are
   81145 ** modified appropriately.
   81146 */
   81147 SQLITE_PRIVATE int sqlite3AuthCheck(
   81148   Parse *pParse,
   81149   int code,
   81150   const char *zArg1,
   81151   const char *zArg2,
   81152   const char *zArg3
   81153 ){
   81154   sqlite3 *db = pParse->db;
   81155   int rc;
   81156 
   81157   /* Don't do any authorization checks if the database is initialising
   81158   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   81159   */
   81160   if( db->init.busy || IN_DECLARE_VTAB ){
   81161     return SQLITE_OK;
   81162   }
   81163 
   81164   if( db->xAuth==0 ){
   81165     return SQLITE_OK;
   81166   }
   81167   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   81168   if( rc==SQLITE_DENY ){
   81169     sqlite3ErrorMsg(pParse, "not authorized");
   81170     pParse->rc = SQLITE_AUTH;
   81171   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   81172     rc = SQLITE_DENY;
   81173     sqliteAuthBadReturnCode(pParse);
   81174   }
   81175   return rc;
   81176 }
   81177 
   81178 /*
   81179 ** Push an authorization context.  After this routine is called, the
   81180 ** zArg3 argument to authorization callbacks will be zContext until
   81181 ** popped.  Or if pParse==0, this routine is a no-op.
   81182 */
   81183 SQLITE_PRIVATE void sqlite3AuthContextPush(
   81184   Parse *pParse,
   81185   AuthContext *pContext,
   81186   const char *zContext
   81187 ){
   81188   assert( pParse );
   81189   pContext->pParse = pParse;
   81190   pContext->zAuthContext = pParse->zAuthContext;
   81191   pParse->zAuthContext = zContext;
   81192 }
   81193 
   81194 /*
   81195 ** Pop an authorization context that was previously pushed
   81196 ** by sqlite3AuthContextPush
   81197 */
   81198 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   81199   if( pContext->pParse ){
   81200     pContext->pParse->zAuthContext = pContext->zAuthContext;
   81201     pContext->pParse = 0;
   81202   }
   81203 }
   81204 
   81205 #endif /* SQLITE_OMIT_AUTHORIZATION */
   81206 
   81207 /************** End of auth.c ************************************************/
   81208 /************** Begin file build.c *******************************************/
   81209 /*
   81210 ** 2001 September 15
   81211 **
   81212 ** The author disclaims copyright to this source code.  In place of
   81213 ** a legal notice, here is a blessing:
   81214 **
   81215 **    May you do good and not evil.
   81216 **    May you find forgiveness for yourself and forgive others.
   81217 **    May you share freely, never taking more than you give.
   81218 **
   81219 *************************************************************************
   81220 ** This file contains C code routines that are called by the SQLite parser
   81221 ** when syntax rules are reduced.  The routines in this file handle the
   81222 ** following kinds of SQL syntax:
   81223 **
   81224 **     CREATE TABLE
   81225 **     DROP TABLE
   81226 **     CREATE INDEX
   81227 **     DROP INDEX
   81228 **     creating ID lists
   81229 **     BEGIN TRANSACTION
   81230 **     COMMIT
   81231 **     ROLLBACK
   81232 */
   81233 
   81234 /*
   81235 ** This routine is called when a new SQL statement is beginning to
   81236 ** be parsed.  Initialize the pParse structure as needed.
   81237 */
   81238 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   81239   pParse->explain = (u8)explainFlag;
   81240   pParse->nVar = 0;
   81241 }
   81242 
   81243 #ifndef SQLITE_OMIT_SHARED_CACHE
   81244 /*
   81245 ** The TableLock structure is only used by the sqlite3TableLock() and
   81246 ** codeTableLocks() functions.
   81247 */
   81248 struct TableLock {
   81249   int iDb;             /* The database containing the table to be locked */
   81250   int iTab;            /* The root page of the table to be locked */
   81251   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   81252   const char *zName;   /* Name of the table */
   81253 };
   81254 
   81255 /*
   81256 ** Record the fact that we want to lock a table at run-time.
   81257 **
   81258 ** The table to be locked has root page iTab and is found in database iDb.
   81259 ** A read or a write lock can be taken depending on isWritelock.
   81260 **
   81261 ** This routine just records the fact that the lock is desired.  The
   81262 ** code to make the lock occur is generated by a later call to
   81263 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   81264 */
   81265 SQLITE_PRIVATE void sqlite3TableLock(
   81266   Parse *pParse,     /* Parsing context */
   81267   int iDb,           /* Index of the database containing the table to lock */
   81268   int iTab,          /* Root page number of the table to be locked */
   81269   u8 isWriteLock,    /* True for a write lock */
   81270   const char *zName  /* Name of the table to be locked */
   81271 ){
   81272   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   81273   int i;
   81274   int nBytes;
   81275   TableLock *p;
   81276   assert( iDb>=0 );
   81277 
   81278   for(i=0; i<pToplevel->nTableLock; i++){
   81279     p = &pToplevel->aTableLock[i];
   81280     if( p->iDb==iDb && p->iTab==iTab ){
   81281       p->isWriteLock = (p->isWriteLock || isWriteLock);
   81282       return;
   81283     }
   81284   }
   81285 
   81286   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   81287   pToplevel->aTableLock =
   81288       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   81289   if( pToplevel->aTableLock ){
   81290     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   81291     p->iDb = iDb;
   81292     p->iTab = iTab;
   81293     p->isWriteLock = isWriteLock;
   81294     p->zName = zName;
   81295   }else{
   81296     pToplevel->nTableLock = 0;
   81297     pToplevel->db->mallocFailed = 1;
   81298   }
   81299 }
   81300 
   81301 /*
   81302 ** Code an OP_TableLock instruction for each table locked by the
   81303 ** statement (configured by calls to sqlite3TableLock()).
   81304 */
   81305 static void codeTableLocks(Parse *pParse){
   81306   int i;
   81307   Vdbe *pVdbe;
   81308 
   81309   pVdbe = sqlite3GetVdbe(pParse);
   81310   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   81311 
   81312   for(i=0; i<pParse->nTableLock; i++){
   81313     TableLock *p = &pParse->aTableLock[i];
   81314     int p1 = p->iDb;
   81315     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   81316                       p->zName, P4_STATIC);
   81317   }
   81318 }
   81319 #else
   81320   #define codeTableLocks(x)
   81321 #endif
   81322 
   81323 /*
   81324 ** This routine is called after a single SQL statement has been
   81325 ** parsed and a VDBE program to execute that statement has been
   81326 ** prepared.  This routine puts the finishing touches on the
   81327 ** VDBE program and resets the pParse structure for the next
   81328 ** parse.
   81329 **
   81330 ** Note that if an error occurred, it might be the case that
   81331 ** no VDBE code was generated.
   81332 */
   81333 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   81334   sqlite3 *db;
   81335   Vdbe *v;
   81336 
   81337   db = pParse->db;
   81338   if( db->mallocFailed ) return;
   81339   if( pParse->nested ) return;
   81340   if( pParse->nErr ) return;
   81341 
   81342   /* Begin by generating some termination code at the end of the
   81343   ** vdbe program
   81344   */
   81345   v = sqlite3GetVdbe(pParse);
   81346   assert( !pParse->isMultiWrite
   81347        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   81348   if( v ){
   81349     sqlite3VdbeAddOp0(v, OP_Halt);
   81350 
   81351     /* The cookie mask contains one bit for each database file open.
   81352     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   81353     ** set for each database that is used.  Generate code to start a
   81354     ** transaction on each used database and to verify the schema cookie
   81355     ** on each used database.
   81356     */
   81357     if( pParse->cookieGoto>0 ){
   81358       yDbMask mask;
   81359       int iDb;
   81360       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   81361       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   81362         if( (mask & pParse->cookieMask)==0 ) continue;
   81363         sqlite3VdbeUsesBtree(v, iDb);
   81364         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   81365         if( db->init.busy==0 ){
   81366           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81367           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
   81368                             iDb, pParse->cookieValue[iDb],
   81369                             db->aDb[iDb].pSchema->iGeneration);
   81370         }
   81371       }
   81372 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81373       {
   81374         int i;
   81375         for(i=0; i<pParse->nVtabLock; i++){
   81376           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   81377           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   81378         }
   81379         pParse->nVtabLock = 0;
   81380       }
   81381 #endif
   81382 
   81383       /* Once all the cookies have been verified and transactions opened,
   81384       ** obtain the required table-locks. This is a no-op unless the
   81385       ** shared-cache feature is enabled.
   81386       */
   81387       codeTableLocks(pParse);
   81388 
   81389       /* Initialize any AUTOINCREMENT data structures required.
   81390       */
   81391       sqlite3AutoincrementBegin(pParse);
   81392 
   81393       /* Finally, jump back to the beginning of the executable code. */
   81394       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
   81395     }
   81396   }
   81397 
   81398 
   81399   /* Get the VDBE program ready for execution
   81400   */
   81401   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   81402 #ifdef SQLITE_DEBUG
   81403     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   81404     sqlite3VdbeTrace(v, trace);
   81405 #endif
   81406     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   81407     /* A minimum of one cursor is required if autoincrement is used
   81408     *  See ticket [a696379c1f08866] */
   81409     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   81410     sqlite3VdbeMakeReady(v, pParse);
   81411     pParse->rc = SQLITE_DONE;
   81412     pParse->colNamesSet = 0;
   81413   }else{
   81414     pParse->rc = SQLITE_ERROR;
   81415   }
   81416   pParse->nTab = 0;
   81417   pParse->nMem = 0;
   81418   pParse->nSet = 0;
   81419   pParse->nVar = 0;
   81420   pParse->cookieMask = 0;
   81421   pParse->cookieGoto = 0;
   81422 }
   81423 
   81424 /*
   81425 ** Run the parser and code generator recursively in order to generate
   81426 ** code for the SQL statement given onto the end of the pParse context
   81427 ** currently under construction.  When the parser is run recursively
   81428 ** this way, the final OP_Halt is not appended and other initialization
   81429 ** and finalization steps are omitted because those are handling by the
   81430 ** outermost parser.
   81431 **
   81432 ** Not everything is nestable.  This facility is designed to permit
   81433 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   81434 ** care if you decide to try to use this routine for some other purposes.
   81435 */
   81436 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   81437   va_list ap;
   81438   char *zSql;
   81439   char *zErrMsg = 0;
   81440   sqlite3 *db = pParse->db;
   81441 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   81442   char saveBuf[SAVE_SZ];
   81443 
   81444   if( pParse->nErr ) return;
   81445   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   81446   va_start(ap, zFormat);
   81447   zSql = sqlite3VMPrintf(db, zFormat, ap);
   81448   va_end(ap);
   81449   if( zSql==0 ){
   81450     return;   /* A malloc must have failed */
   81451   }
   81452   pParse->nested++;
   81453   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   81454   memset(&pParse->nVar, 0, SAVE_SZ);
   81455   sqlite3RunParser(pParse, zSql, &zErrMsg);
   81456   sqlite3DbFree(db, zErrMsg);
   81457   sqlite3DbFree(db, zSql);
   81458   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   81459   pParse->nested--;
   81460 }
   81461 
   81462 /*
   81463 ** Locate the in-memory structure that describes a particular database
   81464 ** table given the name of that table and (optionally) the name of the
   81465 ** database containing the table.  Return NULL if not found.
   81466 **
   81467 ** If zDatabase is 0, all databases are searched for the table and the
   81468 ** first matching table is returned.  (No checking for duplicate table
   81469 ** names is done.)  The search order is TEMP first, then MAIN, then any
   81470 ** auxiliary databases added using the ATTACH command.
   81471 **
   81472 ** See also sqlite3LocateTable().
   81473 */
   81474 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   81475   Table *p = 0;
   81476   int i;
   81477   int nName;
   81478   assert( zName!=0 );
   81479   nName = sqlite3Strlen30(zName);
   81480   /* All mutexes are required for schema access.  Make sure we hold them. */
   81481   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   81482   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   81483     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   81484     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   81485     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   81486     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   81487     if( p ) break;
   81488   }
   81489   return p;
   81490 }
   81491 
   81492 /*
   81493 ** Locate the in-memory structure that describes a particular database
   81494 ** table given the name of that table and (optionally) the name of the
   81495 ** database containing the table.  Return NULL if not found.  Also leave an
   81496 ** error message in pParse->zErrMsg.
   81497 **
   81498 ** The difference between this routine and sqlite3FindTable() is that this
   81499 ** routine leaves an error message in pParse->zErrMsg where
   81500 ** sqlite3FindTable() does not.
   81501 */
   81502 SQLITE_PRIVATE Table *sqlite3LocateTable(
   81503   Parse *pParse,         /* context in which to report errors */
   81504   int isView,            /* True if looking for a VIEW rather than a TABLE */
   81505   const char *zName,     /* Name of the table we are looking for */
   81506   const char *zDbase     /* Name of the database.  Might be NULL */
   81507 ){
   81508   Table *p;
   81509 
   81510   /* Read the database schema. If an error occurs, leave an error message
   81511   ** and code in pParse and return NULL. */
   81512   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   81513     return 0;
   81514   }
   81515 
   81516   p = sqlite3FindTable(pParse->db, zName, zDbase);
   81517   if( p==0 ){
   81518     const char *zMsg = isView ? "no such view" : "no such table";
   81519     if( zDbase ){
   81520       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   81521     }else{
   81522       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   81523     }
   81524     pParse->checkSchema = 1;
   81525   }
   81526   return p;
   81527 }
   81528 
   81529 /*
   81530 ** Locate the in-memory structure that describes
   81531 ** a particular index given the name of that index
   81532 ** and the name of the database that contains the index.
   81533 ** Return NULL if not found.
   81534 **
   81535 ** If zDatabase is 0, all databases are searched for the
   81536 ** table and the first matching index is returned.  (No checking
   81537 ** for duplicate index names is done.)  The search order is
   81538 ** TEMP first, then MAIN, then any auxiliary databases added
   81539 ** using the ATTACH command.
   81540 */
   81541 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   81542   Index *p = 0;
   81543   int i;
   81544   int nName = sqlite3Strlen30(zName);
   81545   /* All mutexes are required for schema access.  Make sure we hold them. */
   81546   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   81547   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   81548     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   81549     Schema *pSchema = db->aDb[j].pSchema;
   81550     assert( pSchema );
   81551     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   81552     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   81553     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   81554     if( p ) break;
   81555   }
   81556   return p;
   81557 }
   81558 
   81559 /*
   81560 ** Reclaim the memory used by an index
   81561 */
   81562 static void freeIndex(sqlite3 *db, Index *p){
   81563 #ifndef SQLITE_OMIT_ANALYZE
   81564   sqlite3DeleteIndexSamples(db, p);
   81565 #endif
   81566   sqlite3DbFree(db, p->zColAff);
   81567   sqlite3DbFree(db, p);
   81568 }
   81569 
   81570 /*
   81571 ** For the index called zIdxName which is found in the database iDb,
   81572 ** unlike that index from its Table then remove the index from
   81573 ** the index hash table and free all memory structures associated
   81574 ** with the index.
   81575 */
   81576 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   81577   Index *pIndex;
   81578   int len;
   81579   Hash *pHash;
   81580 
   81581   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81582   pHash = &db->aDb[iDb].pSchema->idxHash;
   81583   len = sqlite3Strlen30(zIdxName);
   81584   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   81585   if( ALWAYS(pIndex) ){
   81586     if( pIndex->pTable->pIndex==pIndex ){
   81587       pIndex->pTable->pIndex = pIndex->pNext;
   81588     }else{
   81589       Index *p;
   81590       /* Justification of ALWAYS();  The index must be on the list of
   81591       ** indices. */
   81592       p = pIndex->pTable->pIndex;
   81593       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   81594       if( ALWAYS(p && p->pNext==pIndex) ){
   81595         p->pNext = pIndex->pNext;
   81596       }
   81597     }
   81598     freeIndex(db, pIndex);
   81599   }
   81600   db->flags |= SQLITE_InternChanges;
   81601 }
   81602 
   81603 /*
   81604 ** Erase all schema information from the in-memory hash tables of
   81605 ** a single database.  This routine is called to reclaim memory
   81606 ** before the database closes.  It is also called during a rollback
   81607 ** if there were schema changes during the transaction or if a
   81608 ** schema-cookie mismatch occurs.
   81609 **
   81610 ** If iDb<0 then reset the internal schema tables for all database
   81611 ** files.  If iDb>=0 then reset the internal schema for only the
   81612 ** single file indicated.
   81613 */
   81614 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   81615   int i, j;
   81616   assert( iDb<db->nDb );
   81617 
   81618   if( iDb>=0 ){
   81619     /* Case 1:  Reset the single schema identified by iDb */
   81620     Db *pDb = &db->aDb[iDb];
   81621     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81622     assert( pDb->pSchema!=0 );
   81623     sqlite3SchemaClear(pDb->pSchema);
   81624 
   81625     /* If any database other than TEMP is reset, then also reset TEMP
   81626     ** since TEMP might be holding triggers that reference tables in the
   81627     ** other database.
   81628     */
   81629     if( iDb!=1 ){
   81630       pDb = &db->aDb[1];
   81631       assert( pDb->pSchema!=0 );
   81632       sqlite3SchemaClear(pDb->pSchema);
   81633     }
   81634     return;
   81635   }
   81636   /* Case 2 (from here to the end): Reset all schemas for all attached
   81637   ** databases. */
   81638   assert( iDb<0 );
   81639   sqlite3BtreeEnterAll(db);
   81640   for(i=0; i<db->nDb; i++){
   81641     Db *pDb = &db->aDb[i];
   81642     if( pDb->pSchema ){
   81643       sqlite3SchemaClear(pDb->pSchema);
   81644     }
   81645   }
   81646   db->flags &= ~SQLITE_InternChanges;
   81647   sqlite3VtabUnlockList(db);
   81648   sqlite3BtreeLeaveAll(db);
   81649 
   81650   /* If one or more of the auxiliary database files has been closed,
   81651   ** then remove them from the auxiliary database list.  We take the
   81652   ** opportunity to do this here since we have just deleted all of the
   81653   ** schema hash tables and therefore do not have to make any changes
   81654   ** to any of those tables.
   81655   */
   81656   for(i=j=2; i<db->nDb; i++){
   81657     struct Db *pDb = &db->aDb[i];
   81658     if( pDb->pBt==0 ){
   81659       sqlite3DbFree(db, pDb->zName);
   81660       pDb->zName = 0;
   81661       continue;
   81662     }
   81663     if( j<i ){
   81664       db->aDb[j] = db->aDb[i];
   81665     }
   81666     j++;
   81667   }
   81668   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   81669   db->nDb = j;
   81670   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   81671     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   81672     sqlite3DbFree(db, db->aDb);
   81673     db->aDb = db->aDbStatic;
   81674   }
   81675 }
   81676 
   81677 /*
   81678 ** This routine is called when a commit occurs.
   81679 */
   81680 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   81681   db->flags &= ~SQLITE_InternChanges;
   81682 }
   81683 
   81684 /*
   81685 ** Delete memory allocated for the column names of a table or view (the
   81686 ** Table.aCol[] array).
   81687 */
   81688 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   81689   int i;
   81690   Column *pCol;
   81691   assert( pTable!=0 );
   81692   if( (pCol = pTable->aCol)!=0 ){
   81693     for(i=0; i<pTable->nCol; i++, pCol++){
   81694       sqlite3DbFree(db, pCol->zName);
   81695       sqlite3ExprDelete(db, pCol->pDflt);
   81696       sqlite3DbFree(db, pCol->zDflt);
   81697       sqlite3DbFree(db, pCol->zType);
   81698       sqlite3DbFree(db, pCol->zColl);
   81699     }
   81700     sqlite3DbFree(db, pTable->aCol);
   81701   }
   81702 }
   81703 
   81704 /*
   81705 ** Remove the memory data structures associated with the given
   81706 ** Table.  No changes are made to disk by this routine.
   81707 **
   81708 ** This routine just deletes the data structure.  It does not unlink
   81709 ** the table data structure from the hash table.  But it does destroy
   81710 ** memory structures of the indices and foreign keys associated with
   81711 ** the table.
   81712 */
   81713 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   81714   Index *pIndex, *pNext;
   81715 
   81716   assert( !pTable || pTable->nRef>0 );
   81717 
   81718   /* Do not delete the table until the reference count reaches zero. */
   81719   if( !pTable ) return;
   81720   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   81721 
   81722   /* Delete all indices associated with this table. */
   81723   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   81724     pNext = pIndex->pNext;
   81725     assert( pIndex->pSchema==pTable->pSchema );
   81726     if( !db || db->pnBytesFreed==0 ){
   81727       char *zName = pIndex->zName;
   81728       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   81729 	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
   81730       );
   81731       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   81732       assert( pOld==pIndex || pOld==0 );
   81733     }
   81734     freeIndex(db, pIndex);
   81735   }
   81736 
   81737   /* Delete any foreign keys attached to this table. */
   81738   sqlite3FkDelete(db, pTable);
   81739 
   81740   /* Delete the Table structure itself.
   81741   */
   81742   sqliteDeleteColumnNames(db, pTable);
   81743   sqlite3DbFree(db, pTable->zName);
   81744   sqlite3DbFree(db, pTable->zColAff);
   81745   sqlite3SelectDelete(db, pTable->pSelect);
   81746 #ifndef SQLITE_OMIT_CHECK
   81747   sqlite3ExprDelete(db, pTable->pCheck);
   81748 #endif
   81749 #ifndef SQLITE_OMIT_VIRTUALTABLE
   81750   sqlite3VtabClear(db, pTable);
   81751 #endif
   81752   sqlite3DbFree(db, pTable);
   81753 }
   81754 
   81755 /*
   81756 ** Unlink the given table from the hash tables and the delete the
   81757 ** table structure with all its indices and foreign keys.
   81758 */
   81759 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   81760   Table *p;
   81761   Db *pDb;
   81762 
   81763   assert( db!=0 );
   81764   assert( iDb>=0 && iDb<db->nDb );
   81765   assert( zTabName );
   81766   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   81767   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   81768   pDb = &db->aDb[iDb];
   81769   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   81770                         sqlite3Strlen30(zTabName),0);
   81771   sqlite3DeleteTable(db, p);
   81772   db->flags |= SQLITE_InternChanges;
   81773 }
   81774 
   81775 /*
   81776 ** Given a token, return a string that consists of the text of that
   81777 ** token.  Space to hold the returned string
   81778 ** is obtained from sqliteMalloc() and must be freed by the calling
   81779 ** function.
   81780 **
   81781 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   81782 ** surround the body of the token are removed.
   81783 **
   81784 ** Tokens are often just pointers into the original SQL text and so
   81785 ** are not \000 terminated and are not persistent.  The returned string
   81786 ** is \000 terminated and is persistent.
   81787 */
   81788 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   81789   char *zName;
   81790   if( pName ){
   81791     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   81792     sqlite3Dequote(zName);
   81793   }else{
   81794     zName = 0;
   81795   }
   81796   return zName;
   81797 }
   81798 
   81799 /*
   81800 ** Open the sqlite_master table stored in database number iDb for
   81801 ** writing. The table is opened using cursor 0.
   81802 */
   81803 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   81804   Vdbe *v = sqlite3GetVdbe(p);
   81805   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   81806   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
   81807   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
   81808   if( p->nTab==0 ){
   81809     p->nTab = 1;
   81810   }
   81811 }
   81812 
   81813 /*
   81814 ** Parameter zName points to a nul-terminated buffer containing the name
   81815 ** of a database ("main", "temp" or the name of an attached db). This
   81816 ** function returns the index of the named database in db->aDb[], or
   81817 ** -1 if the named db cannot be found.
   81818 */
   81819 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   81820   int i = -1;         /* Database number */
   81821   if( zName ){
   81822     Db *pDb;
   81823     int n = sqlite3Strlen30(zName);
   81824     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   81825       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   81826           0==sqlite3StrICmp(pDb->zName, zName) ){
   81827         break;
   81828       }
   81829     }
   81830   }
   81831   return i;
   81832 }
   81833 
   81834 /*
   81835 ** The token *pName contains the name of a database (either "main" or
   81836 ** "temp" or the name of an attached db). This routine returns the
   81837 ** index of the named database in db->aDb[], or -1 if the named db
   81838 ** does not exist.
   81839 */
   81840 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   81841   int i;                               /* Database number */
   81842   char *zName;                         /* Name we are searching for */
   81843   zName = sqlite3NameFromToken(db, pName);
   81844   i = sqlite3FindDbName(db, zName);
   81845   sqlite3DbFree(db, zName);
   81846   return i;
   81847 }
   81848 
   81849 /* The table or view or trigger name is passed to this routine via tokens
   81850 ** pName1 and pName2. If the table name was fully qualified, for example:
   81851 **
   81852 ** CREATE TABLE xxx.yyy (...);
   81853 **
   81854 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   81855 ** the table name is not fully qualified, i.e.:
   81856 **
   81857 ** CREATE TABLE yyy(...);
   81858 **
   81859 ** Then pName1 is set to "yyy" and pName2 is "".
   81860 **
   81861 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   81862 ** pName2) that stores the unqualified table name.  The index of the
   81863 ** database "xxx" is returned.
   81864 */
   81865 SQLITE_PRIVATE int sqlite3TwoPartName(
   81866   Parse *pParse,      /* Parsing and code generating context */
   81867   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   81868   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   81869   Token **pUnqual     /* Write the unqualified object name here */
   81870 ){
   81871   int iDb;                    /* Database holding the object */
   81872   sqlite3 *db = pParse->db;
   81873 
   81874   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   81875     if( db->init.busy ) {
   81876       sqlite3ErrorMsg(pParse, "corrupt database");
   81877       pParse->nErr++;
   81878       return -1;
   81879     }
   81880     *pUnqual = pName2;
   81881     iDb = sqlite3FindDb(db, pName1);
   81882     if( iDb<0 ){
   81883       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   81884       pParse->nErr++;
   81885       return -1;
   81886     }
   81887   }else{
   81888     assert( db->init.iDb==0 || db->init.busy );
   81889     iDb = db->init.iDb;
   81890     *pUnqual = pName1;
   81891   }
   81892   return iDb;
   81893 }
   81894 
   81895 /*
   81896 ** This routine is used to check if the UTF-8 string zName is a legal
   81897 ** unqualified name for a new schema object (table, index, view or
   81898 ** trigger). All names are legal except those that begin with the string
   81899 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   81900 ** is reserved for internal use.
   81901 */
   81902 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   81903   if( !pParse->db->init.busy && pParse->nested==0
   81904           && (pParse->db->flags & SQLITE_WriteSchema)==0
   81905           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   81906     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   81907     return SQLITE_ERROR;
   81908   }
   81909   return SQLITE_OK;
   81910 }
   81911 
   81912 /*
   81913 ** Begin constructing a new table representation in memory.  This is
   81914 ** the first of several action routines that get called in response
   81915 ** to a CREATE TABLE statement.  In particular, this routine is called
   81916 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   81917 ** flag is true if the table should be stored in the auxiliary database
   81918 ** file instead of in the main database file.  This is normally the case
   81919 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   81920 ** CREATE and TABLE.
   81921 **
   81922 ** The new table record is initialized and put in pParse->pNewTable.
   81923 ** As more of the CREATE TABLE statement is parsed, additional action
   81924 ** routines will be called to add more information to this record.
   81925 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   81926 ** is called to complete the construction of the new table record.
   81927 */
   81928 SQLITE_PRIVATE void sqlite3StartTable(
   81929   Parse *pParse,   /* Parser context */
   81930   Token *pName1,   /* First part of the name of the table or view */
   81931   Token *pName2,   /* Second part of the name of the table or view */
   81932   int isTemp,      /* True if this is a TEMP table */
   81933   int isView,      /* True if this is a VIEW */
   81934   int isVirtual,   /* True if this is a VIRTUAL table */
   81935   int noErr        /* Do nothing if table already exists */
   81936 ){
   81937   Table *pTable;
   81938   char *zName = 0; /* The name of the new table */
   81939   sqlite3 *db = pParse->db;
   81940   Vdbe *v;
   81941   int iDb;         /* Database number to create the table in */
   81942   Token *pName;    /* Unqualified name of the table to create */
   81943 
   81944   /* The table or view name to create is passed to this routine via tokens
   81945   ** pName1 and pName2. If the table name was fully qualified, for example:
   81946   **
   81947   ** CREATE TABLE xxx.yyy (...);
   81948   **
   81949   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   81950   ** the table name is not fully qualified, i.e.:
   81951   **
   81952   ** CREATE TABLE yyy(...);
   81953   **
   81954   ** Then pName1 is set to "yyy" and pName2 is "".
   81955   **
   81956   ** The call below sets the pName pointer to point at the token (pName1 or
   81957   ** pName2) that stores the unqualified table name. The variable iDb is
   81958   ** set to the index of the database that the table or view is to be
   81959   ** created in.
   81960   */
   81961   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   81962   if( iDb<0 ) return;
   81963   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   81964     /* If creating a temp table, the name may not be qualified. Unless
   81965     ** the database name is "temp" anyway.  */
   81966     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   81967     return;
   81968   }
   81969   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   81970 
   81971   pParse->sNameToken = *pName;
   81972   zName = sqlite3NameFromToken(db, pName);
   81973   if( zName==0 ) return;
   81974   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   81975     goto begin_table_error;
   81976   }
   81977   if( db->init.iDb==1 ) isTemp = 1;
   81978 #ifndef SQLITE_OMIT_AUTHORIZATION
   81979   assert( (isTemp & 1)==isTemp );
   81980   {
   81981     int code;
   81982     char *zDb = db->aDb[iDb].zName;
   81983     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   81984       goto begin_table_error;
   81985     }
   81986     if( isView ){
   81987       if( !OMIT_TEMPDB && isTemp ){
   81988         code = SQLITE_CREATE_TEMP_VIEW;
   81989       }else{
   81990         code = SQLITE_CREATE_VIEW;
   81991       }
   81992     }else{
   81993       if( !OMIT_TEMPDB && isTemp ){
   81994         code = SQLITE_CREATE_TEMP_TABLE;
   81995       }else{
   81996         code = SQLITE_CREATE_TABLE;
   81997       }
   81998     }
   81999     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   82000       goto begin_table_error;
   82001     }
   82002   }
   82003 #endif
   82004 
   82005   /* Make sure the new table name does not collide with an existing
   82006   ** index or table name in the same database.  Issue an error message if
   82007   ** it does. The exception is if the statement being parsed was passed
   82008   ** to an sqlite3_declare_vtab() call. In that case only the column names
   82009   ** and types will be used, so there is no need to test for namespace
   82010   ** collisions.
   82011   */
   82012   if( !IN_DECLARE_VTAB ){
   82013     char *zDb = db->aDb[iDb].zName;
   82014     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   82015       goto begin_table_error;
   82016     }
   82017     pTable = sqlite3FindTable(db, zName, zDb);
   82018     if( pTable ){
   82019       if( !noErr ){
   82020         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   82021       }else{
   82022         assert( !db->init.busy );
   82023         sqlite3CodeVerifySchema(pParse, iDb);
   82024       }
   82025       goto begin_table_error;
   82026     }
   82027     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   82028       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   82029       goto begin_table_error;
   82030     }
   82031   }
   82032 
   82033   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   82034   if( pTable==0 ){
   82035     db->mallocFailed = 1;
   82036     pParse->rc = SQLITE_NOMEM;
   82037     pParse->nErr++;
   82038     goto begin_table_error;
   82039   }
   82040   pTable->zName = zName;
   82041   pTable->iPKey = -1;
   82042   pTable->pSchema = db->aDb[iDb].pSchema;
   82043   pTable->nRef = 1;
   82044   pTable->nRowEst = 1000000;
   82045   assert( pParse->pNewTable==0 );
   82046   pParse->pNewTable = pTable;
   82047 
   82048   /* If this is the magic sqlite_sequence table used by autoincrement,
   82049   ** then record a pointer to this table in the main database structure
   82050   ** so that INSERT can find the table easily.
   82051   */
   82052 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82053   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   82054     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82055     pTable->pSchema->pSeqTab = pTable;
   82056   }
   82057 #endif
   82058 
   82059   /* Begin generating the code that will insert the table record into
   82060   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   82061   ** and allocate the record number for the table entry now.  Before any
   82062   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   82063   ** indices to be created and the table record must come before the
   82064   ** indices.  Hence, the record number for the table must be allocated
   82065   ** now.
   82066   */
   82067   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   82068     int j1;
   82069     int fileFormat;
   82070     int reg1, reg2, reg3;
   82071     sqlite3BeginWriteOperation(pParse, 0, iDb);
   82072 
   82073 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82074     if( isVirtual ){
   82075       sqlite3VdbeAddOp0(v, OP_VBegin);
   82076     }
   82077 #endif
   82078 
   82079     /* If the file format and encoding in the database have not been set,
   82080     ** set them now.
   82081     */
   82082     reg1 = pParse->regRowid = ++pParse->nMem;
   82083     reg2 = pParse->regRoot = ++pParse->nMem;
   82084     reg3 = ++pParse->nMem;
   82085     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   82086     sqlite3VdbeUsesBtree(v, iDb);
   82087     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
   82088     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   82089                   1 : SQLITE_MAX_FILE_FORMAT;
   82090     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   82091     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   82092     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   82093     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   82094     sqlite3VdbeJumpHere(v, j1);
   82095 
   82096     /* This just creates a place-holder record in the sqlite_master table.
   82097     ** The record created does not contain anything yet.  It will be replaced
   82098     ** by the real entry in code generated at sqlite3EndTable().
   82099     **
   82100     ** The rowid for the new entry is left in register pParse->regRowid.
   82101     ** The root page number of the new table is left in reg pParse->regRoot.
   82102     ** The rowid and root page number values are needed by the code that
   82103     ** sqlite3EndTable will generate.
   82104     */
   82105 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   82106     if( isView || isVirtual ){
   82107       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   82108     }else
   82109 #endif
   82110     {
   82111       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   82112     }
   82113     sqlite3OpenMasterTable(pParse, iDb);
   82114     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   82115     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   82116     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   82117     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   82118     sqlite3VdbeAddOp0(v, OP_Close);
   82119   }
   82120 
   82121   /* Normal (non-error) return. */
   82122   return;
   82123 
   82124   /* If an error occurs, we jump here */
   82125 begin_table_error:
   82126   sqlite3DbFree(db, zName);
   82127   return;
   82128 }
   82129 
   82130 /*
   82131 ** This macro is used to compare two strings in a case-insensitive manner.
   82132 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   82133 ** produces larger code.
   82134 **
   82135 ** WARNING: This macro is not compatible with the strcmp() family. It
   82136 ** returns true if the two strings are equal, otherwise false.
   82137 */
   82138 #define STRICMP(x, y) (\
   82139 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   82140 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   82141 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   82142 
   82143 /*
   82144 ** Add a new column to the table currently being constructed.
   82145 **
   82146 ** The parser calls this routine once for each column declaration
   82147 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   82148 ** first to get things going.  Then this routine is called for each
   82149 ** column.
   82150 */
   82151 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   82152   Table *p;
   82153   int i;
   82154   char *z;
   82155   Column *pCol;
   82156   sqlite3 *db = pParse->db;
   82157   if( (p = pParse->pNewTable)==0 ) return;
   82158 #if SQLITE_MAX_COLUMN
   82159   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   82160     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   82161     return;
   82162   }
   82163 #endif
   82164   z = sqlite3NameFromToken(db, pName);
   82165   if( z==0 ) return;
   82166   for(i=0; i<p->nCol; i++){
   82167     if( STRICMP(z, p->aCol[i].zName) ){
   82168       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   82169       sqlite3DbFree(db, z);
   82170       return;
   82171     }
   82172   }
   82173   if( (p->nCol & 0x7)==0 ){
   82174     Column *aNew;
   82175     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   82176     if( aNew==0 ){
   82177       sqlite3DbFree(db, z);
   82178       return;
   82179     }
   82180     p->aCol = aNew;
   82181   }
   82182   pCol = &p->aCol[p->nCol];
   82183   memset(pCol, 0, sizeof(p->aCol[0]));
   82184   pCol->zName = z;
   82185 
   82186   /* If there is no type specified, columns have the default affinity
   82187   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   82188   ** be called next to set pCol->affinity correctly.
   82189   */
   82190   pCol->affinity = SQLITE_AFF_NONE;
   82191   p->nCol++;
   82192 }
   82193 
   82194 /*
   82195 ** This routine is called by the parser while in the middle of
   82196 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   82197 ** been seen on a column.  This routine sets the notNull flag on
   82198 ** the column currently under construction.
   82199 */
   82200 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   82201   Table *p;
   82202   p = pParse->pNewTable;
   82203   if( p==0 || NEVER(p->nCol<1) ) return;
   82204   p->aCol[p->nCol-1].notNull = (u8)onError;
   82205 }
   82206 
   82207 /*
   82208 ** Scan the column type name zType (length nType) and return the
   82209 ** associated affinity type.
   82210 **
   82211 ** This routine does a case-independent search of zType for the
   82212 ** substrings in the following table. If one of the substrings is
   82213 ** found, the corresponding affinity is returned. If zType contains
   82214 ** more than one of the substrings, entries toward the top of
   82215 ** the table take priority. For example, if zType is 'BLOBINT',
   82216 ** SQLITE_AFF_INTEGER is returned.
   82217 **
   82218 ** Substring     | Affinity
   82219 ** --------------------------------
   82220 ** 'INT'         | SQLITE_AFF_INTEGER
   82221 ** 'CHAR'        | SQLITE_AFF_TEXT
   82222 ** 'CLOB'        | SQLITE_AFF_TEXT
   82223 ** 'TEXT'        | SQLITE_AFF_TEXT
   82224 ** 'BLOB'        | SQLITE_AFF_NONE
   82225 ** 'REAL'        | SQLITE_AFF_REAL
   82226 ** 'FLOA'        | SQLITE_AFF_REAL
   82227 ** 'DOUB'        | SQLITE_AFF_REAL
   82228 **
   82229 ** If none of the substrings in the above table are found,
   82230 ** SQLITE_AFF_NUMERIC is returned.
   82231 */
   82232 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
   82233   u32 h = 0;
   82234   char aff = SQLITE_AFF_NUMERIC;
   82235 
   82236   if( zIn ) while( zIn[0] ){
   82237     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   82238     zIn++;
   82239     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   82240       aff = SQLITE_AFF_TEXT;
   82241     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   82242       aff = SQLITE_AFF_TEXT;
   82243     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   82244       aff = SQLITE_AFF_TEXT;
   82245     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   82246         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   82247       aff = SQLITE_AFF_NONE;
   82248 #ifndef SQLITE_OMIT_FLOATING_POINT
   82249     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   82250         && aff==SQLITE_AFF_NUMERIC ){
   82251       aff = SQLITE_AFF_REAL;
   82252     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   82253         && aff==SQLITE_AFF_NUMERIC ){
   82254       aff = SQLITE_AFF_REAL;
   82255     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   82256         && aff==SQLITE_AFF_NUMERIC ){
   82257       aff = SQLITE_AFF_REAL;
   82258 #endif
   82259     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   82260       aff = SQLITE_AFF_INTEGER;
   82261       break;
   82262     }
   82263   }
   82264 
   82265   return aff;
   82266 }
   82267 
   82268 /*
   82269 ** This routine is called by the parser while in the middle of
   82270 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   82271 ** token in the sequence of tokens that describe the type of the
   82272 ** column currently under construction.   pLast is the last token
   82273 ** in the sequence.  Use this information to construct a string
   82274 ** that contains the typename of the column and store that string
   82275 ** in zType.
   82276 */
   82277 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   82278   Table *p;
   82279   Column *pCol;
   82280 
   82281   p = pParse->pNewTable;
   82282   if( p==0 || NEVER(p->nCol<1) ) return;
   82283   pCol = &p->aCol[p->nCol-1];
   82284   assert( pCol->zType==0 );
   82285   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   82286   pCol->affinity = sqlite3AffinityType(pCol->zType);
   82287 }
   82288 
   82289 /*
   82290 ** The expression is the default value for the most recently added column
   82291 ** of the table currently under construction.
   82292 **
   82293 ** Default value expressions must be constant.  Raise an exception if this
   82294 ** is not the case.
   82295 **
   82296 ** This routine is called by the parser while in the middle of
   82297 ** parsing a CREATE TABLE statement.
   82298 */
   82299 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   82300   Table *p;
   82301   Column *pCol;
   82302   sqlite3 *db = pParse->db;
   82303   p = pParse->pNewTable;
   82304   if( p!=0 ){
   82305     pCol = &(p->aCol[p->nCol-1]);
   82306     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   82307       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   82308           pCol->zName);
   82309     }else{
   82310       /* A copy of pExpr is used instead of the original, as pExpr contains
   82311       ** tokens that point to volatile memory. The 'span' of the expression
   82312       ** is required by pragma table_info.
   82313       */
   82314       sqlite3ExprDelete(db, pCol->pDflt);
   82315       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   82316       sqlite3DbFree(db, pCol->zDflt);
   82317       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   82318                                      (int)(pSpan->zEnd - pSpan->zStart));
   82319     }
   82320   }
   82321   sqlite3ExprDelete(db, pSpan->pExpr);
   82322 }
   82323 
   82324 /*
   82325 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   82326 ** of columns that form the primary key.  If pList is NULL, then the
   82327 ** most recently added column of the table is the primary key.
   82328 **
   82329 ** A table can have at most one primary key.  If the table already has
   82330 ** a primary key (and this is the second primary key) then create an
   82331 ** error.
   82332 **
   82333 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   82334 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   82335 ** field of the table under construction to be the index of the
   82336 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   82337 ** no INTEGER PRIMARY KEY.
   82338 **
   82339 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   82340 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   82341 */
   82342 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   82343   Parse *pParse,    /* Parsing context */
   82344   ExprList *pList,  /* List of field names to be indexed */
   82345   int onError,      /* What to do with a uniqueness conflict */
   82346   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   82347   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   82348 ){
   82349   Table *pTab = pParse->pNewTable;
   82350   char *zType = 0;
   82351   int iCol = -1, i;
   82352   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   82353   if( pTab->tabFlags & TF_HasPrimaryKey ){
   82354     sqlite3ErrorMsg(pParse,
   82355       "table \"%s\" has more than one primary key", pTab->zName);
   82356     goto primary_key_exit;
   82357   }
   82358   pTab->tabFlags |= TF_HasPrimaryKey;
   82359   if( pList==0 ){
   82360     iCol = pTab->nCol - 1;
   82361     pTab->aCol[iCol].isPrimKey = 1;
   82362   }else{
   82363     for(i=0; i<pList->nExpr; i++){
   82364       for(iCol=0; iCol<pTab->nCol; iCol++){
   82365         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   82366           break;
   82367         }
   82368       }
   82369       if( iCol<pTab->nCol ){
   82370         pTab->aCol[iCol].isPrimKey = 1;
   82371       }
   82372     }
   82373     if( pList->nExpr>1 ) iCol = -1;
   82374   }
   82375   if( iCol>=0 && iCol<pTab->nCol ){
   82376     zType = pTab->aCol[iCol].zType;
   82377   }
   82378   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
   82379         && sortOrder==SQLITE_SO_ASC ){
   82380     pTab->iPKey = iCol;
   82381     pTab->keyConf = (u8)onError;
   82382     assert( autoInc==0 || autoInc==1 );
   82383     pTab->tabFlags |= autoInc*TF_Autoincrement;
   82384   }else if( autoInc ){
   82385 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82386     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   82387        "INTEGER PRIMARY KEY");
   82388 #endif
   82389   }else{
   82390     Index *p;
   82391     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
   82392     if( p ){
   82393       p->autoIndex = 2;
   82394     }
   82395     pList = 0;
   82396   }
   82397 
   82398 primary_key_exit:
   82399   sqlite3ExprListDelete(pParse->db, pList);
   82400   return;
   82401 }
   82402 
   82403 /*
   82404 ** Add a new CHECK constraint to the table currently under construction.
   82405 */
   82406 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   82407   Parse *pParse,    /* Parsing context */
   82408   Expr *pCheckExpr  /* The check expression */
   82409 ){
   82410   sqlite3 *db = pParse->db;
   82411 #ifndef SQLITE_OMIT_CHECK
   82412   Table *pTab = pParse->pNewTable;
   82413   if( pTab && !IN_DECLARE_VTAB ){
   82414     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
   82415   }else
   82416 #endif
   82417   {
   82418     sqlite3ExprDelete(db, pCheckExpr);
   82419   }
   82420 }
   82421 
   82422 /*
   82423 ** Set the collation function of the most recently parsed table column
   82424 ** to the CollSeq given.
   82425 */
   82426 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   82427   Table *p;
   82428   int i;
   82429   char *zColl;              /* Dequoted name of collation sequence */
   82430   sqlite3 *db;
   82431 
   82432   if( (p = pParse->pNewTable)==0 ) return;
   82433   i = p->nCol-1;
   82434   db = pParse->db;
   82435   zColl = sqlite3NameFromToken(db, pToken);
   82436   if( !zColl ) return;
   82437 
   82438   if( sqlite3LocateCollSeq(pParse, zColl) ){
   82439     Index *pIdx;
   82440     p->aCol[i].zColl = zColl;
   82441 
   82442     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   82443     ** then an index may have been created on this column before the
   82444     ** collation type was added. Correct this if it is the case.
   82445     */
   82446     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   82447       assert( pIdx->nColumn==1 );
   82448       if( pIdx->aiColumn[0]==i ){
   82449         pIdx->azColl[0] = p->aCol[i].zColl;
   82450       }
   82451     }
   82452   }else{
   82453     sqlite3DbFree(db, zColl);
   82454   }
   82455 }
   82456 
   82457 /*
   82458 ** This function returns the collation sequence for database native text
   82459 ** encoding identified by the string zName, length nName.
   82460 **
   82461 ** If the requested collation sequence is not available, or not available
   82462 ** in the database native encoding, the collation factory is invoked to
   82463 ** request it. If the collation factory does not supply such a sequence,
   82464 ** and the sequence is available in another text encoding, then that is
   82465 ** returned instead.
   82466 **
   82467 ** If no versions of the requested collations sequence are available, or
   82468 ** another error occurs, NULL is returned and an error message written into
   82469 ** pParse.
   82470 **
   82471 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   82472 ** invokes the collation factory if the named collation cannot be found
   82473 ** and generates an error message.
   82474 **
   82475 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   82476 */
   82477 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   82478   sqlite3 *db = pParse->db;
   82479   u8 enc = ENC(db);
   82480   u8 initbusy = db->init.busy;
   82481   CollSeq *pColl;
   82482 
   82483   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   82484   if( !initbusy && (!pColl || !pColl->xCmp) ){
   82485     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
   82486     if( !pColl ){
   82487       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   82488     }
   82489   }
   82490 
   82491   return pColl;
   82492 }
   82493 
   82494 
   82495 /*
   82496 ** Generate code that will increment the schema cookie.
   82497 **
   82498 ** The schema cookie is used to determine when the schema for the
   82499 ** database changes.  After each schema change, the cookie value
   82500 ** changes.  When a process first reads the schema it records the
   82501 ** cookie.  Thereafter, whenever it goes to access the database,
   82502 ** it checks the cookie to make sure the schema has not changed
   82503 ** since it was last read.
   82504 **
   82505 ** This plan is not completely bullet-proof.  It is possible for
   82506 ** the schema to change multiple times and for the cookie to be
   82507 ** set back to prior value.  But schema changes are infrequent
   82508 ** and the probability of hitting the same cookie value is only
   82509 ** 1 chance in 2^32.  So we're safe enough.
   82510 */
   82511 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   82512   int r1 = sqlite3GetTempReg(pParse);
   82513   sqlite3 *db = pParse->db;
   82514   Vdbe *v = pParse->pVdbe;
   82515   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82516   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   82517   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   82518   sqlite3ReleaseTempReg(pParse, r1);
   82519 }
   82520 
   82521 /*
   82522 ** Measure the number of characters needed to output the given
   82523 ** identifier.  The number returned includes any quotes used
   82524 ** but does not include the null terminator.
   82525 **
   82526 ** The estimate is conservative.  It might be larger that what is
   82527 ** really needed.
   82528 */
   82529 static int identLength(const char *z){
   82530   int n;
   82531   for(n=0; *z; n++, z++){
   82532     if( *z=='"' ){ n++; }
   82533   }
   82534   return n + 2;
   82535 }
   82536 
   82537 /*
   82538 ** The first parameter is a pointer to an output buffer. The second
   82539 ** parameter is a pointer to an integer that contains the offset at
   82540 ** which to write into the output buffer. This function copies the
   82541 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   82542 ** to the specified offset in the buffer and updates *pIdx to refer
   82543 ** to the first byte after the last byte written before returning.
   82544 **
   82545 ** If the string zSignedIdent consists entirely of alpha-numeric
   82546 ** characters, does not begin with a digit and is not an SQL keyword,
   82547 ** then it is copied to the output buffer exactly as it is. Otherwise,
   82548 ** it is quoted using double-quotes.
   82549 */
   82550 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   82551   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   82552   int i, j, needQuote;
   82553   i = *pIdx;
   82554 
   82555   for(j=0; zIdent[j]; j++){
   82556     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   82557   }
   82558   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
   82559   if( !needQuote ){
   82560     needQuote = zIdent[j];
   82561   }
   82562 
   82563   if( needQuote ) z[i++] = '"';
   82564   for(j=0; zIdent[j]; j++){
   82565     z[i++] = zIdent[j];
   82566     if( zIdent[j]=='"' ) z[i++] = '"';
   82567   }
   82568   if( needQuote ) z[i++] = '"';
   82569   z[i] = 0;
   82570   *pIdx = i;
   82571 }
   82572 
   82573 /*
   82574 ** Generate a CREATE TABLE statement appropriate for the given
   82575 ** table.  Memory to hold the text of the statement is obtained
   82576 ** from sqliteMalloc() and must be freed by the calling function.
   82577 */
   82578 static char *createTableStmt(sqlite3 *db, Table *p){
   82579   int i, k, n;
   82580   char *zStmt;
   82581   char *zSep, *zSep2, *zEnd;
   82582   Column *pCol;
   82583   n = 0;
   82584   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   82585     n += identLength(pCol->zName) + 5;
   82586   }
   82587   n += identLength(p->zName);
   82588   if( n<50 ){
   82589     zSep = "";
   82590     zSep2 = ",";
   82591     zEnd = ")";
   82592   }else{
   82593     zSep = "\n  ";
   82594     zSep2 = ",\n  ";
   82595     zEnd = "\n)";
   82596   }
   82597   n += 35 + 6*p->nCol;
   82598   zStmt = sqlite3DbMallocRaw(0, n);
   82599   if( zStmt==0 ){
   82600     db->mallocFailed = 1;
   82601     return 0;
   82602   }
   82603   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   82604   k = sqlite3Strlen30(zStmt);
   82605   identPut(zStmt, &k, p->zName);
   82606   zStmt[k++] = '(';
   82607   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   82608     static const char * const azType[] = {
   82609         /* SQLITE_AFF_TEXT    */ " TEXT",
   82610         /* SQLITE_AFF_NONE    */ "",
   82611         /* SQLITE_AFF_NUMERIC */ " NUM",
   82612         /* SQLITE_AFF_INTEGER */ " INT",
   82613         /* SQLITE_AFF_REAL    */ " REAL"
   82614     };
   82615     int len;
   82616     const char *zType;
   82617 
   82618     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   82619     k += sqlite3Strlen30(&zStmt[k]);
   82620     zSep = zSep2;
   82621     identPut(zStmt, &k, pCol->zName);
   82622     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   82623     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
   82624     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   82625     testcase( pCol->affinity==SQLITE_AFF_NONE );
   82626     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   82627     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   82628     testcase( pCol->affinity==SQLITE_AFF_REAL );
   82629 
   82630     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   82631     len = sqlite3Strlen30(zType);
   82632     assert( pCol->affinity==SQLITE_AFF_NONE
   82633             || pCol->affinity==sqlite3AffinityType(zType) );
   82634     memcpy(&zStmt[k], zType, len);
   82635     k += len;
   82636     assert( k<=n );
   82637   }
   82638   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   82639   return zStmt;
   82640 }
   82641 
   82642 /*
   82643 ** This routine is called to report the final ")" that terminates
   82644 ** a CREATE TABLE statement.
   82645 **
   82646 ** The table structure that other action routines have been building
   82647 ** is added to the internal hash tables, assuming no errors have
   82648 ** occurred.
   82649 **
   82650 ** An entry for the table is made in the master table on disk, unless
   82651 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   82652 ** it means we are reading the sqlite_master table because we just
   82653 ** connected to the database or because the sqlite_master table has
   82654 ** recently changed, so the entry for this table already exists in
   82655 ** the sqlite_master table.  We do not want to create it again.
   82656 **
   82657 ** If the pSelect argument is not NULL, it means that this routine
   82658 ** was called to create a table generated from a
   82659 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   82660 ** the new table will match the result set of the SELECT.
   82661 */
   82662 SQLITE_PRIVATE void sqlite3EndTable(
   82663   Parse *pParse,          /* Parse context */
   82664   Token *pCons,           /* The ',' token after the last column defn. */
   82665   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
   82666   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   82667 ){
   82668   Table *p;
   82669   sqlite3 *db = pParse->db;
   82670   int iDb;
   82671 
   82672   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   82673     return;
   82674   }
   82675   p = pParse->pNewTable;
   82676   if( p==0 ) return;
   82677 
   82678   assert( !db->init.busy || !pSelect );
   82679 
   82680   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   82681 
   82682 #ifndef SQLITE_OMIT_CHECK
   82683   /* Resolve names in all CHECK constraint expressions.
   82684   */
   82685   if( p->pCheck ){
   82686     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   82687     NameContext sNC;                /* Name context for pParse->pNewTable */
   82688 
   82689     memset(&sNC, 0, sizeof(sNC));
   82690     memset(&sSrc, 0, sizeof(sSrc));
   82691     sSrc.nSrc = 1;
   82692     sSrc.a[0].zName = p->zName;
   82693     sSrc.a[0].pTab = p;
   82694     sSrc.a[0].iCursor = -1;
   82695     sNC.pParse = pParse;
   82696     sNC.pSrcList = &sSrc;
   82697     sNC.isCheck = 1;
   82698     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
   82699       return;
   82700     }
   82701   }
   82702 #endif /* !defined(SQLITE_OMIT_CHECK) */
   82703 
   82704   /* If the db->init.busy is 1 it means we are reading the SQL off the
   82705   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   82706   ** So do not write to the disk again.  Extract the root page number
   82707   ** for the table from the db->init.newTnum field.  (The page number
   82708   ** should have been put there by the sqliteOpenCb routine.)
   82709   */
   82710   if( db->init.busy ){
   82711     p->tnum = db->init.newTnum;
   82712   }
   82713 
   82714   /* If not initializing, then create a record for the new table
   82715   ** in the SQLITE_MASTER table of the database.
   82716   **
   82717   ** If this is a TEMPORARY table, write the entry into the auxiliary
   82718   ** file instead of into the main database file.
   82719   */
   82720   if( !db->init.busy ){
   82721     int n;
   82722     Vdbe *v;
   82723     char *zType;    /* "view" or "table" */
   82724     char *zType2;   /* "VIEW" or "TABLE" */
   82725     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   82726 
   82727     v = sqlite3GetVdbe(pParse);
   82728     if( NEVER(v==0) ) return;
   82729 
   82730     sqlite3VdbeAddOp1(v, OP_Close, 0);
   82731 
   82732     /*
   82733     ** Initialize zType for the new view or table.
   82734     */
   82735     if( p->pSelect==0 ){
   82736       /* A regular table */
   82737       zType = "table";
   82738       zType2 = "TABLE";
   82739 #ifndef SQLITE_OMIT_VIEW
   82740     }else{
   82741       /* A view */
   82742       zType = "view";
   82743       zType2 = "VIEW";
   82744 #endif
   82745     }
   82746 
   82747     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   82748     ** statement to populate the new table. The root-page number for the
   82749     ** new table is in register pParse->regRoot.
   82750     **
   82751     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   82752     ** suitable state to query for the column names and types to be used
   82753     ** by the new table.
   82754     **
   82755     ** A shared-cache write-lock is not required to write to the new table,
   82756     ** as a schema-lock must have already been obtained to create it. Since
   82757     ** a schema-lock excludes all other database users, the write-lock would
   82758     ** be redundant.
   82759     */
   82760     if( pSelect ){
   82761       SelectDest dest;
   82762       Table *pSelTab;
   82763 
   82764       assert(pParse->nTab==1);
   82765       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   82766       sqlite3VdbeChangeP5(v, 1);
   82767       pParse->nTab = 2;
   82768       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   82769       sqlite3Select(pParse, pSelect, &dest);
   82770       sqlite3VdbeAddOp1(v, OP_Close, 1);
   82771       if( pParse->nErr==0 ){
   82772         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   82773         if( pSelTab==0 ) return;
   82774         assert( p->aCol==0 );
   82775         p->nCol = pSelTab->nCol;
   82776         p->aCol = pSelTab->aCol;
   82777         pSelTab->nCol = 0;
   82778         pSelTab->aCol = 0;
   82779         sqlite3DeleteTable(db, pSelTab);
   82780       }
   82781     }
   82782 
   82783     /* Compute the complete text of the CREATE statement */
   82784     if( pSelect ){
   82785       zStmt = createTableStmt(db, p);
   82786     }else{
   82787       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
   82788       zStmt = sqlite3MPrintf(db,
   82789           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   82790       );
   82791     }
   82792 
   82793     /* A slot for the record has already been allocated in the
   82794     ** SQLITE_MASTER table.  We just need to update that slot with all
   82795     ** the information we've collected.
   82796     */
   82797     sqlite3NestedParse(pParse,
   82798       "UPDATE %Q.%s "
   82799          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   82800        "WHERE rowid=#%d",
   82801       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   82802       zType,
   82803       p->zName,
   82804       p->zName,
   82805       pParse->regRoot,
   82806       zStmt,
   82807       pParse->regRowid
   82808     );
   82809     sqlite3DbFree(db, zStmt);
   82810     sqlite3ChangeCookie(pParse, iDb);
   82811 
   82812 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82813     /* Check to see if we need to create an sqlite_sequence table for
   82814     ** keeping track of autoincrement keys.
   82815     */
   82816     if( p->tabFlags & TF_Autoincrement ){
   82817       Db *pDb = &db->aDb[iDb];
   82818       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82819       if( pDb->pSchema->pSeqTab==0 ){
   82820         sqlite3NestedParse(pParse,
   82821           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   82822           pDb->zName
   82823         );
   82824       }
   82825     }
   82826 #endif
   82827 
   82828     /* Reparse everything to update our internal data structures */
   82829     sqlite3VdbeAddParseSchemaOp(v, iDb,
   82830                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
   82831   }
   82832 
   82833 
   82834   /* Add the table to the in-memory representation of the database.
   82835   */
   82836   if( db->init.busy ){
   82837     Table *pOld;
   82838     Schema *pSchema = p->pSchema;
   82839     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   82840     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   82841                              sqlite3Strlen30(p->zName),p);
   82842     if( pOld ){
   82843       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   82844       db->mallocFailed = 1;
   82845       return;
   82846     }
   82847     pParse->pNewTable = 0;
   82848     db->flags |= SQLITE_InternChanges;
   82849 
   82850 #ifndef SQLITE_OMIT_ALTERTABLE
   82851     if( !p->pSelect ){
   82852       const char *zName = (const char *)pParse->sNameToken.z;
   82853       int nName;
   82854       assert( !pSelect && pCons && pEnd );
   82855       if( pCons->z==0 ){
   82856         pCons = pEnd;
   82857       }
   82858       nName = (int)((const char *)pCons->z - zName);
   82859       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   82860     }
   82861 #endif
   82862   }
   82863 }
   82864 
   82865 #ifndef SQLITE_OMIT_VIEW
   82866 /*
   82867 ** The parser calls this routine in order to create a new VIEW
   82868 */
   82869 SQLITE_PRIVATE void sqlite3CreateView(
   82870   Parse *pParse,     /* The parsing context */
   82871   Token *pBegin,     /* The CREATE token that begins the statement */
   82872   Token *pName1,     /* The token that holds the name of the view */
   82873   Token *pName2,     /* The token that holds the name of the view */
   82874   Select *pSelect,   /* A SELECT statement that will become the new view */
   82875   int isTemp,        /* TRUE for a TEMPORARY view */
   82876   int noErr          /* Suppress error messages if VIEW already exists */
   82877 ){
   82878   Table *p;
   82879   int n;
   82880   const char *z;
   82881   Token sEnd;
   82882   DbFixer sFix;
   82883   Token *pName = 0;
   82884   int iDb;
   82885   sqlite3 *db = pParse->db;
   82886 
   82887   if( pParse->nVar>0 ){
   82888     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   82889     sqlite3SelectDelete(db, pSelect);
   82890     return;
   82891   }
   82892   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   82893   p = pParse->pNewTable;
   82894   if( p==0 || pParse->nErr ){
   82895     sqlite3SelectDelete(db, pSelect);
   82896     return;
   82897   }
   82898   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   82899   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   82900   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
   82901     && sqlite3FixSelect(&sFix, pSelect)
   82902   ){
   82903     sqlite3SelectDelete(db, pSelect);
   82904     return;
   82905   }
   82906 
   82907   /* Make a copy of the entire SELECT statement that defines the view.
   82908   ** This will force all the Expr.token.z values to be dynamically
   82909   ** allocated rather than point to the input string - which means that
   82910   ** they will persist after the current sqlite3_exec() call returns.
   82911   */
   82912   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   82913   sqlite3SelectDelete(db, pSelect);
   82914   if( db->mallocFailed ){
   82915     return;
   82916   }
   82917   if( !db->init.busy ){
   82918     sqlite3ViewGetColumnNames(pParse, p);
   82919   }
   82920 
   82921   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   82922   ** the end.
   82923   */
   82924   sEnd = pParse->sLastToken;
   82925   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   82926     sEnd.z += sEnd.n;
   82927   }
   82928   sEnd.n = 0;
   82929   n = (int)(sEnd.z - pBegin->z);
   82930   z = pBegin->z;
   82931   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   82932   sEnd.z = &z[n-1];
   82933   sEnd.n = 1;
   82934 
   82935   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   82936   sqlite3EndTable(pParse, 0, &sEnd, 0);
   82937   return;
   82938 }
   82939 #endif /* SQLITE_OMIT_VIEW */
   82940 
   82941 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   82942 /*
   82943 ** The Table structure pTable is really a VIEW.  Fill in the names of
   82944 ** the columns of the view in the pTable structure.  Return the number
   82945 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   82946 */
   82947 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   82948   Table *pSelTab;   /* A fake table from which we get the result set */
   82949   Select *pSel;     /* Copy of the SELECT that implements the view */
   82950   int nErr = 0;     /* Number of errors encountered */
   82951   int n;            /* Temporarily holds the number of cursors assigned */
   82952   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   82953   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   82954 
   82955   assert( pTable );
   82956 
   82957 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82958   if( sqlite3VtabCallConnect(pParse, pTable) ){
   82959     return SQLITE_ERROR;
   82960   }
   82961   if( IsVirtual(pTable) ) return 0;
   82962 #endif
   82963 
   82964 #ifndef SQLITE_OMIT_VIEW
   82965   /* A positive nCol means the columns names for this view are
   82966   ** already known.
   82967   */
   82968   if( pTable->nCol>0 ) return 0;
   82969 
   82970   /* A negative nCol is a special marker meaning that we are currently
   82971   ** trying to compute the column names.  If we enter this routine with
   82972   ** a negative nCol, it means two or more views form a loop, like this:
   82973   **
   82974   **     CREATE VIEW one AS SELECT * FROM two;
   82975   **     CREATE VIEW two AS SELECT * FROM one;
   82976   **
   82977   ** Actually, the error above is now caught prior to reaching this point.
   82978   ** But the following test is still important as it does come up
   82979   ** in the following:
   82980   **
   82981   **     CREATE TABLE main.ex1(a);
   82982   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   82983   **     SELECT * FROM temp.ex1;
   82984   */
   82985   if( pTable->nCol<0 ){
   82986     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   82987     return 1;
   82988   }
   82989   assert( pTable->nCol>=0 );
   82990 
   82991   /* If we get this far, it means we need to compute the table names.
   82992   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   82993   ** "*" elements in the results set of the view and will assign cursors
   82994   ** to the elements of the FROM clause.  But we do not want these changes
   82995   ** to be permanent.  So the computation is done on a copy of the SELECT
   82996   ** statement that defines the view.
   82997   */
   82998   assert( pTable->pSelect );
   82999   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   83000   if( pSel ){
   83001     u8 enableLookaside = db->lookaside.bEnabled;
   83002     n = pParse->nTab;
   83003     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   83004     pTable->nCol = -1;
   83005     db->lookaside.bEnabled = 0;
   83006 #ifndef SQLITE_OMIT_AUTHORIZATION
   83007     xAuth = db->xAuth;
   83008     db->xAuth = 0;
   83009     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   83010     db->xAuth = xAuth;
   83011 #else
   83012     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   83013 #endif
   83014     db->lookaside.bEnabled = enableLookaside;
   83015     pParse->nTab = n;
   83016     if( pSelTab ){
   83017       assert( pTable->aCol==0 );
   83018       pTable->nCol = pSelTab->nCol;
   83019       pTable->aCol = pSelTab->aCol;
   83020       pSelTab->nCol = 0;
   83021       pSelTab->aCol = 0;
   83022       sqlite3DeleteTable(db, pSelTab);
   83023       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
   83024       pTable->pSchema->flags |= DB_UnresetViews;
   83025     }else{
   83026       pTable->nCol = 0;
   83027       nErr++;
   83028     }
   83029     sqlite3SelectDelete(db, pSel);
   83030   } else {
   83031     nErr++;
   83032   }
   83033 #endif /* SQLITE_OMIT_VIEW */
   83034   return nErr;
   83035 }
   83036 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   83037 
   83038 #ifndef SQLITE_OMIT_VIEW
   83039 /*
   83040 ** Clear the column names from every VIEW in database idx.
   83041 */
   83042 static void sqliteViewResetAll(sqlite3 *db, int idx){
   83043   HashElem *i;
   83044   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
   83045   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   83046   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   83047     Table *pTab = sqliteHashData(i);
   83048     if( pTab->pSelect ){
   83049       sqliteDeleteColumnNames(db, pTab);
   83050       pTab->aCol = 0;
   83051       pTab->nCol = 0;
   83052     }
   83053   }
   83054   DbClearProperty(db, idx, DB_UnresetViews);
   83055 }
   83056 #else
   83057 # define sqliteViewResetAll(A,B)
   83058 #endif /* SQLITE_OMIT_VIEW */
   83059 
   83060 /*
   83061 ** This function is called by the VDBE to adjust the internal schema
   83062 ** used by SQLite when the btree layer moves a table root page. The
   83063 ** root-page of a table or index in database iDb has changed from iFrom
   83064 ** to iTo.
   83065 **
   83066 ** Ticket #1728:  The symbol table might still contain information
   83067 ** on tables and/or indices that are the process of being deleted.
   83068 ** If you are unlucky, one of those deleted indices or tables might
   83069 ** have the same rootpage number as the real table or index that is
   83070 ** being moved.  So we cannot stop searching after the first match
   83071 ** because the first match might be for one of the deleted indices
   83072 ** or tables and not the table/index that is actually being moved.
   83073 ** We must continue looping until all tables and indices with
   83074 ** rootpage==iFrom have been converted to have a rootpage of iTo
   83075 ** in order to be certain that we got the right one.
   83076 */
   83077 #ifndef SQLITE_OMIT_AUTOVACUUM
   83078 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
   83079   HashElem *pElem;
   83080   Hash *pHash;
   83081   Db *pDb;
   83082 
   83083   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   83084   pDb = &db->aDb[iDb];
   83085   pHash = &pDb->pSchema->tblHash;
   83086   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   83087     Table *pTab = sqliteHashData(pElem);
   83088     if( pTab->tnum==iFrom ){
   83089       pTab->tnum = iTo;
   83090     }
   83091   }
   83092   pHash = &pDb->pSchema->idxHash;
   83093   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   83094     Index *pIdx = sqliteHashData(pElem);
   83095     if( pIdx->tnum==iFrom ){
   83096       pIdx->tnum = iTo;
   83097     }
   83098   }
   83099 }
   83100 #endif
   83101 
   83102 /*
   83103 ** Write code to erase the table with root-page iTable from database iDb.
   83104 ** Also write code to modify the sqlite_master table and internal schema
   83105 ** if a root-page of another table is moved by the btree-layer whilst
   83106 ** erasing iTable (this can happen with an auto-vacuum database).
   83107 */
   83108 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   83109   Vdbe *v = sqlite3GetVdbe(pParse);
   83110   int r1 = sqlite3GetTempReg(pParse);
   83111   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   83112   sqlite3MayAbort(pParse);
   83113 #ifndef SQLITE_OMIT_AUTOVACUUM
   83114   /* OP_Destroy stores an in integer r1. If this integer
   83115   ** is non-zero, then it is the root page number of a table moved to
   83116   ** location iTable. The following code modifies the sqlite_master table to
   83117   ** reflect this.
   83118   **
   83119   ** The "#NNN" in the SQL is a special constant that means whatever value
   83120   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   83121   ** token for additional information.
   83122   */
   83123   sqlite3NestedParse(pParse,
   83124      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   83125      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   83126 #endif
   83127   sqlite3ReleaseTempReg(pParse, r1);
   83128 }
   83129 
   83130 /*
   83131 ** Write VDBE code to erase table pTab and all associated indices on disk.
   83132 ** Code to update the sqlite_master tables and internal schema definitions
   83133 ** in case a root-page belonging to another table is moved by the btree layer
   83134 ** is also added (this can happen with an auto-vacuum database).
   83135 */
   83136 static void destroyTable(Parse *pParse, Table *pTab){
   83137 #ifdef SQLITE_OMIT_AUTOVACUUM
   83138   Index *pIdx;
   83139   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83140   destroyRootPage(pParse, pTab->tnum, iDb);
   83141   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83142     destroyRootPage(pParse, pIdx->tnum, iDb);
   83143   }
   83144 #else
   83145   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   83146   ** is not defined), then it is important to call OP_Destroy on the
   83147   ** table and index root-pages in order, starting with the numerically
   83148   ** largest root-page number. This guarantees that none of the root-pages
   83149   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   83150   ** following were coded:
   83151   **
   83152   ** OP_Destroy 4 0
   83153   ** ...
   83154   ** OP_Destroy 5 0
   83155   **
   83156   ** and root page 5 happened to be the largest root-page number in the
   83157   ** database, then root page 5 would be moved to page 4 by the
   83158   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   83159   ** a free-list page.
   83160   */
   83161   int iTab = pTab->tnum;
   83162   int iDestroyed = 0;
   83163 
   83164   while( 1 ){
   83165     Index *pIdx;
   83166     int iLargest = 0;
   83167 
   83168     if( iDestroyed==0 || iTab<iDestroyed ){
   83169       iLargest = iTab;
   83170     }
   83171     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83172       int iIdx = pIdx->tnum;
   83173       assert( pIdx->pSchema==pTab->pSchema );
   83174       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   83175         iLargest = iIdx;
   83176       }
   83177     }
   83178     if( iLargest==0 ){
   83179       return;
   83180     }else{
   83181       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83182       destroyRootPage(pParse, iLargest, iDb);
   83183       iDestroyed = iLargest;
   83184     }
   83185   }
   83186 #endif
   83187 }
   83188 
   83189 /*
   83190 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
   83191 ** after a DROP INDEX or DROP TABLE command.
   83192 */
   83193 static void sqlite3ClearStatTables(
   83194   Parse *pParse,         /* The parsing context */
   83195   int iDb,               /* The database number */
   83196   const char *zType,     /* "idx" or "tbl" */
   83197   const char *zName      /* Name of index or table */
   83198 ){
   83199   int i;
   83200   const char *zDbName = pParse->db->aDb[iDb].zName;
   83201   for(i=1; i<=3; i++){
   83202     char zTab[24];
   83203     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
   83204     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
   83205       sqlite3NestedParse(pParse,
   83206         "DELETE FROM %Q.%s WHERE %s=%Q",
   83207         zDbName, zTab, zType, zName
   83208       );
   83209     }
   83210   }
   83211 }
   83212 
   83213 /*
   83214 ** Generate code to drop a table.
   83215 */
   83216 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
   83217   Vdbe *v;
   83218   sqlite3 *db = pParse->db;
   83219   Trigger *pTrigger;
   83220   Db *pDb = &db->aDb[iDb];
   83221 
   83222   v = sqlite3GetVdbe(pParse);
   83223   assert( v!=0 );
   83224   sqlite3BeginWriteOperation(pParse, 1, iDb);
   83225 
   83226 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83227   if( IsVirtual(pTab) ){
   83228     sqlite3VdbeAddOp0(v, OP_VBegin);
   83229   }
   83230 #endif
   83231 
   83232   /* Drop all triggers associated with the table being dropped. Code
   83233   ** is generated to remove entries from sqlite_master and/or
   83234   ** sqlite_temp_master if required.
   83235   */
   83236   pTrigger = sqlite3TriggerList(pParse, pTab);
   83237   while( pTrigger ){
   83238     assert( pTrigger->pSchema==pTab->pSchema ||
   83239         pTrigger->pSchema==db->aDb[1].pSchema );
   83240     sqlite3DropTriggerPtr(pParse, pTrigger);
   83241     pTrigger = pTrigger->pNext;
   83242   }
   83243 
   83244 #ifndef SQLITE_OMIT_AUTOINCREMENT
   83245   /* Remove any entries of the sqlite_sequence table associated with
   83246   ** the table being dropped. This is done before the table is dropped
   83247   ** at the btree level, in case the sqlite_sequence table needs to
   83248   ** move as a result of the drop (can happen in auto-vacuum mode).
   83249   */
   83250   if( pTab->tabFlags & TF_Autoincrement ){
   83251     sqlite3NestedParse(pParse,
   83252       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
   83253       pDb->zName, pTab->zName
   83254     );
   83255   }
   83256 #endif
   83257 
   83258   /* Drop all SQLITE_MASTER table and index entries that refer to the
   83259   ** table. The program name loops through the master table and deletes
   83260   ** every row that refers to a table of the same name as the one being
   83261   ** dropped. Triggers are handled seperately because a trigger can be
   83262   ** created in the temp database that refers to a table in another
   83263   ** database.
   83264   */
   83265   sqlite3NestedParse(pParse,
   83266       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   83267       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   83268   if( !isView && !IsVirtual(pTab) ){
   83269     destroyTable(pParse, pTab);
   83270   }
   83271 
   83272   /* Remove the table entry from SQLite's internal schema and modify
   83273   ** the schema cookie.
   83274   */
   83275   if( IsVirtual(pTab) ){
   83276     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   83277   }
   83278   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   83279   sqlite3ChangeCookie(pParse, iDb);
   83280   sqliteViewResetAll(db, iDb);
   83281 }
   83282 
   83283 /*
   83284 ** This routine is called to do the work of a DROP TABLE statement.
   83285 ** pName is the name of the table to be dropped.
   83286 */
   83287 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   83288   Table *pTab;
   83289   Vdbe *v;
   83290   sqlite3 *db = pParse->db;
   83291   int iDb;
   83292 
   83293   if( db->mallocFailed ){
   83294     goto exit_drop_table;
   83295   }
   83296   assert( pParse->nErr==0 );
   83297   assert( pName->nSrc==1 );
   83298   if( noErr ) db->suppressErr++;
   83299   pTab = sqlite3LocateTable(pParse, isView,
   83300                             pName->a[0].zName, pName->a[0].zDatabase);
   83301   if( noErr ) db->suppressErr--;
   83302 
   83303   if( pTab==0 ){
   83304     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   83305     goto exit_drop_table;
   83306   }
   83307   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83308   assert( iDb>=0 && iDb<db->nDb );
   83309 
   83310   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   83311   ** it is initialized.
   83312   */
   83313   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   83314     goto exit_drop_table;
   83315   }
   83316 #ifndef SQLITE_OMIT_AUTHORIZATION
   83317   {
   83318     int code;
   83319     const char *zTab = SCHEMA_TABLE(iDb);
   83320     const char *zDb = db->aDb[iDb].zName;
   83321     const char *zArg2 = 0;
   83322     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   83323       goto exit_drop_table;
   83324     }
   83325     if( isView ){
   83326       if( !OMIT_TEMPDB && iDb==1 ){
   83327         code = SQLITE_DROP_TEMP_VIEW;
   83328       }else{
   83329         code = SQLITE_DROP_VIEW;
   83330       }
   83331 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83332     }else if( IsVirtual(pTab) ){
   83333       code = SQLITE_DROP_VTABLE;
   83334       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   83335 #endif
   83336     }else{
   83337       if( !OMIT_TEMPDB && iDb==1 ){
   83338         code = SQLITE_DROP_TEMP_TABLE;
   83339       }else{
   83340         code = SQLITE_DROP_TABLE;
   83341       }
   83342     }
   83343     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   83344       goto exit_drop_table;
   83345     }
   83346     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   83347       goto exit_drop_table;
   83348     }
   83349   }
   83350 #endif
   83351   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   83352     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
   83353     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   83354     goto exit_drop_table;
   83355   }
   83356 
   83357 #ifndef SQLITE_OMIT_VIEW
   83358   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   83359   ** on a table.
   83360   */
   83361   if( isView && pTab->pSelect==0 ){
   83362     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   83363     goto exit_drop_table;
   83364   }
   83365   if( !isView && pTab->pSelect ){
   83366     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   83367     goto exit_drop_table;
   83368   }
   83369 #endif
   83370 
   83371   /* Generate code to remove the table from the master table
   83372   ** on disk.
   83373   */
   83374   v = sqlite3GetVdbe(pParse);
   83375   if( v ){
   83376     sqlite3BeginWriteOperation(pParse, 1, iDb);
   83377     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
   83378     sqlite3FkDropTable(pParse, pName, pTab);
   83379     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
   83380   }
   83381 
   83382 exit_drop_table:
   83383   sqlite3SrcListDelete(db, pName);
   83384 }
   83385 
   83386 /*
   83387 ** This routine is called to create a new foreign key on the table
   83388 ** currently under construction.  pFromCol determines which columns
   83389 ** in the current table point to the foreign key.  If pFromCol==0 then
   83390 ** connect the key to the last column inserted.  pTo is the name of
   83391 ** the table referred to.  pToCol is a list of tables in the other
   83392 ** pTo table that the foreign key points to.  flags contains all
   83393 ** information about the conflict resolution algorithms specified
   83394 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   83395 **
   83396 ** An FKey structure is created and added to the table currently
   83397 ** under construction in the pParse->pNewTable field.
   83398 **
   83399 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   83400 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   83401 */
   83402 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   83403   Parse *pParse,       /* Parsing context */
   83404   ExprList *pFromCol,  /* Columns in this table that point to other table */
   83405   Token *pTo,          /* Name of the other table */
   83406   ExprList *pToCol,    /* Columns in the other table */
   83407   int flags            /* Conflict resolution algorithms. */
   83408 ){
   83409   sqlite3 *db = pParse->db;
   83410 #ifndef SQLITE_OMIT_FOREIGN_KEY
   83411   FKey *pFKey = 0;
   83412   FKey *pNextTo;
   83413   Table *p = pParse->pNewTable;
   83414   int nByte;
   83415   int i;
   83416   int nCol;
   83417   char *z;
   83418 
   83419   assert( pTo!=0 );
   83420   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   83421   if( pFromCol==0 ){
   83422     int iCol = p->nCol-1;
   83423     if( NEVER(iCol<0) ) goto fk_end;
   83424     if( pToCol && pToCol->nExpr!=1 ){
   83425       sqlite3ErrorMsg(pParse, "foreign key on %s"
   83426          " should reference only one column of table %T",
   83427          p->aCol[iCol].zName, pTo);
   83428       goto fk_end;
   83429     }
   83430     nCol = 1;
   83431   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   83432     sqlite3ErrorMsg(pParse,
   83433         "number of columns in foreign key does not match the number of "
   83434         "columns in the referenced table");
   83435     goto fk_end;
   83436   }else{
   83437     nCol = pFromCol->nExpr;
   83438   }
   83439   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   83440   if( pToCol ){
   83441     for(i=0; i<pToCol->nExpr; i++){
   83442       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   83443     }
   83444   }
   83445   pFKey = sqlite3DbMallocZero(db, nByte );
   83446   if( pFKey==0 ){
   83447     goto fk_end;
   83448   }
   83449   pFKey->pFrom = p;
   83450   pFKey->pNextFrom = p->pFKey;
   83451   z = (char*)&pFKey->aCol[nCol];
   83452   pFKey->zTo = z;
   83453   memcpy(z, pTo->z, pTo->n);
   83454   z[pTo->n] = 0;
   83455   sqlite3Dequote(z);
   83456   z += pTo->n+1;
   83457   pFKey->nCol = nCol;
   83458   if( pFromCol==0 ){
   83459     pFKey->aCol[0].iFrom = p->nCol-1;
   83460   }else{
   83461     for(i=0; i<nCol; i++){
   83462       int j;
   83463       for(j=0; j<p->nCol; j++){
   83464         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   83465           pFKey->aCol[i].iFrom = j;
   83466           break;
   83467         }
   83468       }
   83469       if( j>=p->nCol ){
   83470         sqlite3ErrorMsg(pParse,
   83471           "unknown column \"%s\" in foreign key definition",
   83472           pFromCol->a[i].zName);
   83473         goto fk_end;
   83474       }
   83475     }
   83476   }
   83477   if( pToCol ){
   83478     for(i=0; i<nCol; i++){
   83479       int n = sqlite3Strlen30(pToCol->a[i].zName);
   83480       pFKey->aCol[i].zCol = z;
   83481       memcpy(z, pToCol->a[i].zName, n);
   83482       z[n] = 0;
   83483       z += n+1;
   83484     }
   83485   }
   83486   pFKey->isDeferred = 0;
   83487   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   83488   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   83489 
   83490   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   83491   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   83492       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   83493   );
   83494   if( pNextTo==pFKey ){
   83495     db->mallocFailed = 1;
   83496     goto fk_end;
   83497   }
   83498   if( pNextTo ){
   83499     assert( pNextTo->pPrevTo==0 );
   83500     pFKey->pNextTo = pNextTo;
   83501     pNextTo->pPrevTo = pFKey;
   83502   }
   83503 
   83504   /* Link the foreign key to the table as the last step.
   83505   */
   83506   p->pFKey = pFKey;
   83507   pFKey = 0;
   83508 
   83509 fk_end:
   83510   sqlite3DbFree(db, pFKey);
   83511 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   83512   sqlite3ExprListDelete(db, pFromCol);
   83513   sqlite3ExprListDelete(db, pToCol);
   83514 }
   83515 
   83516 /*
   83517 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   83518 ** clause is seen as part of a foreign key definition.  The isDeferred
   83519 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   83520 ** The behavior of the most recently created foreign key is adjusted
   83521 ** accordingly.
   83522 */
   83523 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   83524 #ifndef SQLITE_OMIT_FOREIGN_KEY
   83525   Table *pTab;
   83526   FKey *pFKey;
   83527   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   83528   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   83529   pFKey->isDeferred = (u8)isDeferred;
   83530 #endif
   83531 }
   83532 
   83533 /*
   83534 ** Generate code that will erase and refill index *pIdx.  This is
   83535 ** used to initialize a newly created index or to recompute the
   83536 ** content of an index in response to a REINDEX command.
   83537 **
   83538 ** if memRootPage is not negative, it means that the index is newly
   83539 ** created.  The register specified by memRootPage contains the
   83540 ** root page number of the index.  If memRootPage is negative, then
   83541 ** the index already exists and must be cleared before being refilled and
   83542 ** the root page number of the index is taken from pIndex->tnum.
   83543 */
   83544 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   83545   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   83546   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   83547   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   83548   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   83549   int addr1;                     /* Address of top of loop */
   83550   int addr2;                     /* Address to jump to for next iteration */
   83551   int tnum;                      /* Root page of index */
   83552   Vdbe *v;                       /* Generate code into this virtual machine */
   83553   KeyInfo *pKey;                 /* KeyInfo for index */
   83554 #ifdef SQLITE_OMIT_MERGE_SORT
   83555   int regIdxKey;                 /* Registers containing the index key */
   83556 #endif
   83557   int regRecord;                 /* Register holding assemblied index record */
   83558   sqlite3 *db = pParse->db;      /* The database connection */
   83559   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   83560 
   83561 #ifndef SQLITE_OMIT_AUTHORIZATION
   83562   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   83563       db->aDb[iDb].zName ) ){
   83564     return;
   83565   }
   83566 #endif
   83567 
   83568   /* Require a write-lock on the table to perform this operation */
   83569   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   83570 
   83571   v = sqlite3GetVdbe(pParse);
   83572   if( v==0 ) return;
   83573   if( memRootPage>=0 ){
   83574     tnum = memRootPage;
   83575   }else{
   83576     tnum = pIndex->tnum;
   83577     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   83578   }
   83579   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
   83580   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   83581                     (char *)pKey, P4_KEYINFO_HANDOFF);
   83582   if( memRootPage>=0 ){
   83583     sqlite3VdbeChangeP5(v, 1);
   83584   }
   83585 
   83586 #ifndef SQLITE_OMIT_MERGE_SORT
   83587   /* Open the sorter cursor if we are to use one. */
   83588   iSorter = pParse->nTab++;
   83589   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
   83590 #else
   83591   iSorter = iTab;
   83592 #endif
   83593 
   83594   /* Open the table. Loop through all rows of the table, inserting index
   83595   ** records into the sorter. */
   83596   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   83597   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   83598   regRecord = sqlite3GetTempReg(pParse);
   83599 
   83600 #ifndef SQLITE_OMIT_MERGE_SORT
   83601   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   83602   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
   83603   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
   83604   sqlite3VdbeJumpHere(v, addr1);
   83605   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
   83606   if( pIndex->onError!=OE_None ){
   83607     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
   83608     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
   83609     addr2 = sqlite3VdbeCurrentAddr(v);
   83610     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
   83611     sqlite3HaltConstraint(
   83612         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
   83613     );
   83614   }else{
   83615     addr2 = sqlite3VdbeCurrentAddr(v);
   83616   }
   83617   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
   83618   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
   83619   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   83620 #else
   83621   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   83622   addr2 = addr1 + 1;
   83623   if( pIndex->onError!=OE_None ){
   83624     const int regRowid = regIdxKey + pIndex->nColumn;
   83625     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
   83626     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
   83627 
   83628     /* The registers accessed by the OP_IsUnique opcode were allocated
   83629     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
   83630     ** call above. Just before that function was freed they were released
   83631     ** (made available to the compiler for reuse) using
   83632     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
   83633     ** opcode use the values stored within seems dangerous. However, since
   83634     ** we can be sure that no other temp registers have been allocated
   83635     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
   83636     */
   83637     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
   83638     sqlite3HaltConstraint(
   83639         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
   83640   }
   83641   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
   83642   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   83643 #endif
   83644   sqlite3ReleaseTempReg(pParse, regRecord);
   83645   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
   83646   sqlite3VdbeJumpHere(v, addr1);
   83647 
   83648   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   83649   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   83650   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
   83651 }
   83652 
   83653 /*
   83654 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   83655 ** and pTblList is the name of the table that is to be indexed.  Both will
   83656 ** be NULL for a primary key or an index that is created to satisfy a
   83657 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   83658 ** as the table to be indexed.  pParse->pNewTable is a table that is
   83659 ** currently being constructed by a CREATE TABLE statement.
   83660 **
   83661 ** pList is a list of columns to be indexed.  pList will be NULL if this
   83662 ** is a primary key or unique-constraint on the most recent column added
   83663 ** to the table currently under construction.
   83664 **
   83665 ** If the index is created successfully, return a pointer to the new Index
   83666 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   83667 ** as the tables primary key (Index.autoIndex==2).
   83668 */
   83669 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   83670   Parse *pParse,     /* All information about this parse */
   83671   Token *pName1,     /* First part of index name. May be NULL */
   83672   Token *pName2,     /* Second part of index name. May be NULL */
   83673   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   83674   ExprList *pList,   /* A list of columns to be indexed */
   83675   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   83676   Token *pStart,     /* The CREATE token that begins this statement */
   83677   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
   83678   int sortOrder,     /* Sort order of primary key when pList==NULL */
   83679   int ifNotExist     /* Omit error if index already exists */
   83680 ){
   83681   Index *pRet = 0;     /* Pointer to return */
   83682   Table *pTab = 0;     /* Table to be indexed */
   83683   Index *pIndex = 0;   /* The index to be created */
   83684   char *zName = 0;     /* Name of the index */
   83685   int nName;           /* Number of characters in zName */
   83686   int i, j;
   83687   Token nullId;        /* Fake token for an empty ID list */
   83688   DbFixer sFix;        /* For assigning database names to pTable */
   83689   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   83690   sqlite3 *db = pParse->db;
   83691   Db *pDb;             /* The specific table containing the indexed database */
   83692   int iDb;             /* Index of the database that is being written */
   83693   Token *pName = 0;    /* Unqualified name of the index to create */
   83694   struct ExprList_item *pListItem; /* For looping over pList */
   83695   int nCol;
   83696   int nExtra = 0;
   83697   char *zExtra;
   83698 
   83699   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
   83700   assert( pParse->nErr==0 );      /* Never called with prior errors */
   83701   if( db->mallocFailed || IN_DECLARE_VTAB ){
   83702     goto exit_create_index;
   83703   }
   83704   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   83705     goto exit_create_index;
   83706   }
   83707 
   83708   /*
   83709   ** Find the table that is to be indexed.  Return early if not found.
   83710   */
   83711   if( pTblName!=0 ){
   83712 
   83713     /* Use the two-part index name to determine the database
   83714     ** to search for the table. 'Fix' the table name to this db
   83715     ** before looking up the table.
   83716     */
   83717     assert( pName1 && pName2 );
   83718     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   83719     if( iDb<0 ) goto exit_create_index;
   83720     assert( pName && pName->z );
   83721 
   83722 #ifndef SQLITE_OMIT_TEMPDB
   83723     /* If the index name was unqualified, check if the the table
   83724     ** is a temp table. If so, set the database to 1. Do not do this
   83725     ** if initialising a database schema.
   83726     */
   83727     if( !db->init.busy ){
   83728       pTab = sqlite3SrcListLookup(pParse, pTblName);
   83729       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   83730         iDb = 1;
   83731       }
   83732     }
   83733 #endif
   83734 
   83735     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
   83736         sqlite3FixSrcList(&sFix, pTblName)
   83737     ){
   83738       /* Because the parser constructs pTblName from a single identifier,
   83739       ** sqlite3FixSrcList can never fail. */
   83740       assert(0);
   83741     }
   83742     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
   83743         pTblName->a[0].zDatabase);
   83744     if( !pTab || db->mallocFailed ) goto exit_create_index;
   83745     assert( db->aDb[iDb].pSchema==pTab->pSchema );
   83746   }else{
   83747     assert( pName==0 );
   83748     assert( pStart==0 );
   83749     pTab = pParse->pNewTable;
   83750     if( !pTab ) goto exit_create_index;
   83751     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   83752   }
   83753   pDb = &db->aDb[iDb];
   83754 
   83755   assert( pTab!=0 );
   83756   assert( pParse->nErr==0 );
   83757   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   83758        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
   83759     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   83760     goto exit_create_index;
   83761   }
   83762 #ifndef SQLITE_OMIT_VIEW
   83763   if( pTab->pSelect ){
   83764     sqlite3ErrorMsg(pParse, "views may not be indexed");
   83765     goto exit_create_index;
   83766   }
   83767 #endif
   83768 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83769   if( IsVirtual(pTab) ){
   83770     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   83771     goto exit_create_index;
   83772   }
   83773 #endif
   83774 
   83775   /*
   83776   ** Find the name of the index.  Make sure there is not already another
   83777   ** index or table with the same name.
   83778   **
   83779   ** Exception:  If we are reading the names of permanent indices from the
   83780   ** sqlite_master table (because some other process changed the schema) and
   83781   ** one of the index names collides with the name of a temporary table or
   83782   ** index, then we will continue to process this index.
   83783   **
   83784   ** If pName==0 it means that we are
   83785   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   83786   ** own name.
   83787   */
   83788   if( pName ){
   83789     zName = sqlite3NameFromToken(db, pName);
   83790     if( zName==0 ) goto exit_create_index;
   83791     assert( pName->z!=0 );
   83792     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   83793       goto exit_create_index;
   83794     }
   83795     if( !db->init.busy ){
   83796       if( sqlite3FindTable(db, zName, 0)!=0 ){
   83797         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   83798         goto exit_create_index;
   83799       }
   83800     }
   83801     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   83802       if( !ifNotExist ){
   83803         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   83804       }else{
   83805         assert( !db->init.busy );
   83806         sqlite3CodeVerifySchema(pParse, iDb);
   83807       }
   83808       goto exit_create_index;
   83809     }
   83810   }else{
   83811     int n;
   83812     Index *pLoop;
   83813     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   83814     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   83815     if( zName==0 ){
   83816       goto exit_create_index;
   83817     }
   83818   }
   83819 
   83820   /* Check for authorization to create an index.
   83821   */
   83822 #ifndef SQLITE_OMIT_AUTHORIZATION
   83823   {
   83824     const char *zDb = pDb->zName;
   83825     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   83826       goto exit_create_index;
   83827     }
   83828     i = SQLITE_CREATE_INDEX;
   83829     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   83830     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   83831       goto exit_create_index;
   83832     }
   83833   }
   83834 #endif
   83835 
   83836   /* If pList==0, it means this routine was called to make a primary
   83837   ** key out of the last column added to the table under construction.
   83838   ** So create a fake list to simulate this.
   83839   */
   83840   if( pList==0 ){
   83841     nullId.z = pTab->aCol[pTab->nCol-1].zName;
   83842     nullId.n = sqlite3Strlen30((char*)nullId.z);
   83843     pList = sqlite3ExprListAppend(pParse, 0, 0);
   83844     if( pList==0 ) goto exit_create_index;
   83845     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
   83846     pList->a[0].sortOrder = (u8)sortOrder;
   83847   }
   83848 
   83849   /* Figure out how many bytes of space are required to store explicitly
   83850   ** specified collation sequence names.
   83851   */
   83852   for(i=0; i<pList->nExpr; i++){
   83853     Expr *pExpr = pList->a[i].pExpr;
   83854     if( pExpr ){
   83855       CollSeq *pColl = pExpr->pColl;
   83856       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
   83857       ** failure we have quit before reaching this point. */
   83858       if( ALWAYS(pColl) ){
   83859         nExtra += (1 + sqlite3Strlen30(pColl->zName));
   83860       }
   83861     }
   83862   }
   83863 
   83864   /*
   83865   ** Allocate the index structure.
   83866   */
   83867   nName = sqlite3Strlen30(zName);
   83868   nCol = pList->nExpr;
   83869   pIndex = sqlite3DbMallocZero(db,
   83870       ROUND8(sizeof(Index)) +              /* Index structure  */
   83871       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
   83872       sizeof(char *)*nCol +                /* Index.azColl     */
   83873       sizeof(int)*nCol +                   /* Index.aiColumn   */
   83874       sizeof(u8)*nCol +                    /* Index.aSortOrder */
   83875       nName + 1 +                          /* Index.zName      */
   83876       nExtra                               /* Collation sequence names */
   83877   );
   83878   if( db->mallocFailed ){
   83879     goto exit_create_index;
   83880   }
   83881   zExtra = (char*)pIndex;
   83882   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
   83883   pIndex->azColl = (char**)
   83884      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
   83885   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
   83886   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
   83887   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
   83888   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
   83889   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
   83890   zExtra = (char *)(&pIndex->zName[nName+1]);
   83891   memcpy(pIndex->zName, zName, nName+1);
   83892   pIndex->pTable = pTab;
   83893   pIndex->nColumn = pList->nExpr;
   83894   pIndex->onError = (u8)onError;
   83895   pIndex->autoIndex = (u8)(pName==0);
   83896   pIndex->pSchema = db->aDb[iDb].pSchema;
   83897   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   83898 
   83899   /* Check to see if we should honor DESC requests on index columns
   83900   */
   83901   if( pDb->pSchema->file_format>=4 ){
   83902     sortOrderMask = -1;   /* Honor DESC */
   83903   }else{
   83904     sortOrderMask = 0;    /* Ignore DESC */
   83905   }
   83906 
   83907   /* Scan the names of the columns of the table to be indexed and
   83908   ** load the column indices into the Index structure.  Report an error
   83909   ** if any column is not found.
   83910   **
   83911   ** TODO:  Add a test to make sure that the same column is not named
   83912   ** more than once within the same index.  Only the first instance of
   83913   ** the column will ever be used by the optimizer.  Note that using the
   83914   ** same column more than once cannot be an error because that would
   83915   ** break backwards compatibility - it needs to be a warning.
   83916   */
   83917   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   83918     const char *zColName = pListItem->zName;
   83919     Column *pTabCol;
   83920     int requestedSortOrder;
   83921     char *zColl;                   /* Collation sequence name */
   83922 
   83923     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   83924       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   83925     }
   83926     if( j>=pTab->nCol ){
   83927       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   83928         pTab->zName, zColName);
   83929       pParse->checkSchema = 1;
   83930       goto exit_create_index;
   83931     }
   83932     pIndex->aiColumn[i] = j;
   83933     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
   83934     ** the way the "idxlist" non-terminal is constructed by the parser,
   83935     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
   83936     ** must exist or else there must have been an OOM error.  But if there
   83937     ** was an OOM error, we would never reach this point. */
   83938     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
   83939       int nColl;
   83940       zColl = pListItem->pExpr->pColl->zName;
   83941       nColl = sqlite3Strlen30(zColl) + 1;
   83942       assert( nExtra>=nColl );
   83943       memcpy(zExtra, zColl, nColl);
   83944       zColl = zExtra;
   83945       zExtra += nColl;
   83946       nExtra -= nColl;
   83947     }else{
   83948       zColl = pTab->aCol[j].zColl;
   83949       if( !zColl ){
   83950         zColl = db->pDfltColl->zName;
   83951       }
   83952     }
   83953     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   83954       goto exit_create_index;
   83955     }
   83956     pIndex->azColl[i] = zColl;
   83957     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   83958     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   83959   }
   83960   sqlite3DefaultRowEst(pIndex);
   83961 
   83962   if( pTab==pParse->pNewTable ){
   83963     /* This routine has been called to create an automatic index as a
   83964     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   83965     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   83966     ** i.e. one of:
   83967     **
   83968     ** CREATE TABLE t(x PRIMARY KEY, y);
   83969     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   83970     **
   83971     ** Either way, check to see if the table already has such an index. If
   83972     ** so, don't bother creating this one. This only applies to
   83973     ** automatically created indices. Users can do as they wish with
   83974     ** explicit indices.
   83975     **
   83976     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   83977     ** (and thus suppressing the second one) even if they have different
   83978     ** sort orders.
   83979     **
   83980     ** If there are different collating sequences or if the columns of
   83981     ** the constraint occur in different orders, then the constraints are
   83982     ** considered distinct and both result in separate indices.
   83983     */
   83984     Index *pIdx;
   83985     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   83986       int k;
   83987       assert( pIdx->onError!=OE_None );
   83988       assert( pIdx->autoIndex );
   83989       assert( pIndex->onError!=OE_None );
   83990 
   83991       if( pIdx->nColumn!=pIndex->nColumn ) continue;
   83992       for(k=0; k<pIdx->nColumn; k++){
   83993         const char *z1;
   83994         const char *z2;
   83995         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   83996         z1 = pIdx->azColl[k];
   83997         z2 = pIndex->azColl[k];
   83998         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   83999       }
   84000       if( k==pIdx->nColumn ){
   84001         if( pIdx->onError!=pIndex->onError ){
   84002           /* This constraint creates the same index as a previous
   84003           ** constraint specified somewhere in the CREATE TABLE statement.
   84004           ** However the ON CONFLICT clauses are different. If both this
   84005           ** constraint and the previous equivalent constraint have explicit
   84006           ** ON CONFLICT clauses this is an error. Otherwise, use the
   84007           ** explicitly specified behaviour for the index.
   84008           */
   84009           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   84010             sqlite3ErrorMsg(pParse,
   84011                 "conflicting ON CONFLICT clauses specified", 0);
   84012           }
   84013           if( pIdx->onError==OE_Default ){
   84014             pIdx->onError = pIndex->onError;
   84015           }
   84016         }
   84017         goto exit_create_index;
   84018       }
   84019     }
   84020   }
   84021 
   84022   /* Link the new Index structure to its table and to the other
   84023   ** in-memory database structures.
   84024   */
   84025   if( db->init.busy ){
   84026     Index *p;
   84027     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
   84028     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   84029                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   84030                           pIndex);
   84031     if( p ){
   84032       assert( p==pIndex );  /* Malloc must have failed */
   84033       db->mallocFailed = 1;
   84034       goto exit_create_index;
   84035     }
   84036     db->flags |= SQLITE_InternChanges;
   84037     if( pTblName!=0 ){
   84038       pIndex->tnum = db->init.newTnum;
   84039     }
   84040   }
   84041 
   84042   /* If the db->init.busy is 0 then create the index on disk.  This
   84043   ** involves writing the index into the master table and filling in the
   84044   ** index with the current table contents.
   84045   **
   84046   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
   84047   ** command.  db->init.busy is 1 when a database is opened and
   84048   ** CREATE INDEX statements are read out of the master table.  In
   84049   ** the latter case the index already exists on disk, which is why
   84050   ** we don't want to recreate it.
   84051   **
   84052   ** If pTblName==0 it means this index is generated as a primary key
   84053   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
   84054   ** has just been created, it contains no data and the index initialization
   84055   ** step can be skipped.
   84056   */
   84057   else{ /* if( db->init.busy==0 ) */
   84058     Vdbe *v;
   84059     char *zStmt;
   84060     int iMem = ++pParse->nMem;
   84061 
   84062     v = sqlite3GetVdbe(pParse);
   84063     if( v==0 ) goto exit_create_index;
   84064 
   84065 
   84066     /* Create the rootpage for the index
   84067     */
   84068     sqlite3BeginWriteOperation(pParse, 1, iDb);
   84069     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   84070 
   84071     /* Gather the complete text of the CREATE INDEX statement into
   84072     ** the zStmt variable
   84073     */
   84074     if( pStart ){
   84075       assert( pEnd!=0 );
   84076       /* A named index with an explicit CREATE INDEX statement */
   84077       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   84078         onError==OE_None ? "" : " UNIQUE",
   84079         (int)(pEnd->z - pName->z) + 1,
   84080         pName->z);
   84081     }else{
   84082       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   84083       /* zStmt = sqlite3MPrintf(""); */
   84084       zStmt = 0;
   84085     }
   84086 
   84087     /* Add an entry in sqlite_master for this index
   84088     */
   84089     sqlite3NestedParse(pParse,
   84090         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   84091         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   84092         pIndex->zName,
   84093         pTab->zName,
   84094         iMem,
   84095         zStmt
   84096     );
   84097     sqlite3DbFree(db, zStmt);
   84098 
   84099     /* Fill the index with data and reparse the schema. Code an OP_Expire
   84100     ** to invalidate all pre-compiled statements.
   84101     */
   84102     if( pTblName ){
   84103       sqlite3RefillIndex(pParse, pIndex, iMem);
   84104       sqlite3ChangeCookie(pParse, iDb);
   84105       sqlite3VdbeAddParseSchemaOp(v, iDb,
   84106          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
   84107       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   84108     }
   84109   }
   84110 
   84111   /* When adding an index to the list of indices for a table, make
   84112   ** sure all indices labeled OE_Replace come after all those labeled
   84113   ** OE_Ignore.  This is necessary for the correct constraint check
   84114   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   84115   ** UPDATE and INSERT statements.
   84116   */
   84117   if( db->init.busy || pTblName==0 ){
   84118     if( onError!=OE_Replace || pTab->pIndex==0
   84119          || pTab->pIndex->onError==OE_Replace){
   84120       pIndex->pNext = pTab->pIndex;
   84121       pTab->pIndex = pIndex;
   84122     }else{
   84123       Index *pOther = pTab->pIndex;
   84124       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   84125         pOther = pOther->pNext;
   84126       }
   84127       pIndex->pNext = pOther->pNext;
   84128       pOther->pNext = pIndex;
   84129     }
   84130     pRet = pIndex;
   84131     pIndex = 0;
   84132   }
   84133 
   84134   /* Clean up before exiting */
   84135 exit_create_index:
   84136   if( pIndex ){
   84137     sqlite3DbFree(db, pIndex->zColAff);
   84138     sqlite3DbFree(db, pIndex);
   84139   }
   84140   sqlite3ExprListDelete(db, pList);
   84141   sqlite3SrcListDelete(db, pTblName);
   84142   sqlite3DbFree(db, zName);
   84143   return pRet;
   84144 }
   84145 
   84146 /*
   84147 ** Fill the Index.aiRowEst[] array with default information - information
   84148 ** to be used when we have not run the ANALYZE command.
   84149 **
   84150 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   84151 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   84152 ** number of rows in the table that match any particular value of the
   84153 ** first column of the index.  aiRowEst[2] is an estimate of the number
   84154 ** of rows that match any particular combiniation of the first 2 columns
   84155 ** of the index.  And so forth.  It must always be the case that
   84156 *
   84157 **           aiRowEst[N]<=aiRowEst[N-1]
   84158 **           aiRowEst[N]>=1
   84159 **
   84160 ** Apart from that, we have little to go on besides intuition as to
   84161 ** how aiRowEst[] should be initialized.  The numbers generated here
   84162 ** are based on typical values found in actual indices.
   84163 */
   84164 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   84165   tRowcnt *a = pIdx->aiRowEst;
   84166   int i;
   84167   tRowcnt n;
   84168   assert( a!=0 );
   84169   a[0] = pIdx->pTable->nRowEst;
   84170   if( a[0]<10 ) a[0] = 10;
   84171   n = 10;
   84172   for(i=1; i<=pIdx->nColumn; i++){
   84173     a[i] = n;
   84174     if( n>5 ) n--;
   84175   }
   84176   if( pIdx->onError!=OE_None ){
   84177     a[pIdx->nColumn] = 1;
   84178   }
   84179 }
   84180 
   84181 /*
   84182 ** This routine will drop an existing named index.  This routine
   84183 ** implements the DROP INDEX statement.
   84184 */
   84185 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   84186   Index *pIndex;
   84187   Vdbe *v;
   84188   sqlite3 *db = pParse->db;
   84189   int iDb;
   84190 
   84191   assert( pParse->nErr==0 );   /* Never called with prior errors */
   84192   if( db->mallocFailed ){
   84193     goto exit_drop_index;
   84194   }
   84195   assert( pName->nSrc==1 );
   84196   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84197     goto exit_drop_index;
   84198   }
   84199   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   84200   if( pIndex==0 ){
   84201     if( !ifExists ){
   84202       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   84203     }else{
   84204       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
   84205     }
   84206     pParse->checkSchema = 1;
   84207     goto exit_drop_index;
   84208   }
   84209   if( pIndex->autoIndex ){
   84210     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   84211       "or PRIMARY KEY constraint cannot be dropped", 0);
   84212     goto exit_drop_index;
   84213   }
   84214   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   84215 #ifndef SQLITE_OMIT_AUTHORIZATION
   84216   {
   84217     int code = SQLITE_DROP_INDEX;
   84218     Table *pTab = pIndex->pTable;
   84219     const char *zDb = db->aDb[iDb].zName;
   84220     const char *zTab = SCHEMA_TABLE(iDb);
   84221     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   84222       goto exit_drop_index;
   84223     }
   84224     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   84225     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   84226       goto exit_drop_index;
   84227     }
   84228   }
   84229 #endif
   84230 
   84231   /* Generate code to remove the index and from the master table */
   84232   v = sqlite3GetVdbe(pParse);
   84233   if( v ){
   84234     sqlite3BeginWriteOperation(pParse, 1, iDb);
   84235     sqlite3NestedParse(pParse,
   84236        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   84237        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
   84238     );
   84239     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
   84240     sqlite3ChangeCookie(pParse, iDb);
   84241     destroyRootPage(pParse, pIndex->tnum, iDb);
   84242     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   84243   }
   84244 
   84245 exit_drop_index:
   84246   sqlite3SrcListDelete(db, pName);
   84247 }
   84248 
   84249 /*
   84250 ** pArray is a pointer to an array of objects.  Each object in the
   84251 ** array is szEntry bytes in size.  This routine allocates a new
   84252 ** object on the end of the array.
   84253 **
   84254 ** *pnEntry is the number of entries already in use.  *pnAlloc is
   84255 ** the previously allocated size of the array.  initSize is the
   84256 ** suggested initial array size allocation.
   84257 **
   84258 ** The index of the new entry is returned in *pIdx.
   84259 **
   84260 ** This routine returns a pointer to the array of objects.  This
   84261 ** might be the same as the pArray parameter or it might be a different
   84262 ** pointer if the array was resized.
   84263 */
   84264 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   84265   sqlite3 *db,      /* Connection to notify of malloc failures */
   84266   void *pArray,     /* Array of objects.  Might be reallocated */
   84267   int szEntry,      /* Size of each object in the array */
   84268   int *pnEntry,     /* Number of objects currently in use */
   84269   int *pIdx         /* Write the index of a new slot here */
   84270 ){
   84271   char *z;
   84272   int n = *pnEntry;
   84273   if( (n & (n-1))==0 ){
   84274     int sz = (n==0) ? 1 : 2*n;
   84275     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
   84276     if( pNew==0 ){
   84277       *pIdx = -1;
   84278       return pArray;
   84279     }
   84280     pArray = pNew;
   84281   }
   84282   z = (char*)pArray;
   84283   memset(&z[n * szEntry], 0, szEntry);
   84284   *pIdx = n;
   84285   ++*pnEntry;
   84286   return pArray;
   84287 }
   84288 
   84289 /*
   84290 ** Append a new element to the given IdList.  Create a new IdList if
   84291 ** need be.
   84292 **
   84293 ** A new IdList is returned, or NULL if malloc() fails.
   84294 */
   84295 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   84296   int i;
   84297   if( pList==0 ){
   84298     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   84299     if( pList==0 ) return 0;
   84300   }
   84301   pList->a = sqlite3ArrayAllocate(
   84302       db,
   84303       pList->a,
   84304       sizeof(pList->a[0]),
   84305       &pList->nId,
   84306       &i
   84307   );
   84308   if( i<0 ){
   84309     sqlite3IdListDelete(db, pList);
   84310     return 0;
   84311   }
   84312   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   84313   return pList;
   84314 }
   84315 
   84316 /*
   84317 ** Delete an IdList.
   84318 */
   84319 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   84320   int i;
   84321   if( pList==0 ) return;
   84322   for(i=0; i<pList->nId; i++){
   84323     sqlite3DbFree(db, pList->a[i].zName);
   84324   }
   84325   sqlite3DbFree(db, pList->a);
   84326   sqlite3DbFree(db, pList);
   84327 }
   84328 
   84329 /*
   84330 ** Return the index in pList of the identifier named zId.  Return -1
   84331 ** if not found.
   84332 */
   84333 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   84334   int i;
   84335   if( pList==0 ) return -1;
   84336   for(i=0; i<pList->nId; i++){
   84337     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   84338   }
   84339   return -1;
   84340 }
   84341 
   84342 /*
   84343 ** Expand the space allocated for the given SrcList object by
   84344 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   84345 ** New slots are zeroed.
   84346 **
   84347 ** For example, suppose a SrcList initially contains two entries: A,B.
   84348 ** To append 3 new entries onto the end, do this:
   84349 **
   84350 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   84351 **
   84352 ** After the call above it would contain:  A, B, nil, nil, nil.
   84353 ** If the iStart argument had been 1 instead of 2, then the result
   84354 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   84355 ** the iStart value would be 0.  The result then would
   84356 ** be: nil, nil, nil, A, B.
   84357 **
   84358 ** If a memory allocation fails the SrcList is unchanged.  The
   84359 ** db->mallocFailed flag will be set to true.
   84360 */
   84361 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   84362   sqlite3 *db,       /* Database connection to notify of OOM errors */
   84363   SrcList *pSrc,     /* The SrcList to be enlarged */
   84364   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   84365   int iStart         /* Index in pSrc->a[] of first new slot */
   84366 ){
   84367   int i;
   84368 
   84369   /* Sanity checking on calling parameters */
   84370   assert( iStart>=0 );
   84371   assert( nExtra>=1 );
   84372   assert( pSrc!=0 );
   84373   assert( iStart<=pSrc->nSrc );
   84374 
   84375   /* Allocate additional space if needed */
   84376   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
   84377     SrcList *pNew;
   84378     int nAlloc = pSrc->nSrc+nExtra;
   84379     int nGot;
   84380     pNew = sqlite3DbRealloc(db, pSrc,
   84381                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   84382     if( pNew==0 ){
   84383       assert( db->mallocFailed );
   84384       return pSrc;
   84385     }
   84386     pSrc = pNew;
   84387     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   84388     pSrc->nAlloc = (u16)nGot;
   84389   }
   84390 
   84391   /* Move existing slots that come after the newly inserted slots
   84392   ** out of the way */
   84393   for(i=pSrc->nSrc-1; i>=iStart; i--){
   84394     pSrc->a[i+nExtra] = pSrc->a[i];
   84395   }
   84396   pSrc->nSrc += (i16)nExtra;
   84397 
   84398   /* Zero the newly allocated slots */
   84399   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   84400   for(i=iStart; i<iStart+nExtra; i++){
   84401     pSrc->a[i].iCursor = -1;
   84402   }
   84403 
   84404   /* Return a pointer to the enlarged SrcList */
   84405   return pSrc;
   84406 }
   84407 
   84408 
   84409 /*
   84410 ** Append a new table name to the given SrcList.  Create a new SrcList if
   84411 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   84412 **
   84413 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   84414 ** SrcList might be the same as the SrcList that was input or it might be
   84415 ** a new one.  If an OOM error does occurs, then the prior value of pList
   84416 ** that is input to this routine is automatically freed.
   84417 **
   84418 ** If pDatabase is not null, it means that the table has an optional
   84419 ** database name prefix.  Like this:  "database.table".  The pDatabase
   84420 ** points to the table name and the pTable points to the database name.
   84421 ** The SrcList.a[].zName field is filled with the table name which might
   84422 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   84423 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   84424 ** or with NULL if no database is specified.
   84425 **
   84426 ** In other words, if call like this:
   84427 **
   84428 **         sqlite3SrcListAppend(D,A,B,0);
   84429 **
   84430 ** Then B is a table name and the database name is unspecified.  If called
   84431 ** like this:
   84432 **
   84433 **         sqlite3SrcListAppend(D,A,B,C);
   84434 **
   84435 ** Then C is the table name and B is the database name.  If C is defined
   84436 ** then so is B.  In other words, we never have a case where:
   84437 **
   84438 **         sqlite3SrcListAppend(D,A,0,C);
   84439 **
   84440 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   84441 ** before being added to the SrcList.
   84442 */
   84443 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   84444   sqlite3 *db,        /* Connection to notify of malloc failures */
   84445   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   84446   Token *pTable,      /* Table to append */
   84447   Token *pDatabase    /* Database of the table */
   84448 ){
   84449   struct SrcList_item *pItem;
   84450   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   84451   if( pList==0 ){
   84452     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   84453     if( pList==0 ) return 0;
   84454     pList->nAlloc = 1;
   84455   }
   84456   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   84457   if( db->mallocFailed ){
   84458     sqlite3SrcListDelete(db, pList);
   84459     return 0;
   84460   }
   84461   pItem = &pList->a[pList->nSrc-1];
   84462   if( pDatabase && pDatabase->z==0 ){
   84463     pDatabase = 0;
   84464   }
   84465   if( pDatabase ){
   84466     Token *pTemp = pDatabase;
   84467     pDatabase = pTable;
   84468     pTable = pTemp;
   84469   }
   84470   pItem->zName = sqlite3NameFromToken(db, pTable);
   84471   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   84472   return pList;
   84473 }
   84474 
   84475 /*
   84476 ** Assign VdbeCursor index numbers to all tables in a SrcList
   84477 */
   84478 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   84479   int i;
   84480   struct SrcList_item *pItem;
   84481   assert(pList || pParse->db->mallocFailed );
   84482   if( pList ){
   84483     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   84484       if( pItem->iCursor>=0 ) break;
   84485       pItem->iCursor = pParse->nTab++;
   84486       if( pItem->pSelect ){
   84487         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   84488       }
   84489     }
   84490   }
   84491 }
   84492 
   84493 /*
   84494 ** Delete an entire SrcList including all its substructure.
   84495 */
   84496 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   84497   int i;
   84498   struct SrcList_item *pItem;
   84499   if( pList==0 ) return;
   84500   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   84501     sqlite3DbFree(db, pItem->zDatabase);
   84502     sqlite3DbFree(db, pItem->zName);
   84503     sqlite3DbFree(db, pItem->zAlias);
   84504     sqlite3DbFree(db, pItem->zIndex);
   84505     sqlite3DeleteTable(db, pItem->pTab);
   84506     sqlite3SelectDelete(db, pItem->pSelect);
   84507     sqlite3ExprDelete(db, pItem->pOn);
   84508     sqlite3IdListDelete(db, pItem->pUsing);
   84509   }
   84510   sqlite3DbFree(db, pList);
   84511 }
   84512 
   84513 /*
   84514 ** This routine is called by the parser to add a new term to the
   84515 ** end of a growing FROM clause.  The "p" parameter is the part of
   84516 ** the FROM clause that has already been constructed.  "p" is NULL
   84517 ** if this is the first term of the FROM clause.  pTable and pDatabase
   84518 ** are the name of the table and database named in the FROM clause term.
   84519 ** pDatabase is NULL if the database name qualifier is missing - the
   84520 ** usual case.  If the term has a alias, then pAlias points to the
   84521 ** alias token.  If the term is a subquery, then pSubquery is the
   84522 ** SELECT statement that the subquery encodes.  The pTable and
   84523 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   84524 ** parameters are the content of the ON and USING clauses.
   84525 **
   84526 ** Return a new SrcList which encodes is the FROM with the new
   84527 ** term added.
   84528 */
   84529 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   84530   Parse *pParse,          /* Parsing context */
   84531   SrcList *p,             /* The left part of the FROM clause already seen */
   84532   Token *pTable,          /* Name of the table to add to the FROM clause */
   84533   Token *pDatabase,       /* Name of the database containing pTable */
   84534   Token *pAlias,          /* The right-hand side of the AS subexpression */
   84535   Select *pSubquery,      /* A subquery used in place of a table name */
   84536   Expr *pOn,              /* The ON clause of a join */
   84537   IdList *pUsing          /* The USING clause of a join */
   84538 ){
   84539   struct SrcList_item *pItem;
   84540   sqlite3 *db = pParse->db;
   84541   if( !p && (pOn || pUsing) ){
   84542     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   84543       (pOn ? "ON" : "USING")
   84544     );
   84545     goto append_from_error;
   84546   }
   84547   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   84548   if( p==0 || NEVER(p->nSrc==0) ){
   84549     goto append_from_error;
   84550   }
   84551   pItem = &p->a[p->nSrc-1];
   84552   assert( pAlias!=0 );
   84553   if( pAlias->n ){
   84554     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   84555   }
   84556   pItem->pSelect = pSubquery;
   84557   pItem->pOn = pOn;
   84558   pItem->pUsing = pUsing;
   84559   return p;
   84560 
   84561  append_from_error:
   84562   assert( p==0 );
   84563   sqlite3ExprDelete(db, pOn);
   84564   sqlite3IdListDelete(db, pUsing);
   84565   sqlite3SelectDelete(db, pSubquery);
   84566   return 0;
   84567 }
   84568 
   84569 /*
   84570 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   84571 ** element of the source-list passed as the second argument.
   84572 */
   84573 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   84574   assert( pIndexedBy!=0 );
   84575   if( p && ALWAYS(p->nSrc>0) ){
   84576     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   84577     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   84578     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   84579       /* A "NOT INDEXED" clause was supplied. See parse.y
   84580       ** construct "indexed_opt" for details. */
   84581       pItem->notIndexed = 1;
   84582     }else{
   84583       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   84584     }
   84585   }
   84586 }
   84587 
   84588 /*
   84589 ** When building up a FROM clause in the parser, the join operator
   84590 ** is initially attached to the left operand.  But the code generator
   84591 ** expects the join operator to be on the right operand.  This routine
   84592 ** Shifts all join operators from left to right for an entire FROM
   84593 ** clause.
   84594 **
   84595 ** Example: Suppose the join is like this:
   84596 **
   84597 **           A natural cross join B
   84598 **
   84599 ** The operator is "natural cross join".  The A and B operands are stored
   84600 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   84601 ** operator with A.  This routine shifts that operator over to B.
   84602 */
   84603 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   84604   if( p ){
   84605     int i;
   84606     assert( p->a || p->nSrc==0 );
   84607     for(i=p->nSrc-1; i>0; i--){
   84608       p->a[i].jointype = p->a[i-1].jointype;
   84609     }
   84610     p->a[0].jointype = 0;
   84611   }
   84612 }
   84613 
   84614 /*
   84615 ** Begin a transaction
   84616 */
   84617 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   84618   sqlite3 *db;
   84619   Vdbe *v;
   84620   int i;
   84621 
   84622   assert( pParse!=0 );
   84623   db = pParse->db;
   84624   assert( db!=0 );
   84625 /*  if( db->aDb[0].pBt==0 ) return; */
   84626   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   84627     return;
   84628   }
   84629   v = sqlite3GetVdbe(pParse);
   84630   if( !v ) return;
   84631   if( type!=TK_DEFERRED ){
   84632     for(i=0; i<db->nDb; i++){
   84633       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   84634       sqlite3VdbeUsesBtree(v, i);
   84635     }
   84636   }
   84637   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   84638 }
   84639 
   84640 /*
   84641 ** Commit a transaction
   84642 */
   84643 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   84644   Vdbe *v;
   84645 
   84646   assert( pParse!=0 );
   84647   assert( pParse->db!=0 );
   84648   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   84649     return;
   84650   }
   84651   v = sqlite3GetVdbe(pParse);
   84652   if( v ){
   84653     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   84654   }
   84655 }
   84656 
   84657 /*
   84658 ** Rollback a transaction
   84659 */
   84660 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   84661   Vdbe *v;
   84662 
   84663   assert( pParse!=0 );
   84664   assert( pParse->db!=0 );
   84665   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   84666     return;
   84667   }
   84668   v = sqlite3GetVdbe(pParse);
   84669   if( v ){
   84670     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   84671   }
   84672 }
   84673 
   84674 /*
   84675 ** This function is called by the parser when it parses a command to create,
   84676 ** release or rollback an SQL savepoint.
   84677 */
   84678 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   84679   char *zName = sqlite3NameFromToken(pParse->db, pName);
   84680   if( zName ){
   84681     Vdbe *v = sqlite3GetVdbe(pParse);
   84682 #ifndef SQLITE_OMIT_AUTHORIZATION
   84683     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   84684     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   84685 #endif
   84686     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   84687       sqlite3DbFree(pParse->db, zName);
   84688       return;
   84689     }
   84690     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   84691   }
   84692 }
   84693 
   84694 /*
   84695 ** Make sure the TEMP database is open and available for use.  Return
   84696 ** the number of errors.  Leave any error messages in the pParse structure.
   84697 */
   84698 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   84699   sqlite3 *db = pParse->db;
   84700   if( db->aDb[1].pBt==0 && !pParse->explain ){
   84701     int rc;
   84702     Btree *pBt;
   84703     static const int flags =
   84704           SQLITE_OPEN_READWRITE |
   84705           SQLITE_OPEN_CREATE |
   84706           SQLITE_OPEN_EXCLUSIVE |
   84707           SQLITE_OPEN_DELETEONCLOSE |
   84708           SQLITE_OPEN_TEMP_DB;
   84709 
   84710     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
   84711     if( rc!=SQLITE_OK ){
   84712       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   84713         "file for storing temporary tables");
   84714       pParse->rc = rc;
   84715       return 1;
   84716     }
   84717     db->aDb[1].pBt = pBt;
   84718     assert( db->aDb[1].pSchema );
   84719     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   84720       db->mallocFailed = 1;
   84721       return 1;
   84722     }
   84723   }
   84724   return 0;
   84725 }
   84726 
   84727 /*
   84728 ** Generate VDBE code that will verify the schema cookie and start
   84729 ** a read-transaction for all named database files.
   84730 **
   84731 ** It is important that all schema cookies be verified and all
   84732 ** read transactions be started before anything else happens in
   84733 ** the VDBE program.  But this routine can be called after much other
   84734 ** code has been generated.  So here is what we do:
   84735 **
   84736 ** The first time this routine is called, we code an OP_Goto that
   84737 ** will jump to a subroutine at the end of the program.  Then we
   84738 ** record every database that needs its schema verified in the
   84739 ** pParse->cookieMask field.  Later, after all other code has been
   84740 ** generated, the subroutine that does the cookie verifications and
   84741 ** starts the transactions will be coded and the OP_Goto P2 value
   84742 ** will be made to point to that subroutine.  The generation of the
   84743 ** cookie verification subroutine code happens in sqlite3FinishCoding().
   84744 **
   84745 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
   84746 ** schema on any databases.  This can be used to position the OP_Goto
   84747 ** early in the code, before we know if any database tables will be used.
   84748 */
   84749 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   84750   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84751 
   84752   if( pToplevel->cookieGoto==0 ){
   84753     Vdbe *v = sqlite3GetVdbe(pToplevel);
   84754     if( v==0 ) return;  /* This only happens if there was a prior error */
   84755     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
   84756   }
   84757   if( iDb>=0 ){
   84758     sqlite3 *db = pToplevel->db;
   84759     yDbMask mask;
   84760 
   84761     assert( iDb<db->nDb );
   84762     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   84763     assert( iDb<SQLITE_MAX_ATTACHED+2 );
   84764     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   84765     mask = ((yDbMask)1)<<iDb;
   84766     if( (pToplevel->cookieMask & mask)==0 ){
   84767       pToplevel->cookieMask |= mask;
   84768       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   84769       if( !OMIT_TEMPDB && iDb==1 ){
   84770         sqlite3OpenTempDatabase(pToplevel);
   84771       }
   84772     }
   84773   }
   84774 }
   84775 
   84776 /*
   84777 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
   84778 ** attached database. Otherwise, invoke it for the database named zDb only.
   84779 */
   84780 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
   84781   sqlite3 *db = pParse->db;
   84782   int i;
   84783   for(i=0; i<db->nDb; i++){
   84784     Db *pDb = &db->aDb[i];
   84785     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
   84786       sqlite3CodeVerifySchema(pParse, i);
   84787     }
   84788   }
   84789 }
   84790 
   84791 /*
   84792 ** Generate VDBE code that prepares for doing an operation that
   84793 ** might change the database.
   84794 **
   84795 ** This routine starts a new transaction if we are not already within
   84796 ** a transaction.  If we are already within a transaction, then a checkpoint
   84797 ** is set if the setStatement parameter is true.  A checkpoint should
   84798 ** be set for operations that might fail (due to a constraint) part of
   84799 ** the way through and which will need to undo some writes without having to
   84800 ** rollback the whole transaction.  For operations where all constraints
   84801 ** can be checked before any changes are made to the database, it is never
   84802 ** necessary to undo a write and the checkpoint should not be set.
   84803 */
   84804 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   84805   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84806   sqlite3CodeVerifySchema(pParse, iDb);
   84807   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
   84808   pToplevel->isMultiWrite |= setStatement;
   84809 }
   84810 
   84811 /*
   84812 ** Indicate that the statement currently under construction might write
   84813 ** more than one entry (example: deleting one row then inserting another,
   84814 ** inserting multiple rows in a table, or inserting a row and index entries.)
   84815 ** If an abort occurs after some of these writes have completed, then it will
   84816 ** be necessary to undo the completed writes.
   84817 */
   84818 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   84819   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84820   pToplevel->isMultiWrite = 1;
   84821 }
   84822 
   84823 /*
   84824 ** The code generator calls this routine if is discovers that it is
   84825 ** possible to abort a statement prior to completion.  In order to
   84826 ** perform this abort without corrupting the database, we need to make
   84827 ** sure that the statement is protected by a statement transaction.
   84828 **
   84829 ** Technically, we only need to set the mayAbort flag if the
   84830 ** isMultiWrite flag was previously set.  There is a time dependency
   84831 ** such that the abort must occur after the multiwrite.  This makes
   84832 ** some statements involving the REPLACE conflict resolution algorithm
   84833 ** go a little faster.  But taking advantage of this time dependency
   84834 ** makes it more difficult to prove that the code is correct (in
   84835 ** particular, it prevents us from writing an effective
   84836 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   84837 ** to take the safe route and skip the optimization.
   84838 */
   84839 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   84840   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   84841   pToplevel->mayAbort = 1;
   84842 }
   84843 
   84844 /*
   84845 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   84846 ** error. The onError parameter determines which (if any) of the statement
   84847 ** and/or current transaction is rolled back.
   84848 */
   84849 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
   84850   Vdbe *v = sqlite3GetVdbe(pParse);
   84851   if( onError==OE_Abort ){
   84852     sqlite3MayAbort(pParse);
   84853   }
   84854   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
   84855 }
   84856 
   84857 /*
   84858 ** Check to see if pIndex uses the collating sequence pColl.  Return
   84859 ** true if it does and false if it does not.
   84860 */
   84861 #ifndef SQLITE_OMIT_REINDEX
   84862 static int collationMatch(const char *zColl, Index *pIndex){
   84863   int i;
   84864   assert( zColl!=0 );
   84865   for(i=0; i<pIndex->nColumn; i++){
   84866     const char *z = pIndex->azColl[i];
   84867     assert( z!=0 );
   84868     if( 0==sqlite3StrICmp(z, zColl) ){
   84869       return 1;
   84870     }
   84871   }
   84872   return 0;
   84873 }
   84874 #endif
   84875 
   84876 /*
   84877 ** Recompute all indices of pTab that use the collating sequence pColl.
   84878 ** If pColl==0 then recompute all indices of pTab.
   84879 */
   84880 #ifndef SQLITE_OMIT_REINDEX
   84881 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   84882   Index *pIndex;              /* An index associated with pTab */
   84883 
   84884   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   84885     if( zColl==0 || collationMatch(zColl, pIndex) ){
   84886       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   84887       sqlite3BeginWriteOperation(pParse, 0, iDb);
   84888       sqlite3RefillIndex(pParse, pIndex, -1);
   84889     }
   84890   }
   84891 }
   84892 #endif
   84893 
   84894 /*
   84895 ** Recompute all indices of all tables in all databases where the
   84896 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   84897 ** all indices everywhere.
   84898 */
   84899 #ifndef SQLITE_OMIT_REINDEX
   84900 static void reindexDatabases(Parse *pParse, char const *zColl){
   84901   Db *pDb;                    /* A single database */
   84902   int iDb;                    /* The database index number */
   84903   sqlite3 *db = pParse->db;   /* The database connection */
   84904   HashElem *k;                /* For looping over tables in pDb */
   84905   Table *pTab;                /* A table in the database */
   84906 
   84907   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
   84908   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   84909     assert( pDb!=0 );
   84910     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   84911       pTab = (Table*)sqliteHashData(k);
   84912       reindexTable(pParse, pTab, zColl);
   84913     }
   84914   }
   84915 }
   84916 #endif
   84917 
   84918 /*
   84919 ** Generate code for the REINDEX command.
   84920 **
   84921 **        REINDEX                            -- 1
   84922 **        REINDEX  <collation>               -- 2
   84923 **        REINDEX  ?<database>.?<tablename>  -- 3
   84924 **        REINDEX  ?<database>.?<indexname>  -- 4
   84925 **
   84926 ** Form 1 causes all indices in all attached databases to be rebuilt.
   84927 ** Form 2 rebuilds all indices in all databases that use the named
   84928 ** collating function.  Forms 3 and 4 rebuild the named index or all
   84929 ** indices associated with the named table.
   84930 */
   84931 #ifndef SQLITE_OMIT_REINDEX
   84932 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   84933   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   84934   char *z;                    /* Name of a table or index */
   84935   const char *zDb;            /* Name of the database */
   84936   Table *pTab;                /* A table in the database */
   84937   Index *pIndex;              /* An index associated with pTab */
   84938   int iDb;                    /* The database index number */
   84939   sqlite3 *db = pParse->db;   /* The database connection */
   84940   Token *pObjName;            /* Name of the table or index to be reindexed */
   84941 
   84942   /* Read the database schema. If an error occurs, leave an error message
   84943   ** and code in pParse and return NULL. */
   84944   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   84945     return;
   84946   }
   84947 
   84948   if( pName1==0 ){
   84949     reindexDatabases(pParse, 0);
   84950     return;
   84951   }else if( NEVER(pName2==0) || pName2->z==0 ){
   84952     char *zColl;
   84953     assert( pName1->z );
   84954     zColl = sqlite3NameFromToken(pParse->db, pName1);
   84955     if( !zColl ) return;
   84956     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   84957     if( pColl ){
   84958       reindexDatabases(pParse, zColl);
   84959       sqlite3DbFree(db, zColl);
   84960       return;
   84961     }
   84962     sqlite3DbFree(db, zColl);
   84963   }
   84964   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   84965   if( iDb<0 ) return;
   84966   z = sqlite3NameFromToken(db, pObjName);
   84967   if( z==0 ) return;
   84968   zDb = db->aDb[iDb].zName;
   84969   pTab = sqlite3FindTable(db, z, zDb);
   84970   if( pTab ){
   84971     reindexTable(pParse, pTab, 0);
   84972     sqlite3DbFree(db, z);
   84973     return;
   84974   }
   84975   pIndex = sqlite3FindIndex(db, z, zDb);
   84976   sqlite3DbFree(db, z);
   84977   if( pIndex ){
   84978     sqlite3BeginWriteOperation(pParse, 0, iDb);
   84979     sqlite3RefillIndex(pParse, pIndex, -1);
   84980     return;
   84981   }
   84982   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   84983 }
   84984 #endif
   84985 
   84986 /*
   84987 ** Return a dynamicly allocated KeyInfo structure that can be used
   84988 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
   84989 **
   84990 ** If successful, a pointer to the new structure is returned. In this case
   84991 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
   84992 ** pointer. If an error occurs (out of memory or missing collation
   84993 ** sequence), NULL is returned and the state of pParse updated to reflect
   84994 ** the error.
   84995 */
   84996 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
   84997   int i;
   84998   int nCol = pIdx->nColumn;
   84999   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
   85000   sqlite3 *db = pParse->db;
   85001   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
   85002 
   85003   if( pKey ){
   85004     pKey->db = pParse->db;
   85005     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
   85006     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
   85007     for(i=0; i<nCol; i++){
   85008       char *zColl = pIdx->azColl[i];
   85009       assert( zColl );
   85010       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
   85011       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   85012     }
   85013     pKey->nField = (u16)nCol;
   85014   }
   85015 
   85016   if( pParse->nErr ){
   85017     sqlite3DbFree(db, pKey);
   85018     pKey = 0;
   85019   }
   85020   return pKey;
   85021 }
   85022 
   85023 /************** End of build.c ***********************************************/
   85024 /************** Begin file callback.c ****************************************/
   85025 /*
   85026 ** 2005 May 23
   85027 **
   85028 ** The author disclaims copyright to this source code.  In place of
   85029 ** a legal notice, here is a blessing:
   85030 **
   85031 **    May you do good and not evil.
   85032 **    May you find forgiveness for yourself and forgive others.
   85033 **    May you share freely, never taking more than you give.
   85034 **
   85035 *************************************************************************
   85036 **
   85037 ** This file contains functions used to access the internal hash tables
   85038 ** of user defined functions and collation sequences.
   85039 */
   85040 
   85041 
   85042 /*
   85043 ** Invoke the 'collation needed' callback to request a collation sequence
   85044 ** in the encoding enc of name zName, length nName.
   85045 */
   85046 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   85047   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   85048   if( db->xCollNeeded ){
   85049     char *zExternal = sqlite3DbStrDup(db, zName);
   85050     if( !zExternal ) return;
   85051     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   85052     sqlite3DbFree(db, zExternal);
   85053   }
   85054 #ifndef SQLITE_OMIT_UTF16
   85055   if( db->xCollNeeded16 ){
   85056     char const *zExternal;
   85057     sqlite3_value *pTmp = sqlite3ValueNew(db);
   85058     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   85059     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   85060     if( zExternal ){
   85061       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   85062     }
   85063     sqlite3ValueFree(pTmp);
   85064   }
   85065 #endif
   85066 }
   85067 
   85068 /*
   85069 ** This routine is called if the collation factory fails to deliver a
   85070 ** collation function in the best encoding but there may be other versions
   85071 ** of this collation function (for other text encodings) available. Use one
   85072 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   85073 ** possible.
   85074 */
   85075 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   85076   CollSeq *pColl2;
   85077   char *z = pColl->zName;
   85078   int i;
   85079   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   85080   for(i=0; i<3; i++){
   85081     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   85082     if( pColl2->xCmp!=0 ){
   85083       memcpy(pColl, pColl2, sizeof(CollSeq));
   85084       pColl->xDel = 0;         /* Do not copy the destructor */
   85085       return SQLITE_OK;
   85086     }
   85087   }
   85088   return SQLITE_ERROR;
   85089 }
   85090 
   85091 /*
   85092 ** This function is responsible for invoking the collation factory callback
   85093 ** or substituting a collation sequence of a different encoding when the
   85094 ** requested collation sequence is not available in the desired encoding.
   85095 **
   85096 ** If it is not NULL, then pColl must point to the database native encoding
   85097 ** collation sequence with name zName, length nName.
   85098 **
   85099 ** The return value is either the collation sequence to be used in database
   85100 ** db for collation type name zName, length nName, or NULL, if no collation
   85101 ** sequence can be found.
   85102 **
   85103 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   85104 */
   85105 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   85106   sqlite3* db,          /* The database connection */
   85107   u8 enc,               /* The desired encoding for the collating sequence */
   85108   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   85109   const char *zName     /* Collating sequence name */
   85110 ){
   85111   CollSeq *p;
   85112 
   85113   p = pColl;
   85114   if( !p ){
   85115     p = sqlite3FindCollSeq(db, enc, zName, 0);
   85116   }
   85117   if( !p || !p->xCmp ){
   85118     /* No collation sequence of this type for this encoding is registered.
   85119     ** Call the collation factory to see if it can supply us with one.
   85120     */
   85121     callCollNeeded(db, enc, zName);
   85122     p = sqlite3FindCollSeq(db, enc, zName, 0);
   85123   }
   85124   if( p && !p->xCmp && synthCollSeq(db, p) ){
   85125     p = 0;
   85126   }
   85127   assert( !p || p->xCmp );
   85128   return p;
   85129 }
   85130 
   85131 /*
   85132 ** This routine is called on a collation sequence before it is used to
   85133 ** check that it is defined. An undefined collation sequence exists when
   85134 ** a database is loaded that contains references to collation sequences
   85135 ** that have not been defined by sqlite3_create_collation() etc.
   85136 **
   85137 ** If required, this routine calls the 'collation needed' callback to
   85138 ** request a definition of the collating sequence. If this doesn't work,
   85139 ** an equivalent collating sequence that uses a text encoding different
   85140 ** from the main database is substituted, if one is available.
   85141 */
   85142 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   85143   if( pColl ){
   85144     const char *zName = pColl->zName;
   85145     sqlite3 *db = pParse->db;
   85146     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
   85147     if( !p ){
   85148       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   85149       pParse->nErr++;
   85150       return SQLITE_ERROR;
   85151     }
   85152     assert( p==pColl );
   85153   }
   85154   return SQLITE_OK;
   85155 }
   85156 
   85157 
   85158 
   85159 /*
   85160 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   85161 ** specified by zName and nName is not found and parameter 'create' is
   85162 ** true, then create a new entry. Otherwise return NULL.
   85163 **
   85164 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   85165 ** array of three CollSeq structures. The first is the collation sequence
   85166 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   85167 **
   85168 ** Stored immediately after the three collation sequences is a copy of
   85169 ** the collation sequence name. A pointer to this string is stored in
   85170 ** each collation sequence structure.
   85171 */
   85172 static CollSeq *findCollSeqEntry(
   85173   sqlite3 *db,          /* Database connection */
   85174   const char *zName,    /* Name of the collating sequence */
   85175   int create            /* Create a new entry if true */
   85176 ){
   85177   CollSeq *pColl;
   85178   int nName = sqlite3Strlen30(zName);
   85179   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   85180 
   85181   if( 0==pColl && create ){
   85182     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   85183     if( pColl ){
   85184       CollSeq *pDel = 0;
   85185       pColl[0].zName = (char*)&pColl[3];
   85186       pColl[0].enc = SQLITE_UTF8;
   85187       pColl[1].zName = (char*)&pColl[3];
   85188       pColl[1].enc = SQLITE_UTF16LE;
   85189       pColl[2].zName = (char*)&pColl[3];
   85190       pColl[2].enc = SQLITE_UTF16BE;
   85191       memcpy(pColl[0].zName, zName, nName);
   85192       pColl[0].zName[nName] = 0;
   85193       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   85194 
   85195       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   85196       ** return the pColl pointer to be deleted (because it wasn't added
   85197       ** to the hash table).
   85198       */
   85199       assert( pDel==0 || pDel==pColl );
   85200       if( pDel!=0 ){
   85201         db->mallocFailed = 1;
   85202         sqlite3DbFree(db, pDel);
   85203         pColl = 0;
   85204       }
   85205     }
   85206   }
   85207   return pColl;
   85208 }
   85209 
   85210 /*
   85211 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   85212 ** Return the CollSeq* pointer for the collation sequence named zName
   85213 ** for the encoding 'enc' from the database 'db'.
   85214 **
   85215 ** If the entry specified is not found and 'create' is true, then create a
   85216 ** new entry.  Otherwise return NULL.
   85217 **
   85218 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   85219 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   85220 ** if necessary and generates an error message if the collating sequence
   85221 ** cannot be found.
   85222 **
   85223 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   85224 */
   85225 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   85226   sqlite3 *db,
   85227   u8 enc,
   85228   const char *zName,
   85229   int create
   85230 ){
   85231   CollSeq *pColl;
   85232   if( zName ){
   85233     pColl = findCollSeqEntry(db, zName, create);
   85234   }else{
   85235     pColl = db->pDfltColl;
   85236   }
   85237   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   85238   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   85239   if( pColl ) pColl += enc-1;
   85240   return pColl;
   85241 }
   85242 
   85243 /* During the search for the best function definition, this procedure
   85244 ** is called to test how well the function passed as the first argument
   85245 ** matches the request for a function with nArg arguments in a system
   85246 ** that uses encoding enc. The value returned indicates how well the
   85247 ** request is matched. A higher value indicates a better match.
   85248 **
   85249 ** The returned value is always between 0 and 6, as follows:
   85250 **
   85251 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
   85252 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
   85253 **    encoding is requested, or vice versa.
   85254 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
   85255 **    requested, or vice versa.
   85256 ** 3: A variable arguments function using the same text encoding.
   85257 ** 4: A function with the exact number of arguments requested that
   85258 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
   85259 ** 5: A function with the exact number of arguments requested that
   85260 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
   85261 ** 6: An exact match.
   85262 **
   85263 */
   85264 static int matchQuality(FuncDef *p, int nArg, u8 enc){
   85265   int match = 0;
   85266   if( p->nArg==-1 || p->nArg==nArg
   85267    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
   85268   ){
   85269     match = 1;
   85270     if( p->nArg==nArg || nArg==-1 ){
   85271       match = 4;
   85272     }
   85273     if( enc==p->iPrefEnc ){
   85274       match += 2;
   85275     }
   85276     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
   85277              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
   85278       match += 1;
   85279     }
   85280   }
   85281   return match;
   85282 }
   85283 
   85284 /*
   85285 ** Search a FuncDefHash for a function with the given name.  Return
   85286 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   85287 */
   85288 static FuncDef *functionSearch(
   85289   FuncDefHash *pHash,  /* Hash table to search */
   85290   int h,               /* Hash of the name */
   85291   const char *zFunc,   /* Name of function */
   85292   int nFunc            /* Number of bytes in zFunc */
   85293 ){
   85294   FuncDef *p;
   85295   for(p=pHash->a[h]; p; p=p->pHash){
   85296     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   85297       return p;
   85298     }
   85299   }
   85300   return 0;
   85301 }
   85302 
   85303 /*
   85304 ** Insert a new FuncDef into a FuncDefHash hash table.
   85305 */
   85306 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   85307   FuncDefHash *pHash,  /* The hash table into which to insert */
   85308   FuncDef *pDef        /* The function definition to insert */
   85309 ){
   85310   FuncDef *pOther;
   85311   int nName = sqlite3Strlen30(pDef->zName);
   85312   u8 c1 = (u8)pDef->zName[0];
   85313   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   85314   pOther = functionSearch(pHash, h, pDef->zName, nName);
   85315   if( pOther ){
   85316     assert( pOther!=pDef && pOther->pNext!=pDef );
   85317     pDef->pNext = pOther->pNext;
   85318     pOther->pNext = pDef;
   85319   }else{
   85320     pDef->pNext = 0;
   85321     pDef->pHash = pHash->a[h];
   85322     pHash->a[h] = pDef;
   85323   }
   85324 }
   85325 
   85326 
   85327 
   85328 /*
   85329 ** Locate a user function given a name, a number of arguments and a flag
   85330 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   85331 ** pointer to the FuncDef structure that defines that function, or return
   85332 ** NULL if the function does not exist.
   85333 **
   85334 ** If the createFlag argument is true, then a new (blank) FuncDef
   85335 ** structure is created and liked into the "db" structure if a
   85336 ** no matching function previously existed.  When createFlag is true
   85337 ** and the nArg parameter is -1, then only a function that accepts
   85338 ** any number of arguments will be returned.
   85339 **
   85340 ** If createFlag is false and nArg is -1, then the first valid
   85341 ** function found is returned.  A function is valid if either xFunc
   85342 ** or xStep is non-zero.
   85343 **
   85344 ** If createFlag is false, then a function with the required name and
   85345 ** number of arguments may be returned even if the eTextRep flag does not
   85346 ** match that requested.
   85347 */
   85348 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   85349   sqlite3 *db,       /* An open database */
   85350   const char *zName, /* Name of the function.  Not null-terminated */
   85351   int nName,         /* Number of characters in the name */
   85352   int nArg,          /* Number of arguments.  -1 means any number */
   85353   u8 enc,            /* Preferred text encoding */
   85354   int createFlag     /* Create new entry if true and does not otherwise exist */
   85355 ){
   85356   FuncDef *p;         /* Iterator variable */
   85357   FuncDef *pBest = 0; /* Best match found so far */
   85358   int bestScore = 0;  /* Score of best match */
   85359   int h;              /* Hash value */
   85360 
   85361 
   85362   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   85363   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   85364 
   85365   /* First search for a match amongst the application-defined functions.
   85366   */
   85367   p = functionSearch(&db->aFunc, h, zName, nName);
   85368   while( p ){
   85369     int score = matchQuality(p, nArg, enc);
   85370     if( score>bestScore ){
   85371       pBest = p;
   85372       bestScore = score;
   85373     }
   85374     p = p->pNext;
   85375   }
   85376 
   85377   /* If no match is found, search the built-in functions.
   85378   **
   85379   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
   85380   ** functions even if a prior app-defined function was found.  And give
   85381   ** priority to built-in functions.
   85382   **
   85383   ** Except, if createFlag is true, that means that we are trying to
   85384   ** install a new function.  Whatever FuncDef structure is returned it will
   85385   ** have fields overwritten with new information appropriate for the
   85386   ** new function.  But the FuncDefs for built-in functions are read-only.
   85387   ** So we must not search for built-ins when creating a new function.
   85388   */
   85389   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
   85390     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   85391     bestScore = 0;
   85392     p = functionSearch(pHash, 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 
   85403   /* If the createFlag parameter is true and the search did not reveal an
   85404   ** exact match for the name, number of arguments and encoding, then add a
   85405   ** new entry to the hash table and return it.
   85406   */
   85407   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
   85408       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   85409     pBest->zName = (char *)&pBest[1];
   85410     pBest->nArg = (u16)nArg;
   85411     pBest->iPrefEnc = enc;
   85412     memcpy(pBest->zName, zName, nName);
   85413     pBest->zName[nName] = 0;
   85414     sqlite3FuncDefInsert(&db->aFunc, pBest);
   85415   }
   85416 
   85417   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   85418     return pBest;
   85419   }
   85420   return 0;
   85421 }
   85422 
   85423 /*
   85424 ** Free all resources held by the schema structure. The void* argument points
   85425 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   85426 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
   85427 ** of the schema hash tables).
   85428 **
   85429 ** The Schema.cache_size variable is not cleared.
   85430 */
   85431 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
   85432   Hash temp1;
   85433   Hash temp2;
   85434   HashElem *pElem;
   85435   Schema *pSchema = (Schema *)p;
   85436 
   85437   temp1 = pSchema->tblHash;
   85438   temp2 = pSchema->trigHash;
   85439   sqlite3HashInit(&pSchema->trigHash);
   85440   sqlite3HashClear(&pSchema->idxHash);
   85441   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   85442     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   85443   }
   85444   sqlite3HashClear(&temp2);
   85445   sqlite3HashInit(&pSchema->tblHash);
   85446   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   85447     Table *pTab = sqliteHashData(pElem);
   85448     sqlite3DeleteTable(0, pTab);
   85449   }
   85450   sqlite3HashClear(&temp1);
   85451   sqlite3HashClear(&pSchema->fkeyHash);
   85452   pSchema->pSeqTab = 0;
   85453   if( pSchema->flags & DB_SchemaLoaded ){
   85454     pSchema->iGeneration++;
   85455     pSchema->flags &= ~DB_SchemaLoaded;
   85456   }
   85457 }
   85458 
   85459 /*
   85460 ** Find and return the schema associated with a BTree.  Create
   85461 ** a new one if necessary.
   85462 */
   85463 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   85464   Schema * p;
   85465   if( pBt ){
   85466     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   85467   }else{
   85468     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   85469   }
   85470   if( !p ){
   85471     db->mallocFailed = 1;
   85472   }else if ( 0==p->file_format ){
   85473     sqlite3HashInit(&p->tblHash);
   85474     sqlite3HashInit(&p->idxHash);
   85475     sqlite3HashInit(&p->trigHash);
   85476     sqlite3HashInit(&p->fkeyHash);
   85477     p->enc = SQLITE_UTF8;
   85478   }
   85479   return p;
   85480 }
   85481 
   85482 /************** End of callback.c ********************************************/
   85483 /************** Begin file delete.c ******************************************/
   85484 /*
   85485 ** 2001 September 15
   85486 **
   85487 ** The author disclaims copyright to this source code.  In place of
   85488 ** a legal notice, here is a blessing:
   85489 **
   85490 **    May you do good and not evil.
   85491 **    May you find forgiveness for yourself and forgive others.
   85492 **    May you share freely, never taking more than you give.
   85493 **
   85494 *************************************************************************
   85495 ** This file contains C code routines that are called by the parser
   85496 ** in order to generate code for DELETE FROM statements.
   85497 */
   85498 
   85499 /*
   85500 ** While a SrcList can in general represent multiple tables and subqueries
   85501 ** (as in the FROM clause of a SELECT statement) in this case it contains
   85502 ** the name of a single table, as one might find in an INSERT, DELETE,
   85503 ** or UPDATE statement.  Look up that table in the symbol table and
   85504 ** return a pointer.  Set an error message and return NULL if the table
   85505 ** name is not found or if any other error occurs.
   85506 **
   85507 ** The following fields are initialized appropriate in pSrc:
   85508 **
   85509 **    pSrc->a[0].pTab       Pointer to the Table object
   85510 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
   85511 **
   85512 */
   85513 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   85514   struct SrcList_item *pItem = pSrc->a;
   85515   Table *pTab;
   85516   assert( pItem && pSrc->nSrc==1 );
   85517   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   85518   sqlite3DeleteTable(pParse->db, pItem->pTab);
   85519   pItem->pTab = pTab;
   85520   if( pTab ){
   85521     pTab->nRef++;
   85522   }
   85523   if( sqlite3IndexedByLookup(pParse, pItem) ){
   85524     pTab = 0;
   85525   }
   85526   return pTab;
   85527 }
   85528 
   85529 /*
   85530 ** Check to make sure the given table is writable.  If it is not
   85531 ** writable, generate an error message and return 1.  If it is
   85532 ** writable return 0;
   85533 */
   85534 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   85535   /* A table is not writable under the following circumstances:
   85536   **
   85537   **   1) It is a virtual table and no implementation of the xUpdate method
   85538   **      has been provided, or
   85539   **   2) It is a system table (i.e. sqlite_master), this call is not
   85540   **      part of a nested parse and writable_schema pragma has not
   85541   **      been specified.
   85542   **
   85543   ** In either case leave an error message in pParse and return non-zero.
   85544   */
   85545   if( ( IsVirtual(pTab)
   85546      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   85547    || ( (pTab->tabFlags & TF_Readonly)!=0
   85548      && (pParse->db->flags & SQLITE_WriteSchema)==0
   85549      && pParse->nested==0 )
   85550   ){
   85551     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   85552     return 1;
   85553   }
   85554 
   85555 #ifndef SQLITE_OMIT_VIEW
   85556   if( !viewOk && pTab->pSelect ){
   85557     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   85558     return 1;
   85559   }
   85560 #endif
   85561   return 0;
   85562 }
   85563 
   85564 
   85565 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   85566 /*
   85567 ** Evaluate a view and store its result in an ephemeral table.  The
   85568 ** pWhere argument is an optional WHERE clause that restricts the
   85569 ** set of rows in the view that are to be added to the ephemeral table.
   85570 */
   85571 SQLITE_PRIVATE void sqlite3MaterializeView(
   85572   Parse *pParse,       /* Parsing context */
   85573   Table *pView,        /* View definition */
   85574   Expr *pWhere,        /* Optional WHERE clause to be added */
   85575   int iCur             /* Cursor number for ephemerial table */
   85576 ){
   85577   SelectDest dest;
   85578   Select *pDup;
   85579   sqlite3 *db = pParse->db;
   85580 
   85581   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
   85582   if( pWhere ){
   85583     SrcList *pFrom;
   85584 
   85585     pWhere = sqlite3ExprDup(db, pWhere, 0);
   85586     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   85587     if( pFrom ){
   85588       assert( pFrom->nSrc==1 );
   85589       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
   85590       pFrom->a[0].pSelect = pDup;
   85591       assert( pFrom->a[0].pOn==0 );
   85592       assert( pFrom->a[0].pUsing==0 );
   85593     }else{
   85594       sqlite3SelectDelete(db, pDup);
   85595     }
   85596     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   85597   }
   85598   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   85599   sqlite3Select(pParse, pDup, &dest);
   85600   sqlite3SelectDelete(db, pDup);
   85601 }
   85602 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   85603 
   85604 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   85605 /*
   85606 ** Generate an expression tree to implement the WHERE, ORDER BY,
   85607 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   85608 **
   85609 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   85610 **                            \__________________________/
   85611 **                               pLimitWhere (pInClause)
   85612 */
   85613 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   85614   Parse *pParse,               /* The parser context */
   85615   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   85616   Expr *pWhere,                /* The WHERE clause.  May be null */
   85617   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   85618   Expr *pLimit,                /* The LIMIT clause.  May be null */
   85619   Expr *pOffset,               /* The OFFSET clause.  May be null */
   85620   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
   85621 ){
   85622   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   85623   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   85624   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   85625   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   85626   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   85627   Select *pSelect = NULL;      /* Complete SELECT tree */
   85628 
   85629   /* Check that there isn't an ORDER BY without a LIMIT clause.
   85630   */
   85631   if( pOrderBy && (pLimit == 0) ) {
   85632     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   85633     goto limit_where_cleanup_2;
   85634   }
   85635 
   85636   /* We only need to generate a select expression if there
   85637   ** is a limit/offset term to enforce.
   85638   */
   85639   if( pLimit == 0 ) {
   85640     /* if pLimit is null, pOffset will always be null as well. */
   85641     assert( pOffset == 0 );
   85642     return pWhere;
   85643   }
   85644 
   85645   /* Generate a select expression tree to enforce the limit/offset
   85646   ** term for the DELETE or UPDATE statement.  For example:
   85647   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   85648   ** becomes:
   85649   **   DELETE FROM table_a WHERE rowid IN (
   85650   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   85651   **   );
   85652   */
   85653 
   85654   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   85655   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   85656   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   85657   if( pEList == 0 ) goto limit_where_cleanup_2;
   85658 
   85659   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   85660   ** and the SELECT subtree. */
   85661   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   85662   if( pSelectSrc == 0 ) {
   85663     sqlite3ExprListDelete(pParse->db, pEList);
   85664     goto limit_where_cleanup_2;
   85665   }
   85666 
   85667   /* generate the SELECT expression tree. */
   85668   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   85669                              pOrderBy,0,pLimit,pOffset);
   85670   if( pSelect == 0 ) return 0;
   85671 
   85672   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   85673   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   85674   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   85675   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   85676   if( pInClause == 0 ) goto limit_where_cleanup_1;
   85677 
   85678   pInClause->x.pSelect = pSelect;
   85679   pInClause->flags |= EP_xIsSelect;
   85680   sqlite3ExprSetHeight(pParse, pInClause);
   85681   return pInClause;
   85682 
   85683   /* something went wrong. clean up anything allocated. */
   85684 limit_where_cleanup_1:
   85685   sqlite3SelectDelete(pParse->db, pSelect);
   85686   return 0;
   85687 
   85688 limit_where_cleanup_2:
   85689   sqlite3ExprDelete(pParse->db, pWhere);
   85690   sqlite3ExprListDelete(pParse->db, pOrderBy);
   85691   sqlite3ExprDelete(pParse->db, pLimit);
   85692   sqlite3ExprDelete(pParse->db, pOffset);
   85693   return 0;
   85694 }
   85695 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   85696 
   85697 /*
   85698 ** Generate code for a DELETE FROM statement.
   85699 **
   85700 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   85701 **                 \________/       \________________/
   85702 **                  pTabList              pWhere
   85703 */
   85704 SQLITE_PRIVATE void sqlite3DeleteFrom(
   85705   Parse *pParse,         /* The parser context */
   85706   SrcList *pTabList,     /* The table from which we should delete things */
   85707   Expr *pWhere           /* The WHERE clause.  May be null */
   85708 ){
   85709   Vdbe *v;               /* The virtual database engine */
   85710   Table *pTab;           /* The table from which records will be deleted */
   85711   const char *zDb;       /* Name of database holding pTab */
   85712   int end, addr = 0;     /* A couple addresses of generated code */
   85713   int i;                 /* Loop counter */
   85714   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   85715   Index *pIdx;           /* For looping over indices of the table */
   85716   int iCur;              /* VDBE Cursor number for pTab */
   85717   sqlite3 *db;           /* Main database structure */
   85718   AuthContext sContext;  /* Authorization context */
   85719   NameContext sNC;       /* Name context to resolve expressions in */
   85720   int iDb;               /* Database number */
   85721   int memCnt = -1;       /* Memory cell used for change counting */
   85722   int rcauth;            /* Value returned by authorization callback */
   85723 
   85724 #ifndef SQLITE_OMIT_TRIGGER
   85725   int isView;                  /* True if attempting to delete from a view */
   85726   Trigger *pTrigger;           /* List of table triggers, if required */
   85727 #endif
   85728 
   85729   memset(&sContext, 0, sizeof(sContext));
   85730   db = pParse->db;
   85731   if( pParse->nErr || db->mallocFailed ){
   85732     goto delete_from_cleanup;
   85733   }
   85734   assert( pTabList->nSrc==1 );
   85735 
   85736   /* Locate the table which we want to delete.  This table has to be
   85737   ** put in an SrcList structure because some of the subroutines we
   85738   ** will be calling are designed to work with multiple tables and expect
   85739   ** an SrcList* parameter instead of just a Table* parameter.
   85740   */
   85741   pTab = sqlite3SrcListLookup(pParse, pTabList);
   85742   if( pTab==0 )  goto delete_from_cleanup;
   85743 
   85744   /* Figure out if we have any triggers and if the table being
   85745   ** deleted from is a view
   85746   */
   85747 #ifndef SQLITE_OMIT_TRIGGER
   85748   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   85749   isView = pTab->pSelect!=0;
   85750 #else
   85751 # define pTrigger 0
   85752 # define isView 0
   85753 #endif
   85754 #ifdef SQLITE_OMIT_VIEW
   85755 # undef isView
   85756 # define isView 0
   85757 #endif
   85758 
   85759   /* If pTab is really a view, make sure it has been initialized.
   85760   */
   85761   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   85762     goto delete_from_cleanup;
   85763   }
   85764 
   85765   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   85766     goto delete_from_cleanup;
   85767   }
   85768   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   85769   assert( iDb<db->nDb );
   85770   zDb = db->aDb[iDb].zName;
   85771   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   85772   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   85773   if( rcauth==SQLITE_DENY ){
   85774     goto delete_from_cleanup;
   85775   }
   85776   assert(!isView || pTrigger);
   85777 
   85778   /* Assign  cursor number to the table and all its indices.
   85779   */
   85780   assert( pTabList->nSrc==1 );
   85781   iCur = pTabList->a[0].iCursor = pParse->nTab++;
   85782   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   85783     pParse->nTab++;
   85784   }
   85785 
   85786   /* Start the view context
   85787   */
   85788   if( isView ){
   85789     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   85790   }
   85791 
   85792   /* Begin generating code.
   85793   */
   85794   v = sqlite3GetVdbe(pParse);
   85795   if( v==0 ){
   85796     goto delete_from_cleanup;
   85797   }
   85798   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   85799   sqlite3BeginWriteOperation(pParse, 1, iDb);
   85800 
   85801   /* If we are trying to delete from a view, realize that view into
   85802   ** a ephemeral table.
   85803   */
   85804 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   85805   if( isView ){
   85806     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   85807   }
   85808 #endif
   85809 
   85810   /* Resolve the column names in the WHERE clause.
   85811   */
   85812   memset(&sNC, 0, sizeof(sNC));
   85813   sNC.pParse = pParse;
   85814   sNC.pSrcList = pTabList;
   85815   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   85816     goto delete_from_cleanup;
   85817   }
   85818 
   85819   /* Initialize the counter of the number of rows deleted, if
   85820   ** we are counting rows.
   85821   */
   85822   if( db->flags & SQLITE_CountRows ){
   85823     memCnt = ++pParse->nMem;
   85824     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   85825   }
   85826 
   85827 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   85828   /* Special case: A DELETE without a WHERE clause deletes everything.
   85829   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   85830   ** this optimization caused the row change count (the value returned by
   85831   ** API function sqlite3_count_changes) to be set incorrectly.  */
   85832   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   85833    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   85834   ){
   85835     assert( !isView );
   85836     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   85837                       pTab->zName, P4_STATIC);
   85838     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   85839       assert( pIdx->pSchema==pTab->pSchema );
   85840       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   85841     }
   85842   }else
   85843 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   85844   /* The usual case: There is a WHERE clause so we have to scan through
   85845   ** the table and pick which records to delete.
   85846   */
   85847   {
   85848     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
   85849     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
   85850     int regRowid;                   /* Actual register containing rowids */
   85851 
   85852     /* Collect rowids of every row to be deleted.
   85853     */
   85854     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   85855     pWInfo = sqlite3WhereBegin(
   85856         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
   85857     );
   85858     if( pWInfo==0 ) goto delete_from_cleanup;
   85859     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
   85860     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
   85861     if( db->flags & SQLITE_CountRows ){
   85862       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   85863     }
   85864     sqlite3WhereEnd(pWInfo);
   85865 
   85866     /* Delete every item whose key was written to the list during the
   85867     ** database scan.  We have to delete items after the scan is complete
   85868     ** because deleting an item can change the scan order.  */
   85869     end = sqlite3VdbeMakeLabel(v);
   85870 
   85871     /* Unless this is a view, open cursors for the table we are
   85872     ** deleting from and all its indices. If this is a view, then the
   85873     ** only effect this statement has is to fire the INSTEAD OF
   85874     ** triggers.  */
   85875     if( !isView ){
   85876       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
   85877     }
   85878 
   85879     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
   85880 
   85881     /* Delete the row */
   85882 #ifndef SQLITE_OMIT_VIRTUALTABLE
   85883     if( IsVirtual(pTab) ){
   85884       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   85885       sqlite3VtabMakeWritable(pParse, pTab);
   85886       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
   85887       sqlite3VdbeChangeP5(v, OE_Abort);
   85888       sqlite3MayAbort(pParse);
   85889     }else
   85890 #endif
   85891     {
   85892       int count = (pParse->nested==0);    /* True to count changes */
   85893       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
   85894     }
   85895 
   85896     /* End of the delete loop */
   85897     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   85898     sqlite3VdbeResolveLabel(v, end);
   85899 
   85900     /* Close the cursors open on the table and its indexes. */
   85901     if( !isView && !IsVirtual(pTab) ){
   85902       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   85903         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
   85904       }
   85905       sqlite3VdbeAddOp1(v, OP_Close, iCur);
   85906     }
   85907   }
   85908 
   85909   /* Update the sqlite_sequence table by storing the content of the
   85910   ** maximum rowid counter values recorded while inserting into
   85911   ** autoincrement tables.
   85912   */
   85913   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   85914     sqlite3AutoincrementEnd(pParse);
   85915   }
   85916 
   85917   /* Return the number of rows that were deleted. If this routine is
   85918   ** generating code because of a call to sqlite3NestedParse(), do not
   85919   ** invoke the callback function.
   85920   */
   85921   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   85922     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   85923     sqlite3VdbeSetNumCols(v, 1);
   85924     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   85925   }
   85926 
   85927 delete_from_cleanup:
   85928   sqlite3AuthContextPop(&sContext);
   85929   sqlite3SrcListDelete(db, pTabList);
   85930   sqlite3ExprDelete(db, pWhere);
   85931   return;
   85932 }
   85933 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   85934 ** thely may interfere with compilation of other functions in this file
   85935 ** (or in another file, if this file becomes part of the amalgamation).  */
   85936 #ifdef isView
   85937  #undef isView
   85938 #endif
   85939 #ifdef pTrigger
   85940  #undef pTrigger
   85941 #endif
   85942 
   85943 /*
   85944 ** This routine generates VDBE code that causes a single row of a
   85945 ** single table to be deleted.
   85946 **
   85947 ** The VDBE must be in a particular state when this routine is called.
   85948 ** These are the requirements:
   85949 **
   85950 **   1.  A read/write cursor pointing to pTab, the table containing the row
   85951 **       to be deleted, must be opened as cursor number $iCur.
   85952 **
   85953 **   2.  Read/write cursors for all indices of pTab must be open as
   85954 **       cursor number base+i for the i-th index.
   85955 **
   85956 **   3.  The record number of the row to be deleted must be stored in
   85957 **       memory cell iRowid.
   85958 **
   85959 ** This routine generates code to remove both the table record and all
   85960 ** index entries that point to that record.
   85961 */
   85962 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   85963   Parse *pParse,     /* Parsing context */
   85964   Table *pTab,       /* Table containing the row to be deleted */
   85965   int iCur,          /* Cursor number for the table */
   85966   int iRowid,        /* Memory cell that contains the rowid to delete */
   85967   int count,         /* If non-zero, increment the row change counter */
   85968   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   85969   int onconf         /* Default ON CONFLICT policy for triggers */
   85970 ){
   85971   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   85972   int iOld = 0;                   /* First register in OLD.* array */
   85973   int iLabel;                     /* Label resolved to end of generated code */
   85974 
   85975   /* Vdbe is guaranteed to have been allocated by this stage. */
   85976   assert( v );
   85977 
   85978   /* Seek cursor iCur to the row to delete. If this row no longer exists
   85979   ** (this can happen if a trigger program has already deleted it), do
   85980   ** not attempt to delete it or fire any DELETE triggers.  */
   85981   iLabel = sqlite3VdbeMakeLabel(v);
   85982   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   85983 
   85984   /* If there are any triggers to fire, allocate a range of registers to
   85985   ** use for the old.* references in the triggers.  */
   85986   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   85987     u32 mask;                     /* Mask of OLD.* columns in use */
   85988     int iCol;                     /* Iterator used while populating OLD.* */
   85989 
   85990     /* TODO: Could use temporary registers here. Also could attempt to
   85991     ** avoid copying the contents of the rowid register.  */
   85992     mask = sqlite3TriggerColmask(
   85993         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   85994     );
   85995     mask |= sqlite3FkOldmask(pParse, pTab);
   85996     iOld = pParse->nMem+1;
   85997     pParse->nMem += (1 + pTab->nCol);
   85998 
   85999     /* Populate the OLD.* pseudo-table register array. These values will be
   86000     ** used by any BEFORE and AFTER triggers that exist.  */
   86001     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
   86002     for(iCol=0; iCol<pTab->nCol; iCol++){
   86003       if( mask==0xffffffff || mask&(1<<iCol) ){
   86004         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
   86005       }
   86006     }
   86007 
   86008     /* Invoke BEFORE DELETE trigger programs. */
   86009     sqlite3CodeRowTrigger(pParse, pTrigger,
   86010         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   86011     );
   86012 
   86013     /* Seek the cursor to the row to be deleted again. It may be that
   86014     ** the BEFORE triggers coded above have already removed the row
   86015     ** being deleted. Do not attempt to delete the row a second time, and
   86016     ** do not fire AFTER triggers.  */
   86017     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   86018 
   86019     /* Do FK processing. This call checks that any FK constraints that
   86020     ** refer to this table (i.e. constraints attached to other tables)
   86021     ** are not violated by deleting this row.  */
   86022     sqlite3FkCheck(pParse, pTab, iOld, 0);
   86023   }
   86024 
   86025   /* Delete the index and table entries. Skip this step if pTab is really
   86026   ** a view (in which case the only effect of the DELETE statement is to
   86027   ** fire the INSTEAD OF triggers).  */
   86028   if( pTab->pSelect==0 ){
   86029     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
   86030     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
   86031     if( count ){
   86032       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   86033     }
   86034   }
   86035 
   86036   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   86037   ** handle rows (possibly in other tables) that refer via a foreign key
   86038   ** to the row just deleted. */
   86039   sqlite3FkActions(pParse, pTab, 0, iOld);
   86040 
   86041   /* Invoke AFTER DELETE trigger programs. */
   86042   sqlite3CodeRowTrigger(pParse, pTrigger,
   86043       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   86044   );
   86045 
   86046   /* Jump here if the row had already been deleted before any BEFORE
   86047   ** trigger programs were invoked. Or if a trigger program throws a
   86048   ** RAISE(IGNORE) exception.  */
   86049   sqlite3VdbeResolveLabel(v, iLabel);
   86050 }
   86051 
   86052 /*
   86053 ** This routine generates VDBE code that causes the deletion of all
   86054 ** index entries associated with a single row of a single table.
   86055 **
   86056 ** The VDBE must be in a particular state when this routine is called.
   86057 ** These are the requirements:
   86058 **
   86059 **   1.  A read/write cursor pointing to pTab, the table containing the row
   86060 **       to be deleted, must be opened as cursor number "iCur".
   86061 **
   86062 **   2.  Read/write cursors for all indices of pTab must be open as
   86063 **       cursor number iCur+i for the i-th index.
   86064 **
   86065 **   3.  The "iCur" cursor must be pointing to the row that is to be
   86066 **       deleted.
   86067 */
   86068 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   86069   Parse *pParse,     /* Parsing and code generating context */
   86070   Table *pTab,       /* Table containing the row to be deleted */
   86071   int iCur,          /* Cursor number for the table */
   86072   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   86073 ){
   86074   int i;
   86075   Index *pIdx;
   86076   int r1;
   86077 
   86078   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   86079     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
   86080     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
   86081     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
   86082   }
   86083 }
   86084 
   86085 /*
   86086 ** Generate code that will assemble an index key and put it in register
   86087 ** regOut.  The key with be for index pIdx which is an index on pTab.
   86088 ** iCur is the index of a cursor open on the pTab table and pointing to
   86089 ** the entry that needs indexing.
   86090 **
   86091 ** Return a register number which is the first in a block of
   86092 ** registers that holds the elements of the index key.  The
   86093 ** block of registers has already been deallocated by the time
   86094 ** this routine returns.
   86095 */
   86096 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   86097   Parse *pParse,     /* Parsing context */
   86098   Index *pIdx,       /* The index for which to generate a key */
   86099   int iCur,          /* Cursor number for the pIdx->pTable table */
   86100   int regOut,        /* Write the new index key to this register */
   86101   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
   86102 ){
   86103   Vdbe *v = pParse->pVdbe;
   86104   int j;
   86105   Table *pTab = pIdx->pTable;
   86106   int regBase;
   86107   int nCol;
   86108 
   86109   nCol = pIdx->nColumn;
   86110   regBase = sqlite3GetTempRange(pParse, nCol+1);
   86111   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
   86112   for(j=0; j<nCol; j++){
   86113     int idx = pIdx->aiColumn[j];
   86114     if( idx==pTab->iPKey ){
   86115       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
   86116     }else{
   86117       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
   86118       sqlite3ColumnDefault(v, pTab, idx, -1);
   86119     }
   86120   }
   86121   if( doMakeRec ){
   86122     const char *zAff;
   86123     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
   86124       zAff = 0;
   86125     }else{
   86126       zAff = sqlite3IndexAffinityStr(v, pIdx);
   86127     }
   86128     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
   86129     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
   86130   }
   86131   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
   86132   return regBase;
   86133 }
   86134 
   86135 /************** End of delete.c **********************************************/
   86136 /************** Begin file func.c ********************************************/
   86137 /*
   86138 ** 2002 February 23
   86139 **
   86140 ** The author disclaims copyright to this source code.  In place of
   86141 ** a legal notice, here is a blessing:
   86142 **
   86143 **    May you do good and not evil.
   86144 **    May you find forgiveness for yourself and forgive others.
   86145 **    May you share freely, never taking more than you give.
   86146 **
   86147 *************************************************************************
   86148 ** This file contains the C functions that implement various SQL
   86149 ** functions of SQLite.
   86150 **
   86151 ** There is only one exported symbol in this file - the function
   86152 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
   86153 ** All other code has file scope.
   86154 */
   86155 /* #include <stdlib.h> */
   86156 /* #include <assert.h> */
   86157 
   86158 /*
   86159 ** Return the collating function associated with a function.
   86160 */
   86161 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   86162   return context->pColl;
   86163 }
   86164 
   86165 /*
   86166 ** Indicate that the accumulator load should be skipped on this
   86167 ** iteration of the aggregate loop.
   86168 */
   86169 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
   86170   context->skipFlag = 1;
   86171 }
   86172 
   86173 /*
   86174 ** Implementation of the non-aggregate min() and max() functions
   86175 */
   86176 static void minmaxFunc(
   86177   sqlite3_context *context,
   86178   int argc,
   86179   sqlite3_value **argv
   86180 ){
   86181   int i;
   86182   int mask;    /* 0 for min() or 0xffffffff for max() */
   86183   int iBest;
   86184   CollSeq *pColl;
   86185 
   86186   assert( argc>1 );
   86187   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   86188   pColl = sqlite3GetFuncCollSeq(context);
   86189   assert( pColl );
   86190   assert( mask==-1 || mask==0 );
   86191   iBest = 0;
   86192   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   86193   for(i=1; i<argc; i++){
   86194     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   86195     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   86196       testcase( mask==0 );
   86197       iBest = i;
   86198     }
   86199   }
   86200   sqlite3_result_value(context, argv[iBest]);
   86201 }
   86202 
   86203 /*
   86204 ** Return the type of the argument.
   86205 */
   86206 static void typeofFunc(
   86207   sqlite3_context *context,
   86208   int NotUsed,
   86209   sqlite3_value **argv
   86210 ){
   86211   const char *z = 0;
   86212   UNUSED_PARAMETER(NotUsed);
   86213   switch( sqlite3_value_type(argv[0]) ){
   86214     case SQLITE_INTEGER: z = "integer"; break;
   86215     case SQLITE_TEXT:    z = "text";    break;
   86216     case SQLITE_FLOAT:   z = "real";    break;
   86217     case SQLITE_BLOB:    z = "blob";    break;
   86218     default:             z = "null";    break;
   86219   }
   86220   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   86221 }
   86222 
   86223 
   86224 /*
   86225 ** Implementation of the length() function
   86226 */
   86227 static void lengthFunc(
   86228   sqlite3_context *context,
   86229   int argc,
   86230   sqlite3_value **argv
   86231 ){
   86232   int len;
   86233 
   86234   assert( argc==1 );
   86235   UNUSED_PARAMETER(argc);
   86236   switch( sqlite3_value_type(argv[0]) ){
   86237     case SQLITE_BLOB:
   86238     case SQLITE_INTEGER:
   86239     case SQLITE_FLOAT: {
   86240       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   86241       break;
   86242     }
   86243     case SQLITE_TEXT: {
   86244       const unsigned char *z = sqlite3_value_text(argv[0]);
   86245       if( z==0 ) return;
   86246       len = 0;
   86247       while( *z ){
   86248         len++;
   86249         SQLITE_SKIP_UTF8(z);
   86250       }
   86251       sqlite3_result_int(context, len);
   86252       break;
   86253     }
   86254     default: {
   86255       sqlite3_result_null(context);
   86256       break;
   86257     }
   86258   }
   86259 }
   86260 
   86261 /*
   86262 ** Implementation of the abs() function.
   86263 **
   86264 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   86265 ** the numeric argument X.
   86266 */
   86267 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86268   assert( argc==1 );
   86269   UNUSED_PARAMETER(argc);
   86270   switch( sqlite3_value_type(argv[0]) ){
   86271     case SQLITE_INTEGER: {
   86272       i64 iVal = sqlite3_value_int64(argv[0]);
   86273       if( iVal<0 ){
   86274         if( (iVal<<1)==0 ){
   86275           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
   86276           ** abs(X) throws an integer overflow error since there is no
   86277           ** equivalent positive 64-bit two complement value. */
   86278           sqlite3_result_error(context, "integer overflow", -1);
   86279           return;
   86280         }
   86281         iVal = -iVal;
   86282       }
   86283       sqlite3_result_int64(context, iVal);
   86284       break;
   86285     }
   86286     case SQLITE_NULL: {
   86287       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   86288       sqlite3_result_null(context);
   86289       break;
   86290     }
   86291     default: {
   86292       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   86293       ** something that can be converted into a number, we have:
   86294       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   86295       ** cannot be converted to a numeric value.
   86296       */
   86297       double rVal = sqlite3_value_double(argv[0]);
   86298       if( rVal<0 ) rVal = -rVal;
   86299       sqlite3_result_double(context, rVal);
   86300       break;
   86301     }
   86302   }
   86303 }
   86304 
   86305 /*
   86306 ** Implementation of the substr() function.
   86307 **
   86308 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   86309 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   86310 ** of x.  If x is text, then we actually count UTF-8 characters.
   86311 ** If x is a blob, then we count bytes.
   86312 **
   86313 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   86314 **
   86315 ** If p2 is negative, return the p2 characters preceeding p1.
   86316 */
   86317 static void substrFunc(
   86318   sqlite3_context *context,
   86319   int argc,
   86320   sqlite3_value **argv
   86321 ){
   86322   const unsigned char *z;
   86323   const unsigned char *z2;
   86324   int len;
   86325   int p0type;
   86326   i64 p1, p2;
   86327   int negP2 = 0;
   86328 
   86329   assert( argc==3 || argc==2 );
   86330   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   86331    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   86332   ){
   86333     return;
   86334   }
   86335   p0type = sqlite3_value_type(argv[0]);
   86336   p1 = sqlite3_value_int(argv[1]);
   86337   if( p0type==SQLITE_BLOB ){
   86338     len = sqlite3_value_bytes(argv[0]);
   86339     z = sqlite3_value_blob(argv[0]);
   86340     if( z==0 ) return;
   86341     assert( len==sqlite3_value_bytes(argv[0]) );
   86342   }else{
   86343     z = sqlite3_value_text(argv[0]);
   86344     if( z==0 ) return;
   86345     len = 0;
   86346     if( p1<0 ){
   86347       for(z2=z; *z2; len++){
   86348         SQLITE_SKIP_UTF8(z2);
   86349       }
   86350     }
   86351   }
   86352   if( argc==3 ){
   86353     p2 = sqlite3_value_int(argv[2]);
   86354     if( p2<0 ){
   86355       p2 = -p2;
   86356       negP2 = 1;
   86357     }
   86358   }else{
   86359     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   86360   }
   86361   if( p1<0 ){
   86362     p1 += len;
   86363     if( p1<0 ){
   86364       p2 += p1;
   86365       if( p2<0 ) p2 = 0;
   86366       p1 = 0;
   86367     }
   86368   }else if( p1>0 ){
   86369     p1--;
   86370   }else if( p2>0 ){
   86371     p2--;
   86372   }
   86373   if( negP2 ){
   86374     p1 -= p2;
   86375     if( p1<0 ){
   86376       p2 += p1;
   86377       p1 = 0;
   86378     }
   86379   }
   86380   assert( p1>=0 && p2>=0 );
   86381   if( p0type!=SQLITE_BLOB ){
   86382     while( *z && p1 ){
   86383       SQLITE_SKIP_UTF8(z);
   86384       p1--;
   86385     }
   86386     for(z2=z; *z2 && p2; p2--){
   86387       SQLITE_SKIP_UTF8(z2);
   86388     }
   86389     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   86390   }else{
   86391     if( p1+p2>len ){
   86392       p2 = len-p1;
   86393       if( p2<0 ) p2 = 0;
   86394     }
   86395     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   86396   }
   86397 }
   86398 
   86399 /*
   86400 ** Implementation of the round() function
   86401 */
   86402 #ifndef SQLITE_OMIT_FLOATING_POINT
   86403 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86404   int n = 0;
   86405   double r;
   86406   char *zBuf;
   86407   assert( argc==1 || argc==2 );
   86408   if( argc==2 ){
   86409     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   86410     n = sqlite3_value_int(argv[1]);
   86411     if( n>30 ) n = 30;
   86412     if( n<0 ) n = 0;
   86413   }
   86414   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   86415   r = sqlite3_value_double(argv[0]);
   86416   /* If Y==0 and X will fit in a 64-bit int,
   86417   ** handle the rounding directly,
   86418   ** otherwise use printf.
   86419   */
   86420   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   86421     r = (double)((sqlite_int64)(r+0.5));
   86422   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   86423     r = -(double)((sqlite_int64)((-r)+0.5));
   86424   }else{
   86425     zBuf = sqlite3_mprintf("%.*f",n,r);
   86426     if( zBuf==0 ){
   86427       sqlite3_result_error_nomem(context);
   86428       return;
   86429     }
   86430     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   86431     sqlite3_free(zBuf);
   86432   }
   86433   sqlite3_result_double(context, r);
   86434 }
   86435 #endif
   86436 
   86437 /*
   86438 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   86439 ** allocation fails, call sqlite3_result_error_nomem() to notify
   86440 ** the database handle that malloc() has failed and return NULL.
   86441 ** If nByte is larger than the maximum string or blob length, then
   86442 ** raise an SQLITE_TOOBIG exception and return NULL.
   86443 */
   86444 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   86445   char *z;
   86446   sqlite3 *db = sqlite3_context_db_handle(context);
   86447   assert( nByte>0 );
   86448   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   86449   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   86450   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   86451     sqlite3_result_error_toobig(context);
   86452     z = 0;
   86453   }else{
   86454     z = sqlite3Malloc((int)nByte);
   86455     if( !z ){
   86456       sqlite3_result_error_nomem(context);
   86457     }
   86458   }
   86459   return z;
   86460 }
   86461 
   86462 /*
   86463 ** Implementation of the upper() and lower() SQL functions.
   86464 */
   86465 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86466   char *z1;
   86467   const char *z2;
   86468   int i, n;
   86469   UNUSED_PARAMETER(argc);
   86470   z2 = (char*)sqlite3_value_text(argv[0]);
   86471   n = sqlite3_value_bytes(argv[0]);
   86472   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   86473   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   86474   if( z2 ){
   86475     z1 = contextMalloc(context, ((i64)n)+1);
   86476     if( z1 ){
   86477       for(i=0; i<n; i++){
   86478         z1[i] = (char)sqlite3Toupper(z2[i]);
   86479       }
   86480       sqlite3_result_text(context, z1, n, sqlite3_free);
   86481     }
   86482   }
   86483 }
   86484 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86485   char *z1;
   86486   const char *z2;
   86487   int i, n;
   86488   UNUSED_PARAMETER(argc);
   86489   z2 = (char*)sqlite3_value_text(argv[0]);
   86490   n = sqlite3_value_bytes(argv[0]);
   86491   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   86492   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   86493   if( z2 ){
   86494     z1 = contextMalloc(context, ((i64)n)+1);
   86495     if( z1 ){
   86496       for(i=0; i<n; i++){
   86497         z1[i] = sqlite3Tolower(z2[i]);
   86498       }
   86499       sqlite3_result_text(context, z1, n, sqlite3_free);
   86500     }
   86501   }
   86502 }
   86503 
   86504 
   86505 #if 0  /* This function is never used. */
   86506 /*
   86507 ** The COALESCE() and IFNULL() functions used to be implemented as shown
   86508 ** here.  But now they are implemented as VDBE code so that unused arguments
   86509 ** do not have to be computed.  This legacy implementation is retained as
   86510 ** comment.
   86511 */
   86512 /*
   86513 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
   86514 ** All three do the same thing.  They return the first non-NULL
   86515 ** argument.
   86516 */
   86517 static void ifnullFunc(
   86518   sqlite3_context *context,
   86519   int argc,
   86520   sqlite3_value **argv
   86521 ){
   86522   int i;
   86523   for(i=0; i<argc; i++){
   86524     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
   86525       sqlite3_result_value(context, argv[i]);
   86526       break;
   86527     }
   86528   }
   86529 }
   86530 #endif /* NOT USED */
   86531 #define ifnullFunc versionFunc   /* Substitute function - never called */
   86532 
   86533 /*
   86534 ** Implementation of random().  Return a random integer.
   86535 */
   86536 static void randomFunc(
   86537   sqlite3_context *context,
   86538   int NotUsed,
   86539   sqlite3_value **NotUsed2
   86540 ){
   86541   sqlite_int64 r;
   86542   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86543   sqlite3_randomness(sizeof(r), &r);
   86544   if( r<0 ){
   86545     /* We need to prevent a random number of 0x8000000000000000
   86546     ** (or -9223372036854775808) since when you do abs() of that
   86547     ** number of you get the same value back again.  To do this
   86548     ** in a way that is testable, mask the sign bit off of negative
   86549     ** values, resulting in a positive value.  Then take the
   86550     ** 2s complement of that positive value.  The end result can
   86551     ** therefore be no less than -9223372036854775807.
   86552     */
   86553     r = -(r & LARGEST_INT64);
   86554   }
   86555   sqlite3_result_int64(context, r);
   86556 }
   86557 
   86558 /*
   86559 ** Implementation of randomblob(N).  Return a random blob
   86560 ** that is N bytes long.
   86561 */
   86562 static void randomBlob(
   86563   sqlite3_context *context,
   86564   int argc,
   86565   sqlite3_value **argv
   86566 ){
   86567   int n;
   86568   unsigned char *p;
   86569   assert( argc==1 );
   86570   UNUSED_PARAMETER(argc);
   86571   n = sqlite3_value_int(argv[0]);
   86572   if( n<1 ){
   86573     n = 1;
   86574   }
   86575   p = contextMalloc(context, n);
   86576   if( p ){
   86577     sqlite3_randomness(n, p);
   86578     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   86579   }
   86580 }
   86581 
   86582 /*
   86583 ** Implementation of the last_insert_rowid() SQL function.  The return
   86584 ** value is the same as the sqlite3_last_insert_rowid() API function.
   86585 */
   86586 static void last_insert_rowid(
   86587   sqlite3_context *context,
   86588   int NotUsed,
   86589   sqlite3_value **NotUsed2
   86590 ){
   86591   sqlite3 *db = sqlite3_context_db_handle(context);
   86592   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86593   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   86594   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   86595   ** function. */
   86596   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   86597 }
   86598 
   86599 /*
   86600 ** Implementation of the changes() SQL function.
   86601 **
   86602 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   86603 ** around the sqlite3_changes() C/C++ function and hence follows the same
   86604 ** rules for counting changes.
   86605 */
   86606 static void changes(
   86607   sqlite3_context *context,
   86608   int NotUsed,
   86609   sqlite3_value **NotUsed2
   86610 ){
   86611   sqlite3 *db = sqlite3_context_db_handle(context);
   86612   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86613   sqlite3_result_int(context, sqlite3_changes(db));
   86614 }
   86615 
   86616 /*
   86617 ** Implementation of the total_changes() SQL function.  The return value is
   86618 ** the same as the sqlite3_total_changes() API function.
   86619 */
   86620 static void total_changes(
   86621   sqlite3_context *context,
   86622   int NotUsed,
   86623   sqlite3_value **NotUsed2
   86624 ){
   86625   sqlite3 *db = sqlite3_context_db_handle(context);
   86626   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86627   /* IMP: R-52756-41993 This function is a wrapper around the
   86628   ** sqlite3_total_changes() C/C++ interface. */
   86629   sqlite3_result_int(context, sqlite3_total_changes(db));
   86630 }
   86631 
   86632 /*
   86633 ** A structure defining how to do GLOB-style comparisons.
   86634 */
   86635 struct compareInfo {
   86636   u8 matchAll;
   86637   u8 matchOne;
   86638   u8 matchSet;
   86639   u8 noCase;
   86640 };
   86641 
   86642 /*
   86643 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   86644 ** character is exactly one byte in size.  Also, all characters are
   86645 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   86646 ** whereas only characters less than 0x80 do in ASCII.
   86647 */
   86648 #if defined(SQLITE_EBCDIC)
   86649 # define sqlite3Utf8Read(A,C)  (*(A++))
   86650 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
   86651 #else
   86652 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
   86653 #endif
   86654 
   86655 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   86656 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   86657 ** case.  Thus  'a' LIKE 'A' would be true. */
   86658 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   86659 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   86660 ** is case sensitive causing 'a' LIKE 'A' to be false */
   86661 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   86662 
   86663 /*
   86664 ** Compare two UTF-8 strings for equality where the first string can
   86665 ** potentially be a "glob" expression.  Return true (1) if they
   86666 ** are the same and false (0) if they are different.
   86667 **
   86668 ** Globbing rules:
   86669 **
   86670 **      '*'       Matches any sequence of zero or more characters.
   86671 **
   86672 **      '?'       Matches exactly one character.
   86673 **
   86674 **     [...]      Matches one character from the enclosed list of
   86675 **                characters.
   86676 **
   86677 **     [^...]     Matches one character not in the enclosed list.
   86678 **
   86679 ** With the [...] and [^...] matching, a ']' character can be included
   86680 ** in the list by making it the first character after '[' or '^'.  A
   86681 ** range of characters can be specified using '-'.  Example:
   86682 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   86683 ** it the last character in the list.
   86684 **
   86685 ** This routine is usually quick, but can be N**2 in the worst case.
   86686 **
   86687 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   86688 **
   86689 **         abc[*]xyz        Matches "abc*xyz" only
   86690 */
   86691 static int patternCompare(
   86692   const u8 *zPattern,              /* The glob pattern */
   86693   const u8 *zString,               /* The string to compare against the glob */
   86694   const struct compareInfo *pInfo, /* Information about how to do the compare */
   86695   u32 esc                          /* The escape character */
   86696 ){
   86697   u32 c, c2;
   86698   int invert;
   86699   int seen;
   86700   u8 matchOne = pInfo->matchOne;
   86701   u8 matchAll = pInfo->matchAll;
   86702   u8 matchSet = pInfo->matchSet;
   86703   u8 noCase = pInfo->noCase;
   86704   int prevEscape = 0;     /* True if the previous character was 'escape' */
   86705 
   86706   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
   86707     if( !prevEscape && c==matchAll ){
   86708       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
   86709                || c == matchOne ){
   86710         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
   86711           return 0;
   86712         }
   86713       }
   86714       if( c==0 ){
   86715         return 1;
   86716       }else if( c==esc ){
   86717         c = sqlite3Utf8Read(zPattern, &zPattern);
   86718         if( c==0 ){
   86719           return 0;
   86720         }
   86721       }else if( c==matchSet ){
   86722         assert( esc==0 );         /* This is GLOB, not LIKE */
   86723         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   86724         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   86725           SQLITE_SKIP_UTF8(zString);
   86726         }
   86727         return *zString!=0;
   86728       }
   86729       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
   86730         if( noCase ){
   86731           GlogUpperToLower(c2);
   86732           GlogUpperToLower(c);
   86733           while( c2 != 0 && c2 != c ){
   86734             c2 = sqlite3Utf8Read(zString, &zString);
   86735             GlogUpperToLower(c2);
   86736           }
   86737         }else{
   86738           while( c2 != 0 && c2 != c ){
   86739             c2 = sqlite3Utf8Read(zString, &zString);
   86740           }
   86741         }
   86742         if( c2==0 ) return 0;
   86743         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   86744       }
   86745       return 0;
   86746     }else if( !prevEscape && c==matchOne ){
   86747       if( sqlite3Utf8Read(zString, &zString)==0 ){
   86748         return 0;
   86749       }
   86750     }else if( c==matchSet ){
   86751       u32 prior_c = 0;
   86752       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   86753       seen = 0;
   86754       invert = 0;
   86755       c = sqlite3Utf8Read(zString, &zString);
   86756       if( c==0 ) return 0;
   86757       c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86758       if( c2=='^' ){
   86759         invert = 1;
   86760         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86761       }
   86762       if( c2==']' ){
   86763         if( c==']' ) seen = 1;
   86764         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86765       }
   86766       while( c2 && c2!=']' ){
   86767         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   86768           c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86769           if( c>=prior_c && c<=c2 ) seen = 1;
   86770           prior_c = 0;
   86771         }else{
   86772           if( c==c2 ){
   86773             seen = 1;
   86774           }
   86775           prior_c = c2;
   86776         }
   86777         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   86778       }
   86779       if( c2==0 || (seen ^ invert)==0 ){
   86780         return 0;
   86781       }
   86782     }else if( esc==c && !prevEscape ){
   86783       prevEscape = 1;
   86784     }else{
   86785       c2 = sqlite3Utf8Read(zString, &zString);
   86786       if( noCase ){
   86787         GlogUpperToLower(c);
   86788         GlogUpperToLower(c2);
   86789       }
   86790       if( c!=c2 ){
   86791         return 0;
   86792       }
   86793       prevEscape = 0;
   86794     }
   86795   }
   86796   return *zString==0;
   86797 }
   86798 
   86799 /*
   86800 ** Count the number of times that the LIKE operator (or GLOB which is
   86801 ** just a variation of LIKE) gets called.  This is used for testing
   86802 ** only.
   86803 */
   86804 #ifdef SQLITE_TEST
   86805 SQLITE_API int sqlite3_like_count = 0;
   86806 #endif
   86807 
   86808 
   86809 /*
   86810 ** Implementation of the like() SQL function.  This function implements
   86811 ** the build-in LIKE operator.  The first argument to the function is the
   86812 ** pattern and the second argument is the string.  So, the SQL statements:
   86813 **
   86814 **       A LIKE B
   86815 **
   86816 ** is implemented as like(B,A).
   86817 **
   86818 ** This same function (with a different compareInfo structure) computes
   86819 ** the GLOB operator.
   86820 */
   86821 static void likeFunc(
   86822   sqlite3_context *context,
   86823   int argc,
   86824   sqlite3_value **argv
   86825 ){
   86826   const unsigned char *zA, *zB;
   86827   u32 escape = 0;
   86828   int nPat;
   86829   sqlite3 *db = sqlite3_context_db_handle(context);
   86830 
   86831   zB = sqlite3_value_text(argv[0]);
   86832   zA = sqlite3_value_text(argv[1]);
   86833 
   86834   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   86835   ** of deep recursion and N*N behavior in patternCompare().
   86836   */
   86837   nPat = sqlite3_value_bytes(argv[0]);
   86838   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   86839   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   86840   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   86841     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   86842     return;
   86843   }
   86844   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   86845 
   86846   if( argc==3 ){
   86847     /* The escape character string must consist of a single UTF-8 character.
   86848     ** Otherwise, return an error.
   86849     */
   86850     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   86851     if( zEsc==0 ) return;
   86852     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   86853       sqlite3_result_error(context,
   86854           "ESCAPE expression must be a single character", -1);
   86855       return;
   86856     }
   86857     escape = sqlite3Utf8Read(zEsc, &zEsc);
   86858   }
   86859   if( zA && zB ){
   86860     struct compareInfo *pInfo = sqlite3_user_data(context);
   86861 #ifdef SQLITE_TEST
   86862     sqlite3_like_count++;
   86863 #endif
   86864 
   86865     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   86866   }
   86867 }
   86868 
   86869 /*
   86870 ** Implementation of the NULLIF(x,y) function.  The result is the first
   86871 ** argument if the arguments are different.  The result is NULL if the
   86872 ** arguments are equal to each other.
   86873 */
   86874 static void nullifFunc(
   86875   sqlite3_context *context,
   86876   int NotUsed,
   86877   sqlite3_value **argv
   86878 ){
   86879   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   86880   UNUSED_PARAMETER(NotUsed);
   86881   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   86882     sqlite3_result_value(context, argv[0]);
   86883   }
   86884 }
   86885 
   86886 /*
   86887 ** Implementation of the sqlite_version() function.  The result is the version
   86888 ** of the SQLite library that is running.
   86889 */
   86890 static void versionFunc(
   86891   sqlite3_context *context,
   86892   int NotUsed,
   86893   sqlite3_value **NotUsed2
   86894 ){
   86895   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86896   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   86897   ** sqlite3_libversion() C-interface. */
   86898   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   86899 }
   86900 
   86901 /*
   86902 ** Implementation of the sqlite_source_id() function. The result is a string
   86903 ** that identifies the particular version of the source code used to build
   86904 ** SQLite.
   86905 */
   86906 static void sourceidFunc(
   86907   sqlite3_context *context,
   86908   int NotUsed,
   86909   sqlite3_value **NotUsed2
   86910 ){
   86911   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   86912   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   86913   ** sqlite3_sourceid() C interface. */
   86914   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   86915 }
   86916 
   86917 /*
   86918 ** Implementation of the sqlite_log() function.  This is a wrapper around
   86919 ** sqlite3_log().  The return value is NULL.  The function exists purely for
   86920 ** its side-effects.
   86921 */
   86922 static void errlogFunc(
   86923   sqlite3_context *context,
   86924   int argc,
   86925   sqlite3_value **argv
   86926 ){
   86927   UNUSED_PARAMETER(argc);
   86928   UNUSED_PARAMETER(context);
   86929   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
   86930 }
   86931 
   86932 /*
   86933 ** Implementation of the sqlite_compileoption_used() function.
   86934 ** The result is an integer that identifies if the compiler option
   86935 ** was used to build SQLite.
   86936 */
   86937 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   86938 static void compileoptionusedFunc(
   86939   sqlite3_context *context,
   86940   int argc,
   86941   sqlite3_value **argv
   86942 ){
   86943   const char *zOptName;
   86944   assert( argc==1 );
   86945   UNUSED_PARAMETER(argc);
   86946   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   86947   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   86948   ** function.
   86949   */
   86950   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   86951     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   86952   }
   86953 }
   86954 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   86955 
   86956 /*
   86957 ** Implementation of the sqlite_compileoption_get() function.
   86958 ** The result is a string that identifies the compiler options
   86959 ** used to build SQLite.
   86960 */
   86961 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   86962 static void compileoptiongetFunc(
   86963   sqlite3_context *context,
   86964   int argc,
   86965   sqlite3_value **argv
   86966 ){
   86967   int n;
   86968   assert( argc==1 );
   86969   UNUSED_PARAMETER(argc);
   86970   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   86971   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   86972   */
   86973   n = sqlite3_value_int(argv[0]);
   86974   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   86975 }
   86976 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   86977 
   86978 /* Array for converting from half-bytes (nybbles) into ASCII hex
   86979 ** digits. */
   86980 static const char hexdigits[] = {
   86981   '0', '1', '2', '3', '4', '5', '6', '7',
   86982   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   86983 };
   86984 
   86985 /*
   86986 ** EXPERIMENTAL - This is not an official function.  The interface may
   86987 ** change.  This function may disappear.  Do not write code that depends
   86988 ** on this function.
   86989 **
   86990 ** Implementation of the QUOTE() function.  This function takes a single
   86991 ** argument.  If the argument is numeric, the return value is the same as
   86992 ** the argument.  If the argument is NULL, the return value is the string
   86993 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   86994 ** single-quote escapes.
   86995 */
   86996 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   86997   assert( argc==1 );
   86998   UNUSED_PARAMETER(argc);
   86999   switch( sqlite3_value_type(argv[0]) ){
   87000     case SQLITE_INTEGER:
   87001     case SQLITE_FLOAT: {
   87002       sqlite3_result_value(context, argv[0]);
   87003       break;
   87004     }
   87005     case SQLITE_BLOB: {
   87006       char *zText = 0;
   87007       char const *zBlob = sqlite3_value_blob(argv[0]);
   87008       int nBlob = sqlite3_value_bytes(argv[0]);
   87009       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   87010       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   87011       if( zText ){
   87012         int i;
   87013         for(i=0; i<nBlob; i++){
   87014           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   87015           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   87016         }
   87017         zText[(nBlob*2)+2] = '\'';
   87018         zText[(nBlob*2)+3] = '\0';
   87019         zText[0] = 'X';
   87020         zText[1] = '\'';
   87021         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   87022         sqlite3_free(zText);
   87023       }
   87024       break;
   87025     }
   87026     case SQLITE_TEXT: {
   87027       int i,j;
   87028       u64 n;
   87029       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   87030       char *z;
   87031 
   87032       if( zArg==0 ) return;
   87033       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   87034       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   87035       if( z ){
   87036         z[0] = '\'';
   87037         for(i=0, j=1; zArg[i]; i++){
   87038           z[j++] = zArg[i];
   87039           if( zArg[i]=='\'' ){
   87040             z[j++] = '\'';
   87041           }
   87042         }
   87043         z[j++] = '\'';
   87044         z[j] = 0;
   87045         sqlite3_result_text(context, z, j, sqlite3_free);
   87046       }
   87047       break;
   87048     }
   87049     default: {
   87050       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   87051       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   87052       break;
   87053     }
   87054   }
   87055 }
   87056 
   87057 /*
   87058 ** The hex() function.  Interpret the argument as a blob.  Return
   87059 ** a hexadecimal rendering as text.
   87060 */
   87061 static void hexFunc(
   87062   sqlite3_context *context,
   87063   int argc,
   87064   sqlite3_value **argv
   87065 ){
   87066   int i, n;
   87067   const unsigned char *pBlob;
   87068   char *zHex, *z;
   87069   assert( argc==1 );
   87070   UNUSED_PARAMETER(argc);
   87071   pBlob = sqlite3_value_blob(argv[0]);
   87072   n = sqlite3_value_bytes(argv[0]);
   87073   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   87074   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   87075   if( zHex ){
   87076     for(i=0; i<n; i++, pBlob++){
   87077       unsigned char c = *pBlob;
   87078       *(z++) = hexdigits[(c>>4)&0xf];
   87079       *(z++) = hexdigits[c&0xf];
   87080     }
   87081     *z = 0;
   87082     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   87083   }
   87084 }
   87085 
   87086 /*
   87087 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   87088 */
   87089 static void zeroblobFunc(
   87090   sqlite3_context *context,
   87091   int argc,
   87092   sqlite3_value **argv
   87093 ){
   87094   i64 n;
   87095   sqlite3 *db = sqlite3_context_db_handle(context);
   87096   assert( argc==1 );
   87097   UNUSED_PARAMETER(argc);
   87098   n = sqlite3_value_int64(argv[0]);
   87099   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87100   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   87101   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   87102     sqlite3_result_error_toobig(context);
   87103   }else{
   87104     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
   87105   }
   87106 }
   87107 
   87108 /*
   87109 ** The replace() function.  Three arguments are all strings: call
   87110 ** them A, B, and C. The result is also a string which is derived
   87111 ** from A by replacing every occurance of B with C.  The match
   87112 ** must be exact.  Collating sequences are not used.
   87113 */
   87114 static void replaceFunc(
   87115   sqlite3_context *context,
   87116   int argc,
   87117   sqlite3_value **argv
   87118 ){
   87119   const unsigned char *zStr;        /* The input string A */
   87120   const unsigned char *zPattern;    /* The pattern string B */
   87121   const unsigned char *zRep;        /* The replacement string C */
   87122   unsigned char *zOut;              /* The output */
   87123   int nStr;                /* Size of zStr */
   87124   int nPattern;            /* Size of zPattern */
   87125   int nRep;                /* Size of zRep */
   87126   i64 nOut;                /* Maximum size of zOut */
   87127   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   87128   int i, j;                /* Loop counters */
   87129 
   87130   assert( argc==3 );
   87131   UNUSED_PARAMETER(argc);
   87132   zStr = sqlite3_value_text(argv[0]);
   87133   if( zStr==0 ) return;
   87134   nStr = sqlite3_value_bytes(argv[0]);
   87135   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   87136   zPattern = sqlite3_value_text(argv[1]);
   87137   if( zPattern==0 ){
   87138     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   87139             || sqlite3_context_db_handle(context)->mallocFailed );
   87140     return;
   87141   }
   87142   if( zPattern[0]==0 ){
   87143     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   87144     sqlite3_result_value(context, argv[0]);
   87145     return;
   87146   }
   87147   nPattern = sqlite3_value_bytes(argv[1]);
   87148   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   87149   zRep = sqlite3_value_text(argv[2]);
   87150   if( zRep==0 ) return;
   87151   nRep = sqlite3_value_bytes(argv[2]);
   87152   assert( zRep==sqlite3_value_text(argv[2]) );
   87153   nOut = nStr + 1;
   87154   assert( nOut<SQLITE_MAX_LENGTH );
   87155   zOut = contextMalloc(context, (i64)nOut);
   87156   if( zOut==0 ){
   87157     return;
   87158   }
   87159   loopLimit = nStr - nPattern;
   87160   for(i=j=0; i<=loopLimit; i++){
   87161     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   87162       zOut[j++] = zStr[i];
   87163     }else{
   87164       u8 *zOld;
   87165       sqlite3 *db = sqlite3_context_db_handle(context);
   87166       nOut += nRep - nPattern;
   87167       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87168       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   87169       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   87170         sqlite3_result_error_toobig(context);
   87171         sqlite3_free(zOut);
   87172         return;
   87173       }
   87174       zOld = zOut;
   87175       zOut = sqlite3_realloc(zOut, (int)nOut);
   87176       if( zOut==0 ){
   87177         sqlite3_result_error_nomem(context);
   87178         sqlite3_free(zOld);
   87179         return;
   87180       }
   87181       memcpy(&zOut[j], zRep, nRep);
   87182       j += nRep;
   87183       i += nPattern-1;
   87184     }
   87185   }
   87186   assert( j+nStr-i+1==nOut );
   87187   memcpy(&zOut[j], &zStr[i], nStr-i);
   87188   j += nStr - i;
   87189   assert( j<=nOut );
   87190   zOut[j] = 0;
   87191   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   87192 }
   87193 
   87194 /*
   87195 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   87196 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   87197 */
   87198 static void trimFunc(
   87199   sqlite3_context *context,
   87200   int argc,
   87201   sqlite3_value **argv
   87202 ){
   87203   const unsigned char *zIn;         /* Input string */
   87204   const unsigned char *zCharSet;    /* Set of characters to trim */
   87205   int nIn;                          /* Number of bytes in input */
   87206   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   87207   int i;                            /* Loop counter */
   87208   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   87209   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   87210   int nChar;                        /* Number of characters in zCharSet */
   87211 
   87212   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   87213     return;
   87214   }
   87215   zIn = sqlite3_value_text(argv[0]);
   87216   if( zIn==0 ) return;
   87217   nIn = sqlite3_value_bytes(argv[0]);
   87218   assert( zIn==sqlite3_value_text(argv[0]) );
   87219   if( argc==1 ){
   87220     static const unsigned char lenOne[] = { 1 };
   87221     static unsigned char * const azOne[] = { (u8*)" " };
   87222     nChar = 1;
   87223     aLen = (u8*)lenOne;
   87224     azChar = (unsigned char **)azOne;
   87225     zCharSet = 0;
   87226   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   87227     return;
   87228   }else{
   87229     const unsigned char *z;
   87230     for(z=zCharSet, nChar=0; *z; nChar++){
   87231       SQLITE_SKIP_UTF8(z);
   87232     }
   87233     if( nChar>0 ){
   87234       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   87235       if( azChar==0 ){
   87236         return;
   87237       }
   87238       aLen = (unsigned char*)&azChar[nChar];
   87239       for(z=zCharSet, nChar=0; *z; nChar++){
   87240         azChar[nChar] = (unsigned char *)z;
   87241         SQLITE_SKIP_UTF8(z);
   87242         aLen[nChar] = (u8)(z - azChar[nChar]);
   87243       }
   87244     }
   87245   }
   87246   if( nChar>0 ){
   87247     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   87248     if( flags & 1 ){
   87249       while( nIn>0 ){
   87250         int len = 0;
   87251         for(i=0; i<nChar; i++){
   87252           len = aLen[i];
   87253           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   87254         }
   87255         if( i>=nChar ) break;
   87256         zIn += len;
   87257         nIn -= len;
   87258       }
   87259     }
   87260     if( flags & 2 ){
   87261       while( nIn>0 ){
   87262         int len = 0;
   87263         for(i=0; i<nChar; i++){
   87264           len = aLen[i];
   87265           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   87266         }
   87267         if( i>=nChar ) break;
   87268         nIn -= len;
   87269       }
   87270     }
   87271     if( zCharSet ){
   87272       sqlite3_free(azChar);
   87273     }
   87274   }
   87275   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   87276 }
   87277 
   87278 
   87279 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   87280 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   87281 ** when SQLite is built.
   87282 */
   87283 #ifdef SQLITE_SOUNDEX
   87284 /*
   87285 ** Compute the soundex encoding of a word.
   87286 **
   87287 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   87288 ** soundex encoding of the string X.
   87289 */
   87290 static void soundexFunc(
   87291   sqlite3_context *context,
   87292   int argc,
   87293   sqlite3_value **argv
   87294 ){
   87295   char zResult[8];
   87296   const u8 *zIn;
   87297   int i, j;
   87298   static const unsigned char iCode[] = {
   87299     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87300     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87301     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87302     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   87303     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   87304     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   87305     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   87306     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   87307   };
   87308   assert( argc==1 );
   87309   zIn = (u8*)sqlite3_value_text(argv[0]);
   87310   if( zIn==0 ) zIn = (u8*)"";
   87311   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   87312   if( zIn[i] ){
   87313     u8 prevcode = iCode[zIn[i]&0x7f];
   87314     zResult[0] = sqlite3Toupper(zIn[i]);
   87315     for(j=1; j<4 && zIn[i]; i++){
   87316       int code = iCode[zIn[i]&0x7f];
   87317       if( code>0 ){
   87318         if( code!=prevcode ){
   87319           prevcode = code;
   87320           zResult[j++] = code + '0';
   87321         }
   87322       }else{
   87323         prevcode = 0;
   87324       }
   87325     }
   87326     while( j<4 ){
   87327       zResult[j++] = '0';
   87328     }
   87329     zResult[j] = 0;
   87330     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   87331   }else{
   87332     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   87333     ** is NULL or contains no ASCII alphabetic characters. */
   87334     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   87335   }
   87336 }
   87337 #endif /* SQLITE_SOUNDEX */
   87338 
   87339 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   87340 /*
   87341 ** A function that loads a shared-library extension then returns NULL.
   87342 */
   87343 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   87344   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   87345   const char *zProc;
   87346   sqlite3 *db = sqlite3_context_db_handle(context);
   87347   char *zErrMsg = 0;
   87348 
   87349   if( argc==2 ){
   87350     zProc = (const char *)sqlite3_value_text(argv[1]);
   87351   }else{
   87352     zProc = 0;
   87353   }
   87354   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   87355     sqlite3_result_error(context, zErrMsg, -1);
   87356     sqlite3_free(zErrMsg);
   87357   }
   87358 }
   87359 #endif
   87360 
   87361 
   87362 /*
   87363 ** An instance of the following structure holds the context of a
   87364 ** sum() or avg() aggregate computation.
   87365 */
   87366 typedef struct SumCtx SumCtx;
   87367 struct SumCtx {
   87368   double rSum;      /* Floating point sum */
   87369   i64 iSum;         /* Integer sum */
   87370   i64 cnt;          /* Number of elements summed */
   87371   u8 overflow;      /* True if integer overflow seen */
   87372   u8 approx;        /* True if non-integer value was input to the sum */
   87373 };
   87374 
   87375 /*
   87376 ** Routines used to compute the sum, average, and total.
   87377 **
   87378 ** The SUM() function follows the (broken) SQL standard which means
   87379 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   87380 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   87381 ** SUM might return an integer if it never encounters a floating point
   87382 ** value.  TOTAL never fails, but SUM might through an exception if
   87383 ** it overflows an integer.
   87384 */
   87385 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   87386   SumCtx *p;
   87387   int type;
   87388   assert( argc==1 );
   87389   UNUSED_PARAMETER(argc);
   87390   p = sqlite3_aggregate_context(context, sizeof(*p));
   87391   type = sqlite3_value_numeric_type(argv[0]);
   87392   if( p && type!=SQLITE_NULL ){
   87393     p->cnt++;
   87394     if( type==SQLITE_INTEGER ){
   87395       i64 v = sqlite3_value_int64(argv[0]);
   87396       p->rSum += v;
   87397       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
   87398         p->overflow = 1;
   87399       }
   87400     }else{
   87401       p->rSum += sqlite3_value_double(argv[0]);
   87402       p->approx = 1;
   87403     }
   87404   }
   87405 }
   87406 static void sumFinalize(sqlite3_context *context){
   87407   SumCtx *p;
   87408   p = sqlite3_aggregate_context(context, 0);
   87409   if( p && p->cnt>0 ){
   87410     if( p->overflow ){
   87411       sqlite3_result_error(context,"integer overflow",-1);
   87412     }else if( p->approx ){
   87413       sqlite3_result_double(context, p->rSum);
   87414     }else{
   87415       sqlite3_result_int64(context, p->iSum);
   87416     }
   87417   }
   87418 }
   87419 static void avgFinalize(sqlite3_context *context){
   87420   SumCtx *p;
   87421   p = sqlite3_aggregate_context(context, 0);
   87422   if( p && p->cnt>0 ){
   87423     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   87424   }
   87425 }
   87426 static void totalFinalize(sqlite3_context *context){
   87427   SumCtx *p;
   87428   p = sqlite3_aggregate_context(context, 0);
   87429   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   87430   sqlite3_result_double(context, p ? p->rSum : (double)0);
   87431 }
   87432 
   87433 /*
   87434 ** The following structure keeps track of state information for the
   87435 ** count() aggregate function.
   87436 */
   87437 typedef struct CountCtx CountCtx;
   87438 struct CountCtx {
   87439   i64 n;
   87440 };
   87441 
   87442 /*
   87443 ** Routines to implement the count() aggregate function.
   87444 */
   87445 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   87446   CountCtx *p;
   87447   p = sqlite3_aggregate_context(context, sizeof(*p));
   87448   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   87449     p->n++;
   87450   }
   87451 
   87452 #ifndef SQLITE_OMIT_DEPRECATED
   87453   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   87454   ** sure it still operates correctly, verify that its count agrees with our
   87455   ** internal count when using count(*) and when the total count can be
   87456   ** expressed as a 32-bit integer. */
   87457   assert( argc==1 || p==0 || p->n>0x7fffffff
   87458           || p->n==sqlite3_aggregate_count(context) );
   87459 #endif
   87460 }
   87461 static void countFinalize(sqlite3_context *context){
   87462   CountCtx *p;
   87463   p = sqlite3_aggregate_context(context, 0);
   87464   sqlite3_result_int64(context, p ? p->n : 0);
   87465 }
   87466 
   87467 /*
   87468 ** Routines to implement min() and max() aggregate functions.
   87469 */
   87470 static void minmaxStep(
   87471   sqlite3_context *context,
   87472   int NotUsed,
   87473   sqlite3_value **argv
   87474 ){
   87475   Mem *pArg  = (Mem *)argv[0];
   87476   Mem *pBest;
   87477   UNUSED_PARAMETER(NotUsed);
   87478 
   87479   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   87480   if( !pBest ) return;
   87481 
   87482   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   87483     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
   87484   }else if( pBest->flags ){
   87485     int max;
   87486     int cmp;
   87487     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   87488     /* This step function is used for both the min() and max() aggregates,
   87489     ** the only difference between the two being that the sense of the
   87490     ** comparison is inverted. For the max() aggregate, the
   87491     ** sqlite3_user_data() function returns (void *)-1. For min() it
   87492     ** returns (void *)db, where db is the sqlite3* database pointer.
   87493     ** Therefore the next statement sets variable 'max' to 1 for the max()
   87494     ** aggregate, or 0 for min().
   87495     */
   87496     max = sqlite3_user_data(context)!=0;
   87497     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   87498     if( (max && cmp<0) || (!max && cmp>0) ){
   87499       sqlite3VdbeMemCopy(pBest, pArg);
   87500     }else{
   87501       sqlite3SkipAccumulatorLoad(context);
   87502     }
   87503   }else{
   87504     sqlite3VdbeMemCopy(pBest, pArg);
   87505   }
   87506 }
   87507 static void minMaxFinalize(sqlite3_context *context){
   87508   sqlite3_value *pRes;
   87509   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   87510   if( pRes ){
   87511     if( pRes->flags ){
   87512       sqlite3_result_value(context, pRes);
   87513     }
   87514     sqlite3VdbeMemRelease(pRes);
   87515   }
   87516 }
   87517 
   87518 /*
   87519 ** group_concat(EXPR, ?SEPARATOR?)
   87520 */
   87521 static void groupConcatStep(
   87522   sqlite3_context *context,
   87523   int argc,
   87524   sqlite3_value **argv
   87525 ){
   87526   const char *zVal;
   87527   StrAccum *pAccum;
   87528   const char *zSep;
   87529   int nVal, nSep;
   87530   assert( argc==1 || argc==2 );
   87531   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   87532   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   87533 
   87534   if( pAccum ){
   87535     sqlite3 *db = sqlite3_context_db_handle(context);
   87536     int firstTerm = pAccum->useMalloc==0;
   87537     pAccum->useMalloc = 2;
   87538     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   87539     if( !firstTerm ){
   87540       if( argc==2 ){
   87541         zSep = (char*)sqlite3_value_text(argv[1]);
   87542         nSep = sqlite3_value_bytes(argv[1]);
   87543       }else{
   87544         zSep = ",";
   87545         nSep = 1;
   87546       }
   87547       sqlite3StrAccumAppend(pAccum, zSep, nSep);
   87548     }
   87549     zVal = (char*)sqlite3_value_text(argv[0]);
   87550     nVal = sqlite3_value_bytes(argv[0]);
   87551     sqlite3StrAccumAppend(pAccum, zVal, nVal);
   87552   }
   87553 }
   87554 static void groupConcatFinalize(sqlite3_context *context){
   87555   StrAccum *pAccum;
   87556   pAccum = sqlite3_aggregate_context(context, 0);
   87557   if( pAccum ){
   87558     if( pAccum->tooBig ){
   87559       sqlite3_result_error_toobig(context);
   87560     }else if( pAccum->mallocFailed ){
   87561       sqlite3_result_error_nomem(context);
   87562     }else{
   87563       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   87564                           sqlite3_free);
   87565     }
   87566   }
   87567 }
   87568 
   87569 /*
   87570 ** This routine does per-connection function registration.  Most
   87571 ** of the built-in functions above are part of the global function set.
   87572 ** This routine only deals with those that are not global.
   87573 */
   87574 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   87575   int rc = sqlite3_overload_function(db, "MATCH", 2);
   87576   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   87577   if( rc==SQLITE_NOMEM ){
   87578     db->mallocFailed = 1;
   87579   }
   87580 }
   87581 
   87582 /*
   87583 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   87584 */
   87585 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   87586   FuncDef *pDef;
   87587   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   87588                              2, SQLITE_UTF8, 0);
   87589   if( ALWAYS(pDef) ){
   87590     pDef->flags = flagVal;
   87591   }
   87592 }
   87593 
   87594 /*
   87595 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   87596 ** parameter determines whether or not the LIKE operator is case
   87597 ** sensitive.  GLOB is always case sensitive.
   87598 */
   87599 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   87600   struct compareInfo *pInfo;
   87601   if( caseSensitive ){
   87602     pInfo = (struct compareInfo*)&likeInfoAlt;
   87603   }else{
   87604     pInfo = (struct compareInfo*)&likeInfoNorm;
   87605   }
   87606   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   87607   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
   87608   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
   87609       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   87610   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   87611   setLikeOptFlag(db, "like",
   87612       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   87613 }
   87614 
   87615 /*
   87616 ** pExpr points to an expression which implements a function.  If
   87617 ** it is appropriate to apply the LIKE optimization to that function
   87618 ** then set aWc[0] through aWc[2] to the wildcard characters and
   87619 ** return TRUE.  If the function is not a LIKE-style function then
   87620 ** return FALSE.
   87621 */
   87622 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   87623   FuncDef *pDef;
   87624   if( pExpr->op!=TK_FUNCTION
   87625    || !pExpr->x.pList
   87626    || pExpr->x.pList->nExpr!=2
   87627   ){
   87628     return 0;
   87629   }
   87630   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   87631   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   87632                              sqlite3Strlen30(pExpr->u.zToken),
   87633                              2, SQLITE_UTF8, 0);
   87634   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
   87635     return 0;
   87636   }
   87637 
   87638   /* The memcpy() statement assumes that the wildcard characters are
   87639   ** the first three statements in the compareInfo structure.  The
   87640   ** asserts() that follow verify that assumption
   87641   */
   87642   memcpy(aWc, pDef->pUserData, 3);
   87643   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   87644   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   87645   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   87646   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
   87647   return 1;
   87648 }
   87649 
   87650 /*
   87651 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   87652 ** to the global function hash table.  This occurs at start-time (as
   87653 ** a consequence of calling sqlite3_initialize()).
   87654 **
   87655 ** After this routine runs
   87656 */
   87657 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   87658   /*
   87659   ** The following array holds FuncDef structures for all of the functions
   87660   ** defined in this file.
   87661   **
   87662   ** The array cannot be constant since changes are made to the
   87663   ** FuncDef.pHash elements at start-time.  The elements of this array
   87664   ** are read-only after initialization is complete.
   87665   */
   87666   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   87667     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   87668     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   87669     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   87670     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   87671     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   87672     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   87673     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   87674     FUNCTION(min,                0, 0, 1, 0                ),
   87675     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   87676     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   87677     FUNCTION(max,                0, 1, 1, 0                ),
   87678     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   87679     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
   87680     FUNCTION(length,             1, 0, 0, lengthFunc       ),
   87681     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   87682     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   87683     FUNCTION(abs,                1, 0, 0, absFunc          ),
   87684 #ifndef SQLITE_OMIT_FLOATING_POINT
   87685     FUNCTION(round,              1, 0, 0, roundFunc        ),
   87686     FUNCTION(round,              2, 0, 0, roundFunc        ),
   87687 #endif
   87688     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   87689     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   87690     FUNCTION(coalesce,           1, 0, 0, 0                ),
   87691     FUNCTION(coalesce,           0, 0, 0, 0                ),
   87692 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
   87693     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
   87694     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   87695 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
   87696     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
   87697     FUNCTION(random,             0, 0, 0, randomFunc       ),
   87698     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
   87699     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   87700     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   87701     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   87702     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
   87703 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   87704     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   87705     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   87706 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   87707     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   87708     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
   87709     FUNCTION(changes,            0, 0, 0, changes          ),
   87710     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
   87711     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   87712     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   87713   #ifdef SQLITE_SOUNDEX
   87714     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   87715   #endif
   87716   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   87717     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   87718     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   87719   #endif
   87720     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   87721     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   87722     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   87723  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   87724     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
   87725     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   87726     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   87727     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   87728 
   87729     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87730   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   87731     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87732     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   87733   #else
   87734     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   87735     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   87736   #endif
   87737   };
   87738 
   87739   int i;
   87740   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   87741   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   87742 
   87743   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   87744     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   87745   }
   87746   sqlite3RegisterDateTimeFunctions();
   87747 #ifndef SQLITE_OMIT_ALTERTABLE
   87748   sqlite3AlterFunctions();
   87749 #endif
   87750 }
   87751 
   87752 /************** End of func.c ************************************************/
   87753 /************** Begin file fkey.c ********************************************/
   87754 /*
   87755 **
   87756 ** The author disclaims copyright to this source code.  In place of
   87757 ** a legal notice, here is a blessing:
   87758 **
   87759 **    May you do good and not evil.
   87760 **    May you find forgiveness for yourself and forgive others.
   87761 **    May you share freely, never taking more than you give.
   87762 **
   87763 *************************************************************************
   87764 ** This file contains code used by the compiler to add foreign key
   87765 ** support to compiled SQL statements.
   87766 */
   87767 
   87768 #ifndef SQLITE_OMIT_FOREIGN_KEY
   87769 #ifndef SQLITE_OMIT_TRIGGER
   87770 
   87771 /*
   87772 ** Deferred and Immediate FKs
   87773 ** --------------------------
   87774 **
   87775 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   87776 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
   87777 ** is returned and the current statement transaction rolled back. If a
   87778 ** deferred foreign key constraint is violated, no action is taken
   87779 ** immediately. However if the application attempts to commit the
   87780 ** transaction before fixing the constraint violation, the attempt fails.
   87781 **
   87782 ** Deferred constraints are implemented using a simple counter associated
   87783 ** with the database handle. The counter is set to zero each time a
   87784 ** database transaction is opened. Each time a statement is executed
   87785 ** that causes a foreign key violation, the counter is incremented. Each
   87786 ** time a statement is executed that removes an existing violation from
   87787 ** the database, the counter is decremented. When the transaction is
   87788 ** committed, the commit fails if the current value of the counter is
   87789 ** greater than zero. This scheme has two big drawbacks:
   87790 **
   87791 **   * When a commit fails due to a deferred foreign key constraint,
   87792 **     there is no way to tell which foreign constraint is not satisfied,
   87793 **     or which row it is not satisfied for.
   87794 **
   87795 **   * If the database contains foreign key violations when the
   87796 **     transaction is opened, this may cause the mechanism to malfunction.
   87797 **
   87798 ** Despite these problems, this approach is adopted as it seems simpler
   87799 ** than the alternatives.
   87800 **
   87801 ** INSERT operations:
   87802 **
   87803 **   I.1) For each FK for which the table is the child table, search
   87804 **        the parent table for a match. If none is found increment the
   87805 **        constraint counter.
   87806 **
   87807 **   I.2) For each FK for which the table is the parent table,
   87808 **        search the child table for rows that correspond to the new
   87809 **        row in the parent table. Decrement the counter for each row
   87810 **        found (as the constraint is now satisfied).
   87811 **
   87812 ** DELETE operations:
   87813 **
   87814 **   D.1) For each FK for which the table is the child table,
   87815 **        search the parent table for a row that corresponds to the
   87816 **        deleted row in the child table. If such a row is not found,
   87817 **        decrement the counter.
   87818 **
   87819 **   D.2) For each FK for which the table is the parent table, search
   87820 **        the child table for rows that correspond to the deleted row
   87821 **        in the parent table. For each found increment the counter.
   87822 **
   87823 ** UPDATE operations:
   87824 **
   87825 **   An UPDATE command requires that all 4 steps above are taken, but only
   87826 **   for FK constraints for which the affected columns are actually
   87827 **   modified (values must be compared at runtime).
   87828 **
   87829 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   87830 ** This simplifies the implementation a bit.
   87831 **
   87832 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   87833 ** resolution is considered to delete rows before the new row is inserted.
   87834 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   87835 ** is thrown, even if the FK constraint would be satisfied after the new
   87836 ** row is inserted.
   87837 **
   87838 ** Immediate constraints are usually handled similarly. The only difference
   87839 ** is that the counter used is stored as part of each individual statement
   87840 ** object (struct Vdbe). If, after the statement has run, its immediate
   87841 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
   87842 ** and the statement transaction is rolled back. An exception is an INSERT
   87843 ** statement that inserts a single row only (no triggers). In this case,
   87844 ** instead of using a counter, an exception is thrown immediately if the
   87845 ** INSERT violates a foreign key constraint. This is necessary as such
   87846 ** an INSERT does not open a statement transaction.
   87847 **
   87848 ** TODO: How should dropping a table be handled? How should renaming a
   87849 ** table be handled?
   87850 **
   87851 **
   87852 ** Query API Notes
   87853 ** ---------------
   87854 **
   87855 ** Before coding an UPDATE or DELETE row operation, the code-generator
   87856 ** for those two operations needs to know whether or not the operation
   87857 ** requires any FK processing and, if so, which columns of the original
   87858 ** row are required by the FK processing VDBE code (i.e. if FKs were
   87859 ** implemented using triggers, which of the old.* columns would be
   87860 ** accessed). No information is required by the code-generator before
   87861 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   87862 ** generation code to query for this information are:
   87863 **
   87864 **   sqlite3FkRequired() - Test to see if FK processing is required.
   87865 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   87866 **
   87867 **
   87868 ** Externally accessible module functions
   87869 ** --------------------------------------
   87870 **
   87871 **   sqlite3FkCheck()    - Check for foreign key violations.
   87872 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   87873 **   sqlite3FkDelete()   - Delete an FKey structure.
   87874 */
   87875 
   87876 /*
   87877 ** VDBE Calling Convention
   87878 ** -----------------------
   87879 **
   87880 ** Example:
   87881 **
   87882 **   For the following INSERT statement:
   87883 **
   87884 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   87885 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   87886 **
   87887 **   Register (x):        2    (type integer)
   87888 **   Register (x+1):      1    (type integer)
   87889 **   Register (x+2):      NULL (type NULL)
   87890 **   Register (x+3):      3.1  (type real)
   87891 */
   87892 
   87893 /*
   87894 ** A foreign key constraint requires that the key columns in the parent
   87895 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   87896 ** Given that pParent is the parent table for foreign key constraint pFKey,
   87897 ** search the schema a unique index on the parent key columns.
   87898 **
   87899 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   87900 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   87901 ** is set to point to the unique index.
   87902 **
   87903 ** If the parent key consists of a single column (the foreign key constraint
   87904 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   87905 ** Otherwise, it is set to point to an allocated array of size N, where
   87906 ** N is the number of columns in the parent key. The first element of the
   87907 ** array is the index of the child table column that is mapped by the FK
   87908 ** constraint to the parent table column stored in the left-most column
   87909 ** of index *ppIdx. The second element of the array is the index of the
   87910 ** child table column that corresponds to the second left-most column of
   87911 ** *ppIdx, and so on.
   87912 **
   87913 ** If the required index cannot be found, either because:
   87914 **
   87915 **   1) The named parent key columns do not exist, or
   87916 **
   87917 **   2) The named parent key columns do exist, but are not subject to a
   87918 **      UNIQUE or PRIMARY KEY constraint, or
   87919 **
   87920 **   3) No parent key columns were provided explicitly as part of the
   87921 **      foreign key definition, and the parent table does not have a
   87922 **      PRIMARY KEY, or
   87923 **
   87924 **   4) No parent key columns were provided explicitly as part of the
   87925 **      foreign key definition, and the PRIMARY KEY of the parent table
   87926 **      consists of a a different number of columns to the child key in
   87927 **      the child table.
   87928 **
   87929 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   87930 ** into pParse. If an OOM error occurs, non-zero is returned and the
   87931 ** pParse->db->mallocFailed flag is set.
   87932 */
   87933 static int locateFkeyIndex(
   87934   Parse *pParse,                  /* Parse context to store any error in */
   87935   Table *pParent,                 /* Parent table of FK constraint pFKey */
   87936   FKey *pFKey,                    /* Foreign key to find index for */
   87937   Index **ppIdx,                  /* OUT: Unique index on parent table */
   87938   int **paiCol                    /* OUT: Map of index columns in pFKey */
   87939 ){
   87940   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   87941   int *aiCol = 0;                     /* Value to return via *paiCol */
   87942   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   87943   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   87944 
   87945   /* The caller is responsible for zeroing output parameters. */
   87946   assert( ppIdx && *ppIdx==0 );
   87947   assert( !paiCol || *paiCol==0 );
   87948   assert( pParse );
   87949 
   87950   /* If this is a non-composite (single column) foreign key, check if it
   87951   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   87952   ** and *paiCol set to zero and return early.
   87953   **
   87954   ** Otherwise, for a composite foreign key (more than one column), allocate
   87955   ** space for the aiCol array (returned via output parameter *paiCol).
   87956   ** Non-composite foreign keys do not require the aiCol array.
   87957   */
   87958   if( nCol==1 ){
   87959     /* The FK maps to the IPK if any of the following are true:
   87960     **
   87961     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   87962     **      mapped to the primary key of table pParent, or
   87963     **   2) The FK is explicitly mapped to a column declared as INTEGER
   87964     **      PRIMARY KEY.
   87965     */
   87966     if( pParent->iPKey>=0 ){
   87967       if( !zKey ) return 0;
   87968       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   87969     }
   87970   }else if( paiCol ){
   87971     assert( nCol>1 );
   87972     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   87973     if( !aiCol ) return 1;
   87974     *paiCol = aiCol;
   87975   }
   87976 
   87977   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   87978     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
   87979       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   87980       ** of columns. If each indexed column corresponds to a foreign key
   87981       ** column of pFKey, then this index is a winner.  */
   87982 
   87983       if( zKey==0 ){
   87984         /* If zKey is NULL, then this foreign key is implicitly mapped to
   87985         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   87986         ** identified by the test (Index.autoIndex==2).  */
   87987         if( pIdx->autoIndex==2 ){
   87988           if( aiCol ){
   87989             int i;
   87990             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   87991           }
   87992           break;
   87993         }
   87994       }else{
   87995         /* If zKey is non-NULL, then this foreign key was declared to
   87996         ** map to an explicit list of columns in table pParent. Check if this
   87997         ** index matches those columns. Also, check that the index uses
   87998         ** the default collation sequences for each column. */
   87999         int i, j;
   88000         for(i=0; i<nCol; i++){
   88001           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   88002           char *zDfltColl;                  /* Def. collation for column */
   88003           char *zIdxCol;                    /* Name of indexed column */
   88004 
   88005           /* If the index uses a collation sequence that is different from
   88006           ** the default collation sequence for the column, this index is
   88007           ** unusable. Bail out early in this case.  */
   88008           zDfltColl = pParent->aCol[iCol].zColl;
   88009           if( !zDfltColl ){
   88010             zDfltColl = "BINARY";
   88011           }
   88012           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   88013 
   88014           zIdxCol = pParent->aCol[iCol].zName;
   88015           for(j=0; j<nCol; j++){
   88016             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   88017               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   88018               break;
   88019             }
   88020           }
   88021           if( j==nCol ) break;
   88022         }
   88023         if( i==nCol ) break;      /* pIdx is usable */
   88024       }
   88025     }
   88026   }
   88027 
   88028   if( !pIdx ){
   88029     if( !pParse->disableTriggers ){
   88030       sqlite3ErrorMsg(pParse, "foreign key mismatch");
   88031     }
   88032     sqlite3DbFree(pParse->db, aiCol);
   88033     return 1;
   88034   }
   88035 
   88036   *ppIdx = pIdx;
   88037   return 0;
   88038 }
   88039 
   88040 /*
   88041 ** This function is called when a row is inserted into or deleted from the
   88042 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   88043 ** on the child table of pFKey, this function is invoked twice for each row
   88044 ** affected - once to "delete" the old row, and then again to "insert" the
   88045 ** new row.
   88046 **
   88047 ** Each time it is called, this function generates VDBE code to locate the
   88048 ** row in the parent table that corresponds to the row being inserted into
   88049 ** or deleted from the child table. If the parent row can be found, no
   88050 ** special action is taken. Otherwise, if the parent row can *not* be
   88051 ** found in the parent table:
   88052 **
   88053 **   Operation | FK type   | Action taken
   88054 **   --------------------------------------------------------------------------
   88055 **   INSERT      immediate   Increment the "immediate constraint counter".
   88056 **
   88057 **   DELETE      immediate   Decrement the "immediate constraint counter".
   88058 **
   88059 **   INSERT      deferred    Increment the "deferred constraint counter".
   88060 **
   88061 **   DELETE      deferred    Decrement the "deferred constraint counter".
   88062 **
   88063 ** These operations are identified in the comment at the top of this file
   88064 ** (fkey.c) as "I.1" and "D.1".
   88065 */
   88066 static void fkLookupParent(
   88067   Parse *pParse,        /* Parse context */
   88068   int iDb,              /* Index of database housing pTab */
   88069   Table *pTab,          /* Parent table of FK pFKey */
   88070   Index *pIdx,          /* Unique index on parent key columns in pTab */
   88071   FKey *pFKey,          /* Foreign key constraint */
   88072   int *aiCol,           /* Map from parent key columns to child table columns */
   88073   int regData,          /* Address of array containing child table row */
   88074   int nIncr,            /* Increment constraint counter by this */
   88075   int isIgnore          /* If true, pretend pTab contains all NULL values */
   88076 ){
   88077   int i;                                    /* Iterator variable */
   88078   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   88079   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   88080   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   88081 
   88082   /* If nIncr is less than zero, then check at runtime if there are any
   88083   ** outstanding constraints to resolve. If there are not, there is no need
   88084   ** to check if deleting this row resolves any outstanding violations.
   88085   **
   88086   ** Check if any of the key columns in the child table row are NULL. If
   88087   ** any are, then the constraint is considered satisfied. No need to
   88088   ** search for a matching row in the parent table.  */
   88089   if( nIncr<0 ){
   88090     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   88091   }
   88092   for(i=0; i<pFKey->nCol; i++){
   88093     int iReg = aiCol[i] + regData + 1;
   88094     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
   88095   }
   88096 
   88097   if( isIgnore==0 ){
   88098     if( pIdx==0 ){
   88099       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   88100       ** column of the parent table (table pTab).  */
   88101       int iMustBeInt;               /* Address of MustBeInt instruction */
   88102       int regTemp = sqlite3GetTempReg(pParse);
   88103 
   88104       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   88105       ** apply the affinity of the parent key). If this fails, then there
   88106       ** is no matching parent key. Before using MustBeInt, make a copy of
   88107       ** the value. Otherwise, the value inserted into the child key column
   88108       ** will have INTEGER affinity applied to it, which may not be correct.  */
   88109       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   88110       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   88111 
   88112       /* If the parent table is the same as the child table, and we are about
   88113       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   88114       ** then check if the row being inserted matches itself. If so, do not
   88115       ** increment the constraint-counter.  */
   88116       if( pTab==pFKey->pFrom && nIncr==1 ){
   88117         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
   88118       }
   88119 
   88120       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   88121       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
   88122       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   88123       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   88124       sqlite3VdbeJumpHere(v, iMustBeInt);
   88125       sqlite3ReleaseTempReg(pParse, regTemp);
   88126     }else{
   88127       int nCol = pFKey->nCol;
   88128       int regTemp = sqlite3GetTempRange(pParse, nCol);
   88129       int regRec = sqlite3GetTempReg(pParse);
   88130       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   88131 
   88132       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   88133       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
   88134       for(i=0; i<nCol; i++){
   88135         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   88136       }
   88137 
   88138       /* If the parent table is the same as the child table, and we are about
   88139       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   88140       ** then check if the row being inserted matches itself. If so, do not
   88141       ** increment the constraint-counter.
   88142       **
   88143       ** If any of the parent-key values are NULL, then the row cannot match
   88144       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
   88145       ** of the parent-key values are NULL (at this point it is known that
   88146       ** none of the child key values are).
   88147       */
   88148       if( pTab==pFKey->pFrom && nIncr==1 ){
   88149         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   88150         for(i=0; i<nCol; i++){
   88151           int iChild = aiCol[i]+1+regData;
   88152           int iParent = pIdx->aiColumn[i]+1+regData;
   88153           assert( aiCol[i]!=pTab->iPKey );
   88154           if( pIdx->aiColumn[i]==pTab->iPKey ){
   88155             /* The parent key is a composite key that includes the IPK column */
   88156             iParent = regData;
   88157           }
   88158           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
   88159           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   88160         }
   88161         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   88162       }
   88163 
   88164       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
   88165       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
   88166       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
   88167 
   88168       sqlite3ReleaseTempReg(pParse, regRec);
   88169       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   88170     }
   88171   }
   88172 
   88173   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   88174     /* Special case: If this is an INSERT statement that will insert exactly
   88175     ** one row into the table, raise a constraint immediately instead of
   88176     ** incrementing a counter. This is necessary as the VM code is being
   88177     ** generated for will not open a statement transaction.  */
   88178     assert( nIncr==1 );
   88179     sqlite3HaltConstraint(
   88180         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   88181     );
   88182   }else{
   88183     if( nIncr>0 && pFKey->isDeferred==0 ){
   88184       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   88185     }
   88186     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   88187   }
   88188 
   88189   sqlite3VdbeResolveLabel(v, iOk);
   88190   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   88191 }
   88192 
   88193 /*
   88194 ** This function is called to generate code executed when a row is deleted
   88195 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   88196 ** deferred, when a row is inserted into the same table. When generating
   88197 ** code for an SQL UPDATE operation, this function may be called twice -
   88198 ** once to "delete" the old row and once to "insert" the new row.
   88199 **
   88200 ** The code generated by this function scans through the rows in the child
   88201 ** table that correspond to the parent table row being deleted or inserted.
   88202 ** For each child row found, one of the following actions is taken:
   88203 **
   88204 **   Operation | FK type   | Action taken
   88205 **   --------------------------------------------------------------------------
   88206 **   DELETE      immediate   Increment the "immediate constraint counter".
   88207 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   88208 **                           throw a "foreign key constraint failed" exception.
   88209 **
   88210 **   INSERT      immediate   Decrement the "immediate constraint counter".
   88211 **
   88212 **   DELETE      deferred    Increment the "deferred constraint counter".
   88213 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   88214 **                           throw a "foreign key constraint failed" exception.
   88215 **
   88216 **   INSERT      deferred    Decrement the "deferred constraint counter".
   88217 **
   88218 ** These operations are identified in the comment at the top of this file
   88219 ** (fkey.c) as "I.2" and "D.2".
   88220 */
   88221 static void fkScanChildren(
   88222   Parse *pParse,                  /* Parse context */
   88223   SrcList *pSrc,                  /* SrcList containing the table to scan */
   88224   Table *pTab,
   88225   Index *pIdx,                    /* Foreign key index */
   88226   FKey *pFKey,                    /* Foreign key relationship */
   88227   int *aiCol,                     /* Map from pIdx cols to child table cols */
   88228   int regData,                    /* Referenced table data starts here */
   88229   int nIncr                       /* Amount to increment deferred counter by */
   88230 ){
   88231   sqlite3 *db = pParse->db;       /* Database handle */
   88232   int i;                          /* Iterator variable */
   88233   Expr *pWhere = 0;               /* WHERE clause to scan with */
   88234   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   88235   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   88236   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   88237   Vdbe *v = sqlite3GetVdbe(pParse);
   88238 
   88239   assert( !pIdx || pIdx->pTable==pTab );
   88240 
   88241   if( nIncr<0 ){
   88242     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   88243   }
   88244 
   88245   /* Create an Expr object representing an SQL expression like:
   88246   **
   88247   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   88248   **
   88249   ** The collation sequence used for the comparison should be that of
   88250   ** the parent key columns. The affinity of the parent key column should
   88251   ** be applied to each child key value before the comparison takes place.
   88252   */
   88253   for(i=0; i<pFKey->nCol; i++){
   88254     Expr *pLeft;                  /* Value from parent table row */
   88255     Expr *pRight;                 /* Column ref to child table */
   88256     Expr *pEq;                    /* Expression (pLeft = pRight) */
   88257     int iCol;                     /* Index of column in child table */
   88258     const char *zCol;             /* Name of column in child table */
   88259 
   88260     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   88261     if( pLeft ){
   88262       /* Set the collation sequence and affinity of the LHS of each TK_EQ
   88263       ** expression to the parent key column defaults.  */
   88264       if( pIdx ){
   88265         Column *pCol;
   88266         iCol = pIdx->aiColumn[i];
   88267         pCol = &pTab->aCol[iCol];
   88268         if( pTab->iPKey==iCol ) iCol = -1;
   88269         pLeft->iTable = regData+iCol+1;
   88270         pLeft->affinity = pCol->affinity;
   88271         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
   88272       }else{
   88273         pLeft->iTable = regData;
   88274         pLeft->affinity = SQLITE_AFF_INTEGER;
   88275       }
   88276     }
   88277     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   88278     assert( iCol>=0 );
   88279     zCol = pFKey->pFrom->aCol[iCol].zName;
   88280     pRight = sqlite3Expr(db, TK_ID, zCol);
   88281     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   88282     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88283   }
   88284 
   88285   /* If the child table is the same as the parent table, and this scan
   88286   ** is taking place as part of a DELETE operation (operation D.2), omit the
   88287   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
   88288   ** clause, where $rowid is the rowid of the row being deleted.  */
   88289   if( pTab==pFKey->pFrom && nIncr>0 ){
   88290     Expr *pEq;                    /* Expression (pLeft = pRight) */
   88291     Expr *pLeft;                  /* Value from parent table row */
   88292     Expr *pRight;                 /* Column ref to child table */
   88293     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   88294     pRight = sqlite3Expr(db, TK_COLUMN, 0);
   88295     if( pLeft && pRight ){
   88296       pLeft->iTable = regData;
   88297       pLeft->affinity = SQLITE_AFF_INTEGER;
   88298       pRight->iTable = pSrc->a[0].iCursor;
   88299       pRight->iColumn = -1;
   88300     }
   88301     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   88302     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88303   }
   88304 
   88305   /* Resolve the references in the WHERE clause. */
   88306   memset(&sNameContext, 0, sizeof(NameContext));
   88307   sNameContext.pSrcList = pSrc;
   88308   sNameContext.pParse = pParse;
   88309   sqlite3ResolveExprNames(&sNameContext, pWhere);
   88310 
   88311   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   88312   ** clause. If the constraint is not deferred, throw an exception for
   88313   ** each row found. Otherwise, for deferred constraints, increment the
   88314   ** deferred constraint counter by nIncr for each row selected.  */
   88315   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
   88316   if( nIncr>0 && pFKey->isDeferred==0 ){
   88317     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   88318   }
   88319   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   88320   if( pWInfo ){
   88321     sqlite3WhereEnd(pWInfo);
   88322   }
   88323 
   88324   /* Clean up the WHERE clause constructed above. */
   88325   sqlite3ExprDelete(db, pWhere);
   88326   if( iFkIfZero ){
   88327     sqlite3VdbeJumpHere(v, iFkIfZero);
   88328   }
   88329 }
   88330 
   88331 /*
   88332 ** This function returns a pointer to the head of a linked list of FK
   88333 ** constraints for which table pTab is the parent table. For example,
   88334 ** given the following schema:
   88335 **
   88336 **   CREATE TABLE t1(a PRIMARY KEY);
   88337 **   CREATE TABLE t2(b REFERENCES t1(a);
   88338 **
   88339 ** Calling this function with table "t1" as an argument returns a pointer
   88340 ** to the FKey structure representing the foreign key constraint on table
   88341 ** "t2". Calling this function with "t2" as the argument would return a
   88342 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   88343 ** table).
   88344 */
   88345 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   88346   int nName = sqlite3Strlen30(pTab->zName);
   88347   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   88348 }
   88349 
   88350 /*
   88351 ** The second argument is a Trigger structure allocated by the
   88352 ** fkActionTrigger() routine. This function deletes the Trigger structure
   88353 ** and all of its sub-components.
   88354 **
   88355 ** The Trigger structure or any of its sub-components may be allocated from
   88356 ** the lookaside buffer belonging to database handle dbMem.
   88357 */
   88358 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   88359   if( p ){
   88360     TriggerStep *pStep = p->step_list;
   88361     sqlite3ExprDelete(dbMem, pStep->pWhere);
   88362     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   88363     sqlite3SelectDelete(dbMem, pStep->pSelect);
   88364     sqlite3ExprDelete(dbMem, p->pWhen);
   88365     sqlite3DbFree(dbMem, p);
   88366   }
   88367 }
   88368 
   88369 /*
   88370 ** This function is called to generate code that runs when table pTab is
   88371 ** being dropped from the database. The SrcList passed as the second argument
   88372 ** to this function contains a single entry guaranteed to resolve to
   88373 ** table pTab.
   88374 **
   88375 ** Normally, no code is required. However, if either
   88376 **
   88377 **   (a) The table is the parent table of a FK constraint, or
   88378 **   (b) The table is the child table of a deferred FK constraint and it is
   88379 **       determined at runtime that there are outstanding deferred FK
   88380 **       constraint violations in the database,
   88381 **
   88382 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   88383 ** the table from the database. Triggers are disabled while running this
   88384 ** DELETE, but foreign key actions are not.
   88385 */
   88386 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   88387   sqlite3 *db = pParse->db;
   88388   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   88389     int iSkip = 0;
   88390     Vdbe *v = sqlite3GetVdbe(pParse);
   88391 
   88392     assert( v );                  /* VDBE has already been allocated */
   88393     if( sqlite3FkReferences(pTab)==0 ){
   88394       /* Search for a deferred foreign key constraint for which this table
   88395       ** is the child table. If one cannot be found, return without
   88396       ** generating any VDBE code. If one can be found, then jump over
   88397       ** the entire DELETE if there are no outstanding deferred constraints
   88398       ** when this statement is run.  */
   88399       FKey *p;
   88400       for(p=pTab->pFKey; p; p=p->pNextFrom){
   88401         if( p->isDeferred ) break;
   88402       }
   88403       if( !p ) return;
   88404       iSkip = sqlite3VdbeMakeLabel(v);
   88405       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
   88406     }
   88407 
   88408     pParse->disableTriggers = 1;
   88409     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   88410     pParse->disableTriggers = 0;
   88411 
   88412     /* If the DELETE has generated immediate foreign key constraint
   88413     ** violations, halt the VDBE and return an error at this point, before
   88414     ** any modifications to the schema are made. This is because statement
   88415     ** transactions are not able to rollback schema changes.  */
   88416     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   88417     sqlite3HaltConstraint(
   88418         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   88419     );
   88420 
   88421     if( iSkip ){
   88422       sqlite3VdbeResolveLabel(v, iSkip);
   88423     }
   88424   }
   88425 }
   88426 
   88427 /*
   88428 ** This function is called when inserting, deleting or updating a row of
   88429 ** table pTab to generate VDBE code to perform foreign key constraint
   88430 ** processing for the operation.
   88431 **
   88432 ** For a DELETE operation, parameter regOld is passed the index of the
   88433 ** first register in an array of (pTab->nCol+1) registers containing the
   88434 ** rowid of the row being deleted, followed by each of the column values
   88435 ** of the row being deleted, from left to right. Parameter regNew is passed
   88436 ** zero in this case.
   88437 **
   88438 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   88439 ** first register of an array of (pTab->nCol+1) registers containing the new
   88440 ** row data.
   88441 **
   88442 ** For an UPDATE operation, this function is called twice. Once before
   88443 ** the original record is deleted from the table using the calling convention
   88444 ** described for DELETE. Then again after the original record is deleted
   88445 ** but before the new record is inserted using the INSERT convention.
   88446 */
   88447 SQLITE_PRIVATE void sqlite3FkCheck(
   88448   Parse *pParse,                  /* Parse context */
   88449   Table *pTab,                    /* Row is being deleted from this table */
   88450   int regOld,                     /* Previous row data is stored here */
   88451   int regNew                      /* New row data is stored here */
   88452 ){
   88453   sqlite3 *db = pParse->db;       /* Database handle */
   88454   FKey *pFKey;                    /* Used to iterate through FKs */
   88455   int iDb;                        /* Index of database containing pTab */
   88456   const char *zDb;                /* Name of database containing pTab */
   88457   int isIgnoreErrors = pParse->disableTriggers;
   88458 
   88459   /* Exactly one of regOld and regNew should be non-zero. */
   88460   assert( (regOld==0)!=(regNew==0) );
   88461 
   88462   /* If foreign-keys are disabled, this function is a no-op. */
   88463   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   88464 
   88465   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   88466   zDb = db->aDb[iDb].zName;
   88467 
   88468   /* Loop through all the foreign key constraints for which pTab is the
   88469   ** child table (the table that the foreign key definition is part of).  */
   88470   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   88471     Table *pTo;                   /* Parent table of foreign key pFKey */
   88472     Index *pIdx = 0;              /* Index on key columns in pTo */
   88473     int *aiFree = 0;
   88474     int *aiCol;
   88475     int iCol;
   88476     int i;
   88477     int isIgnore = 0;
   88478 
   88479     /* Find the parent table of this foreign key. Also find a unique index
   88480     ** on the parent key columns in the parent table. If either of these
   88481     ** schema items cannot be located, set an error in pParse and return
   88482     ** early.  */
   88483     if( pParse->disableTriggers ){
   88484       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   88485     }else{
   88486       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   88487     }
   88488     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   88489       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
   88490       if( !isIgnoreErrors || db->mallocFailed ) return;
   88491       if( pTo==0 ){
   88492         /* If isIgnoreErrors is true, then a table is being dropped. In this
   88493         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
   88494         ** before actually dropping it in order to check FK constraints.
   88495         ** If the parent table of an FK constraint on the current table is
   88496         ** missing, behave as if it is empty. i.e. decrement the relevant
   88497         ** FK counter for each row of the current table with non-NULL keys.
   88498         */
   88499         Vdbe *v = sqlite3GetVdbe(pParse);
   88500         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   88501         for(i=0; i<pFKey->nCol; i++){
   88502           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   88503           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
   88504         }
   88505         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   88506       }
   88507       continue;
   88508     }
   88509     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   88510 
   88511     if( aiFree ){
   88512       aiCol = aiFree;
   88513     }else{
   88514       iCol = pFKey->aCol[0].iFrom;
   88515       aiCol = &iCol;
   88516     }
   88517     for(i=0; i<pFKey->nCol; i++){
   88518       if( aiCol[i]==pTab->iPKey ){
   88519         aiCol[i] = -1;
   88520       }
   88521 #ifndef SQLITE_OMIT_AUTHORIZATION
   88522       /* Request permission to read the parent key columns. If the
   88523       ** authorization callback returns SQLITE_IGNORE, behave as if any
   88524       ** values read from the parent table are NULL. */
   88525       if( db->xAuth ){
   88526         int rcauth;
   88527         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   88528         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   88529         isIgnore = (rcauth==SQLITE_IGNORE);
   88530       }
   88531 #endif
   88532     }
   88533 
   88534     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   88535     ** a cursor to use to search the unique index on the parent key columns
   88536     ** in the parent table.  */
   88537     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   88538     pParse->nTab++;
   88539 
   88540     if( regOld!=0 ){
   88541       /* A row is being removed from the child table. Search for the parent.
   88542       ** If the parent does not exist, removing the child row resolves an
   88543       ** outstanding foreign key constraint violation. */
   88544       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   88545     }
   88546     if( regNew!=0 ){
   88547       /* A row is being added to the child table. If a parent row cannot
   88548       ** be found, adding the child row has violated the FK constraint. */
   88549       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   88550     }
   88551 
   88552     sqlite3DbFree(db, aiFree);
   88553   }
   88554 
   88555   /* Loop through all the foreign key constraints that refer to this table */
   88556   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   88557     Index *pIdx = 0;              /* Foreign key index for pFKey */
   88558     SrcList *pSrc;
   88559     int *aiCol = 0;
   88560 
   88561     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   88562       assert( regOld==0 && regNew!=0 );
   88563       /* Inserting a single row into a parent table cannot cause an immediate
   88564       ** foreign key violation. So do nothing in this case.  */
   88565       continue;
   88566     }
   88567 
   88568     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   88569       if( !isIgnoreErrors || db->mallocFailed ) return;
   88570       continue;
   88571     }
   88572     assert( aiCol || pFKey->nCol==1 );
   88573 
   88574     /* Create a SrcList structure containing a single table (the table
   88575     ** the foreign key that refers to this table is attached to). This
   88576     ** is required for the sqlite3WhereXXX() interface.  */
   88577     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   88578     if( pSrc ){
   88579       struct SrcList_item *pItem = pSrc->a;
   88580       pItem->pTab = pFKey->pFrom;
   88581       pItem->zName = pFKey->pFrom->zName;
   88582       pItem->pTab->nRef++;
   88583       pItem->iCursor = pParse->nTab++;
   88584 
   88585       if( regNew!=0 ){
   88586         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   88587       }
   88588       if( regOld!=0 ){
   88589         /* If there is a RESTRICT action configured for the current operation
   88590         ** on the parent table of this FK, then throw an exception
   88591         ** immediately if the FK constraint is violated, even if this is a
   88592         ** deferred trigger. That's what RESTRICT means. To defer checking
   88593         ** the constraint, the FK should specify NO ACTION (represented
   88594         ** using OE_None). NO ACTION is the default.  */
   88595         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   88596       }
   88597       pItem->zName = 0;
   88598       sqlite3SrcListDelete(db, pSrc);
   88599     }
   88600     sqlite3DbFree(db, aiCol);
   88601   }
   88602 }
   88603 
   88604 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   88605 
   88606 /*
   88607 ** This function is called before generating code to update or delete a
   88608 ** row contained in table pTab.
   88609 */
   88610 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   88611   Parse *pParse,                  /* Parse context */
   88612   Table *pTab                     /* Table being modified */
   88613 ){
   88614   u32 mask = 0;
   88615   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88616     FKey *p;
   88617     int i;
   88618     for(p=pTab->pFKey; p; p=p->pNextFrom){
   88619       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   88620     }
   88621     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   88622       Index *pIdx = 0;
   88623       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
   88624       if( pIdx ){
   88625         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   88626       }
   88627     }
   88628   }
   88629   return mask;
   88630 }
   88631 
   88632 /*
   88633 ** This function is called before generating code to update or delete a
   88634 ** row contained in table pTab. If the operation is a DELETE, then
   88635 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   88636 ** to an array of size N, where N is the number of columns in table pTab.
   88637 ** If the i'th column is not modified by the UPDATE, then the corresponding
   88638 ** entry in the aChange[] array is set to -1. If the column is modified,
   88639 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   88640 ** UPDATE statement modifies the rowid fields of the table.
   88641 **
   88642 ** If any foreign key processing will be required, this function returns
   88643 ** true. If there is no foreign key related processing, this function
   88644 ** returns false.
   88645 */
   88646 SQLITE_PRIVATE int sqlite3FkRequired(
   88647   Parse *pParse,                  /* Parse context */
   88648   Table *pTab,                    /* Table being modified */
   88649   int *aChange,                   /* Non-NULL for UPDATE operations */
   88650   int chngRowid                   /* True for UPDATE that affects rowid */
   88651 ){
   88652   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88653     if( !aChange ){
   88654       /* A DELETE operation. Foreign key processing is required if the
   88655       ** table in question is either the child or parent table for any
   88656       ** foreign key constraint.  */
   88657       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   88658     }else{
   88659       /* This is an UPDATE. Foreign key processing is only required if the
   88660       ** operation modifies one or more child or parent key columns. */
   88661       int i;
   88662       FKey *p;
   88663 
   88664       /* Check if any child key columns are being modified. */
   88665       for(p=pTab->pFKey; p; p=p->pNextFrom){
   88666         for(i=0; i<p->nCol; i++){
   88667           int iChildKey = p->aCol[i].iFrom;
   88668           if( aChange[iChildKey]>=0 ) return 1;
   88669           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
   88670         }
   88671       }
   88672 
   88673       /* Check if any parent key columns are being modified. */
   88674       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   88675         for(i=0; i<p->nCol; i++){
   88676           char *zKey = p->aCol[i].zCol;
   88677           int iKey;
   88678           for(iKey=0; iKey<pTab->nCol; iKey++){
   88679             Column *pCol = &pTab->aCol[iKey];
   88680             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
   88681               if( aChange[iKey]>=0 ) return 1;
   88682               if( iKey==pTab->iPKey && chngRowid ) return 1;
   88683             }
   88684           }
   88685         }
   88686       }
   88687     }
   88688   }
   88689   return 0;
   88690 }
   88691 
   88692 /*
   88693 ** This function is called when an UPDATE or DELETE operation is being
   88694 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   88695 ** If the current operation is an UPDATE, then the pChanges parameter is
   88696 ** passed a pointer to the list of columns being modified. If it is a
   88697 ** DELETE, pChanges is passed a NULL pointer.
   88698 **
   88699 ** It returns a pointer to a Trigger structure containing a trigger
   88700 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   88701 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   88702 ** returned (these actions require no special handling by the triggers
   88703 ** sub-system, code for them is created by fkScanChildren()).
   88704 **
   88705 ** For example, if pFKey is the foreign key and pTab is table "p" in
   88706 ** the following schema:
   88707 **
   88708 **   CREATE TABLE p(pk PRIMARY KEY);
   88709 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   88710 **
   88711 ** then the returned trigger structure is equivalent to:
   88712 **
   88713 **   CREATE TRIGGER ... DELETE ON p BEGIN
   88714 **     DELETE FROM c WHERE ck = old.pk;
   88715 **   END;
   88716 **
   88717 ** The returned pointer is cached as part of the foreign key object. It
   88718 ** is eventually freed along with the rest of the foreign key object by
   88719 ** sqlite3FkDelete().
   88720 */
   88721 static Trigger *fkActionTrigger(
   88722   Parse *pParse,                  /* Parse context */
   88723   Table *pTab,                    /* Table being updated or deleted from */
   88724   FKey *pFKey,                    /* Foreign key to get action for */
   88725   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   88726 ){
   88727   sqlite3 *db = pParse->db;       /* Database handle */
   88728   int action;                     /* One of OE_None, OE_Cascade etc. */
   88729   Trigger *pTrigger;              /* Trigger definition to return */
   88730   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   88731 
   88732   action = pFKey->aAction[iAction];
   88733   pTrigger = pFKey->apTrigger[iAction];
   88734 
   88735   if( action!=OE_None && !pTrigger ){
   88736     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   88737     char const *zFrom;            /* Name of child table */
   88738     int nFrom;                    /* Length in bytes of zFrom */
   88739     Index *pIdx = 0;              /* Parent key index for this FK */
   88740     int *aiCol = 0;               /* child table cols -> parent key cols */
   88741     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   88742     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   88743     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   88744     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   88745     int i;                        /* Iterator variable */
   88746     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   88747 
   88748     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   88749     assert( aiCol || pFKey->nCol==1 );
   88750 
   88751     for(i=0; i<pFKey->nCol; i++){
   88752       Token tOld = { "old", 3 };  /* Literal "old" token */
   88753       Token tNew = { "new", 3 };  /* Literal "new" token */
   88754       Token tFromCol;             /* Name of column in child table */
   88755       Token tToCol;               /* Name of column in parent table */
   88756       int iFromCol;               /* Idx of column in child table */
   88757       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   88758 
   88759       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   88760       assert( iFromCol>=0 );
   88761       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   88762       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   88763 
   88764       tToCol.n = sqlite3Strlen30(tToCol.z);
   88765       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   88766 
   88767       /* Create the expression "OLD.zToCol = zFromCol". It is important
   88768       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   88769       ** that the affinity and collation sequence associated with the
   88770       ** parent table are used for the comparison. */
   88771       pEq = sqlite3PExpr(pParse, TK_EQ,
   88772           sqlite3PExpr(pParse, TK_DOT,
   88773             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   88774             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   88775           , 0),
   88776           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   88777       , 0);
   88778       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   88779 
   88780       /* For ON UPDATE, construct the next term of the WHEN clause.
   88781       ** The final WHEN clause will be like this:
   88782       **
   88783       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   88784       */
   88785       if( pChanges ){
   88786         pEq = sqlite3PExpr(pParse, TK_IS,
   88787             sqlite3PExpr(pParse, TK_DOT,
   88788               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   88789               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   88790               0),
   88791             sqlite3PExpr(pParse, TK_DOT,
   88792               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   88793               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   88794               0),
   88795             0);
   88796         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   88797       }
   88798 
   88799       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   88800         Expr *pNew;
   88801         if( action==OE_Cascade ){
   88802           pNew = sqlite3PExpr(pParse, TK_DOT,
   88803             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   88804             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   88805           , 0);
   88806         }else if( action==OE_SetDflt ){
   88807           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   88808           if( pDflt ){
   88809             pNew = sqlite3ExprDup(db, pDflt, 0);
   88810           }else{
   88811             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   88812           }
   88813         }else{
   88814           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   88815         }
   88816         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   88817         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   88818       }
   88819     }
   88820     sqlite3DbFree(db, aiCol);
   88821 
   88822     zFrom = pFKey->pFrom->zName;
   88823     nFrom = sqlite3Strlen30(zFrom);
   88824 
   88825     if( action==OE_Restrict ){
   88826       Token tFrom;
   88827       Expr *pRaise;
   88828 
   88829       tFrom.z = zFrom;
   88830       tFrom.n = nFrom;
   88831       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
   88832       if( pRaise ){
   88833         pRaise->affinity = OE_Abort;
   88834       }
   88835       pSelect = sqlite3SelectNew(pParse,
   88836           sqlite3ExprListAppend(pParse, 0, pRaise),
   88837           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   88838           pWhere,
   88839           0, 0, 0, 0, 0, 0
   88840       );
   88841       pWhere = 0;
   88842     }
   88843 
   88844     /* Disable lookaside memory allocation */
   88845     enableLookaside = db->lookaside.bEnabled;
   88846     db->lookaside.bEnabled = 0;
   88847 
   88848     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   88849         sizeof(Trigger) +         /* struct Trigger */
   88850         sizeof(TriggerStep) +     /* Single step in trigger program */
   88851         nFrom + 1                 /* Space for pStep->target.z */
   88852     );
   88853     if( pTrigger ){
   88854       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   88855       pStep->target.z = (char *)&pStep[1];
   88856       pStep->target.n = nFrom;
   88857       memcpy((char *)pStep->target.z, zFrom, nFrom);
   88858 
   88859       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   88860       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   88861       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   88862       if( pWhen ){
   88863         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   88864         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   88865       }
   88866     }
   88867 
   88868     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   88869     db->lookaside.bEnabled = enableLookaside;
   88870 
   88871     sqlite3ExprDelete(db, pWhere);
   88872     sqlite3ExprDelete(db, pWhen);
   88873     sqlite3ExprListDelete(db, pList);
   88874     sqlite3SelectDelete(db, pSelect);
   88875     if( db->mallocFailed==1 ){
   88876       fkTriggerDelete(db, pTrigger);
   88877       return 0;
   88878     }
   88879     assert( pStep!=0 );
   88880 
   88881     switch( action ){
   88882       case OE_Restrict:
   88883         pStep->op = TK_SELECT;
   88884         break;
   88885       case OE_Cascade:
   88886         if( !pChanges ){
   88887           pStep->op = TK_DELETE;
   88888           break;
   88889         }
   88890       default:
   88891         pStep->op = TK_UPDATE;
   88892     }
   88893     pStep->pTrig = pTrigger;
   88894     pTrigger->pSchema = pTab->pSchema;
   88895     pTrigger->pTabSchema = pTab->pSchema;
   88896     pFKey->apTrigger[iAction] = pTrigger;
   88897     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   88898   }
   88899 
   88900   return pTrigger;
   88901 }
   88902 
   88903 /*
   88904 ** This function is called when deleting or updating a row to implement
   88905 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   88906 */
   88907 SQLITE_PRIVATE void sqlite3FkActions(
   88908   Parse *pParse,                  /* Parse context */
   88909   Table *pTab,                    /* Table being updated or deleted from */
   88910   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   88911   int regOld                      /* Address of array containing old row */
   88912 ){
   88913   /* If foreign-key support is enabled, iterate through all FKs that
   88914   ** refer to table pTab. If there is an action associated with the FK
   88915   ** for this operation (either update or delete), invoke the associated
   88916   ** trigger sub-program.  */
   88917   if( pParse->db->flags&SQLITE_ForeignKeys ){
   88918     FKey *pFKey;                  /* Iterator variable */
   88919     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   88920       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   88921       if( pAction ){
   88922         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
   88923       }
   88924     }
   88925   }
   88926 }
   88927 
   88928 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   88929 
   88930 /*
   88931 ** Free all memory associated with foreign key definitions attached to
   88932 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   88933 ** hash table.
   88934 */
   88935 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   88936   FKey *pFKey;                    /* Iterator variable */
   88937   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   88938 
   88939   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
   88940   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   88941 
   88942     /* Remove the FK from the fkeyHash hash table. */
   88943     if( !db || db->pnBytesFreed==0 ){
   88944       if( pFKey->pPrevTo ){
   88945         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   88946       }else{
   88947         void *p = (void *)pFKey->pNextTo;
   88948         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   88949         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
   88950       }
   88951       if( pFKey->pNextTo ){
   88952         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   88953       }
   88954     }
   88955 
   88956     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   88957     ** classified as either immediate or deferred.
   88958     */
   88959     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   88960 
   88961     /* Delete any triggers created to implement actions for this FK. */
   88962 #ifndef SQLITE_OMIT_TRIGGER
   88963     fkTriggerDelete(db, pFKey->apTrigger[0]);
   88964     fkTriggerDelete(db, pFKey->apTrigger[1]);
   88965 #endif
   88966 
   88967     pNext = pFKey->pNextFrom;
   88968     sqlite3DbFree(db, pFKey);
   88969   }
   88970 }
   88971 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   88972 
   88973 /************** End of fkey.c ************************************************/
   88974 /************** Begin file insert.c ******************************************/
   88975 /*
   88976 ** 2001 September 15
   88977 **
   88978 ** The author disclaims copyright to this source code.  In place of
   88979 ** a legal notice, here is a blessing:
   88980 **
   88981 **    May you do good and not evil.
   88982 **    May you find forgiveness for yourself and forgive others.
   88983 **    May you share freely, never taking more than you give.
   88984 **
   88985 *************************************************************************
   88986 ** This file contains C code routines that are called by the parser
   88987 ** to handle INSERT statements in SQLite.
   88988 */
   88989 
   88990 /*
   88991 ** Generate code that will open a table for reading.
   88992 */
   88993 SQLITE_PRIVATE void sqlite3OpenTable(
   88994   Parse *p,       /* Generate code into this VDBE */
   88995   int iCur,       /* The cursor number of the table */
   88996   int iDb,        /* The database index in sqlite3.aDb[] */
   88997   Table *pTab,    /* The table to be opened */
   88998   int opcode      /* OP_OpenRead or OP_OpenWrite */
   88999 ){
   89000   Vdbe *v;
   89001   if( IsVirtual(pTab) ) return;
   89002   v = sqlite3GetVdbe(p);
   89003   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   89004   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
   89005   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
   89006   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
   89007   VdbeComment((v, "%s", pTab->zName));
   89008 }
   89009 
   89010 /*
   89011 ** Return a pointer to the column affinity string associated with index
   89012 ** pIdx. A column affinity string has one character for each column in
   89013 ** the table, according to the affinity of the column:
   89014 **
   89015 **  Character      Column affinity
   89016 **  ------------------------------
   89017 **  'a'            TEXT
   89018 **  'b'            NONE
   89019 **  'c'            NUMERIC
   89020 **  'd'            INTEGER
   89021 **  'e'            REAL
   89022 **
   89023 ** An extra 'd' is appended to the end of the string to cover the
   89024 ** rowid that appears as the last column in every index.
   89025 **
   89026 ** Memory for the buffer containing the column index affinity string
   89027 ** is managed along with the rest of the Index structure. It will be
   89028 ** released when sqlite3DeleteIndex() is called.
   89029 */
   89030 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   89031   if( !pIdx->zColAff ){
   89032     /* The first time a column affinity string for a particular index is
   89033     ** required, it is allocated and populated here. It is then stored as
   89034     ** a member of the Index structure for subsequent use.
   89035     **
   89036     ** The column affinity string will eventually be deleted by
   89037     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   89038     ** up.
   89039     */
   89040     int n;
   89041     Table *pTab = pIdx->pTable;
   89042     sqlite3 *db = sqlite3VdbeDb(v);
   89043     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
   89044     if( !pIdx->zColAff ){
   89045       db->mallocFailed = 1;
   89046       return 0;
   89047     }
   89048     for(n=0; n<pIdx->nColumn; n++){
   89049       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
   89050     }
   89051     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
   89052     pIdx->zColAff[n] = 0;
   89053   }
   89054 
   89055   return pIdx->zColAff;
   89056 }
   89057 
   89058 /*
   89059 ** Set P4 of the most recently inserted opcode to a column affinity
   89060 ** string for table pTab. A column affinity string has one character
   89061 ** for each column indexed by the index, according to the affinity of the
   89062 ** column:
   89063 **
   89064 **  Character      Column affinity
   89065 **  ------------------------------
   89066 **  'a'            TEXT
   89067 **  'b'            NONE
   89068 **  'c'            NUMERIC
   89069 **  'd'            INTEGER
   89070 **  'e'            REAL
   89071 */
   89072 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
   89073   /* The first time a column affinity string for a particular table
   89074   ** is required, it is allocated and populated here. It is then
   89075   ** stored as a member of the Table structure for subsequent use.
   89076   **
   89077   ** The column affinity string will eventually be deleted by
   89078   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
   89079   */
   89080   if( !pTab->zColAff ){
   89081     char *zColAff;
   89082     int i;
   89083     sqlite3 *db = sqlite3VdbeDb(v);
   89084 
   89085     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   89086     if( !zColAff ){
   89087       db->mallocFailed = 1;
   89088       return;
   89089     }
   89090 
   89091     for(i=0; i<pTab->nCol; i++){
   89092       zColAff[i] = pTab->aCol[i].affinity;
   89093     }
   89094     zColAff[pTab->nCol] = '\0';
   89095 
   89096     pTab->zColAff = zColAff;
   89097   }
   89098 
   89099   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
   89100 }
   89101 
   89102 /*
   89103 ** Return non-zero if the table pTab in database iDb or any of its indices
   89104 ** have been opened at any point in the VDBE program beginning at location
   89105 ** iStartAddr throught the end of the program.  This is used to see if
   89106 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   89107 ** run without using temporary table for the results of the SELECT.
   89108 */
   89109 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
   89110   Vdbe *v = sqlite3GetVdbe(p);
   89111   int i;
   89112   int iEnd = sqlite3VdbeCurrentAddr(v);
   89113 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89114   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   89115 #endif
   89116 
   89117   for(i=iStartAddr; i<iEnd; i++){
   89118     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   89119     assert( pOp!=0 );
   89120     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   89121       Index *pIndex;
   89122       int tnum = pOp->p2;
   89123       if( tnum==pTab->tnum ){
   89124         return 1;
   89125       }
   89126       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   89127         if( tnum==pIndex->tnum ){
   89128           return 1;
   89129         }
   89130       }
   89131     }
   89132 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89133     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   89134       assert( pOp->p4.pVtab!=0 );
   89135       assert( pOp->p4type==P4_VTAB );
   89136       return 1;
   89137     }
   89138 #endif
   89139   }
   89140   return 0;
   89141 }
   89142 
   89143 #ifndef SQLITE_OMIT_AUTOINCREMENT
   89144 /*
   89145 ** Locate or create an AutoincInfo structure associated with table pTab
   89146 ** which is in database iDb.  Return the register number for the register
   89147 ** that holds the maximum rowid.
   89148 **
   89149 ** There is at most one AutoincInfo structure per table even if the
   89150 ** same table is autoincremented multiple times due to inserts within
   89151 ** triggers.  A new AutoincInfo structure is created if this is the
   89152 ** first use of table pTab.  On 2nd and subsequent uses, the original
   89153 ** AutoincInfo structure is used.
   89154 **
   89155 ** Three memory locations are allocated:
   89156 **
   89157 **   (1)  Register to hold the name of the pTab table.
   89158 **   (2)  Register to hold the maximum ROWID of pTab.
   89159 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   89160 **
   89161 ** The 2nd register is the one that is returned.  That is all the
   89162 ** insert routine needs to know about.
   89163 */
   89164 static int autoIncBegin(
   89165   Parse *pParse,      /* Parsing context */
   89166   int iDb,            /* Index of the database holding pTab */
   89167   Table *pTab         /* The table we are writing to */
   89168 ){
   89169   int memId = 0;      /* Register holding maximum rowid */
   89170   if( pTab->tabFlags & TF_Autoincrement ){
   89171     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   89172     AutoincInfo *pInfo;
   89173 
   89174     pInfo = pToplevel->pAinc;
   89175     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   89176     if( pInfo==0 ){
   89177       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   89178       if( pInfo==0 ) return 0;
   89179       pInfo->pNext = pToplevel->pAinc;
   89180       pToplevel->pAinc = pInfo;
   89181       pInfo->pTab = pTab;
   89182       pInfo->iDb = iDb;
   89183       pToplevel->nMem++;                  /* Register to hold name of table */
   89184       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   89185       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   89186     }
   89187     memId = pInfo->regCtr;
   89188   }
   89189   return memId;
   89190 }
   89191 
   89192 /*
   89193 ** This routine generates code that will initialize all of the
   89194 ** register used by the autoincrement tracker.
   89195 */
   89196 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   89197   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   89198   sqlite3 *db = pParse->db;  /* The database connection */
   89199   Db *pDb;                   /* Database only autoinc table */
   89200   int memId;                 /* Register holding max rowid */
   89201   int addr;                  /* A VDBE address */
   89202   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   89203 
   89204   /* This routine is never called during trigger-generation.  It is
   89205   ** only called from the top-level */
   89206   assert( pParse->pTriggerTab==0 );
   89207   assert( pParse==sqlite3ParseToplevel(pParse) );
   89208 
   89209   assert( v );   /* We failed long ago if this is not so */
   89210   for(p = pParse->pAinc; p; p = p->pNext){
   89211     pDb = &db->aDb[p->iDb];
   89212     memId = p->regCtr;
   89213     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   89214     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   89215     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   89216     addr = sqlite3VdbeCurrentAddr(v);
   89217     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   89218     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
   89219     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   89220     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
   89221     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   89222     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   89223     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   89224     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   89225     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
   89226     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   89227     sqlite3VdbeAddOp0(v, OP_Close);
   89228   }
   89229 }
   89230 
   89231 /*
   89232 ** Update the maximum rowid for an autoincrement calculation.
   89233 **
   89234 ** This routine should be called when the top of the stack holds a
   89235 ** new rowid that is about to be inserted.  If that new rowid is
   89236 ** larger than the maximum rowid in the memId memory cell, then the
   89237 ** memory cell is updated.  The stack is unchanged.
   89238 */
   89239 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   89240   if( memId>0 ){
   89241     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   89242   }
   89243 }
   89244 
   89245 /*
   89246 ** This routine generates the code needed to write autoincrement
   89247 ** maximum rowid values back into the sqlite_sequence register.
   89248 ** Every statement that might do an INSERT into an autoincrement
   89249 ** table (either directly or through triggers) needs to call this
   89250 ** routine just before the "exit" code.
   89251 */
   89252 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   89253   AutoincInfo *p;
   89254   Vdbe *v = pParse->pVdbe;
   89255   sqlite3 *db = pParse->db;
   89256 
   89257   assert( v );
   89258   for(p = pParse->pAinc; p; p = p->pNext){
   89259     Db *pDb = &db->aDb[p->iDb];
   89260     int j1, j2, j3, j4, j5;
   89261     int iRec;
   89262     int memId = p->regCtr;
   89263 
   89264     iRec = sqlite3GetTempReg(pParse);
   89265     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   89266     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   89267     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
   89268     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
   89269     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
   89270     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
   89271     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
   89272     sqlite3VdbeJumpHere(v, j2);
   89273     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   89274     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
   89275     sqlite3VdbeJumpHere(v, j4);
   89276     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   89277     sqlite3VdbeJumpHere(v, j1);
   89278     sqlite3VdbeJumpHere(v, j5);
   89279     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   89280     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   89281     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   89282     sqlite3VdbeAddOp0(v, OP_Close);
   89283     sqlite3ReleaseTempReg(pParse, iRec);
   89284   }
   89285 }
   89286 #else
   89287 /*
   89288 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   89289 ** above are all no-ops
   89290 */
   89291 # define autoIncBegin(A,B,C) (0)
   89292 # define autoIncStep(A,B,C)
   89293 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   89294 
   89295 
   89296 /* Forward declaration */
   89297 static int xferOptimization(
   89298   Parse *pParse,        /* Parser context */
   89299   Table *pDest,         /* The table we are inserting into */
   89300   Select *pSelect,      /* A SELECT statement to use as the data source */
   89301   int onError,          /* How to handle constraint errors */
   89302   int iDbDest           /* The database of pDest */
   89303 );
   89304 
   89305 /*
   89306 ** This routine is call to handle SQL of the following forms:
   89307 **
   89308 **    insert into TABLE (IDLIST) values(EXPRLIST)
   89309 **    insert into TABLE (IDLIST) select
   89310 **
   89311 ** The IDLIST following the table name is always optional.  If omitted,
   89312 ** then a list of all columns for the table is substituted.  The IDLIST
   89313 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   89314 **
   89315 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   89316 ** statement above, and pSelect is NULL.  For the second form, pList is
   89317 ** NULL and pSelect is a pointer to the select statement used to generate
   89318 ** data for the insert.
   89319 **
   89320 ** The code generated follows one of four templates.  For a simple
   89321 ** select with data coming from a VALUES clause, the code executes
   89322 ** once straight down through.  Pseudo-code follows (we call this
   89323 ** the "1st template"):
   89324 **
   89325 **         open write cursor to <table> and its indices
   89326 **         puts VALUES clause expressions onto the stack
   89327 **         write the resulting record into <table>
   89328 **         cleanup
   89329 **
   89330 ** The three remaining templates assume the statement is of the form
   89331 **
   89332 **   INSERT INTO <table> SELECT ...
   89333 **
   89334 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   89335 ** in other words if the SELECT pulls all columns from a single table
   89336 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   89337 ** if <table2> and <table1> are distinct tables but have identical
   89338 ** schemas, including all the same indices, then a special optimization
   89339 ** is invoked that copies raw records from <table2> over to <table1>.
   89340 ** See the xferOptimization() function for the implementation of this
   89341 ** template.  This is the 2nd template.
   89342 **
   89343 **         open a write cursor to <table>
   89344 **         open read cursor on <table2>
   89345 **         transfer all records in <table2> over to <table>
   89346 **         close cursors
   89347 **         foreach index on <table>
   89348 **           open a write cursor on the <table> index
   89349 **           open a read cursor on the corresponding <table2> index
   89350 **           transfer all records from the read to the write cursors
   89351 **           close cursors
   89352 **         end foreach
   89353 **
   89354 ** The 3rd template is for when the second template does not apply
   89355 ** and the SELECT clause does not read from <table> at any time.
   89356 ** The generated code follows this template:
   89357 **
   89358 **         EOF <- 0
   89359 **         X <- A
   89360 **         goto B
   89361 **      A: setup for the SELECT
   89362 **         loop over the rows in the SELECT
   89363 **           load values into registers R..R+n
   89364 **           yield X
   89365 **         end loop
   89366 **         cleanup after the SELECT
   89367 **         EOF <- 1
   89368 **         yield X
   89369 **         goto A
   89370 **      B: open write cursor to <table> and its indices
   89371 **      C: yield X
   89372 **         if EOF goto D
   89373 **         insert the select result into <table> from R..R+n
   89374 **         goto C
   89375 **      D: cleanup
   89376 **
   89377 ** The 4th template is used if the insert statement takes its
   89378 ** values from a SELECT but the data is being inserted into a table
   89379 ** that is also read as part of the SELECT.  In the third form,
   89380 ** we have to use a intermediate table to store the results of
   89381 ** the select.  The template is like this:
   89382 **
   89383 **         EOF <- 0
   89384 **         X <- A
   89385 **         goto B
   89386 **      A: setup for the SELECT
   89387 **         loop over the tables in the SELECT
   89388 **           load value into register R..R+n
   89389 **           yield X
   89390 **         end loop
   89391 **         cleanup after the SELECT
   89392 **         EOF <- 1
   89393 **         yield X
   89394 **         halt-error
   89395 **      B: open temp table
   89396 **      L: yield X
   89397 **         if EOF goto M
   89398 **         insert row from R..R+n into temp table
   89399 **         goto L
   89400 **      M: open write cursor to <table> and its indices
   89401 **         rewind temp table
   89402 **      C: loop over rows of intermediate table
   89403 **           transfer values form intermediate table into <table>
   89404 **         end loop
   89405 **      D: cleanup
   89406 */
   89407 SQLITE_PRIVATE void sqlite3Insert(
   89408   Parse *pParse,        /* Parser context */
   89409   SrcList *pTabList,    /* Name of table into which we are inserting */
   89410   ExprList *pList,      /* List of values to be inserted */
   89411   Select *pSelect,      /* A SELECT statement to use as the data source */
   89412   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   89413   int onError           /* How to handle constraint errors */
   89414 ){
   89415   sqlite3 *db;          /* The main database structure */
   89416   Table *pTab;          /* The table to insert into.  aka TABLE */
   89417   char *zTab;           /* Name of the table into which we are inserting */
   89418   const char *zDb;      /* Name of the database holding this table */
   89419   int i, j, idx;        /* Loop counters */
   89420   Vdbe *v;              /* Generate code into this virtual machine */
   89421   Index *pIdx;          /* For looping over indices of the table */
   89422   int nColumn;          /* Number of columns in the data */
   89423   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   89424   int baseCur = 0;      /* VDBE Cursor number for pTab */
   89425   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   89426   int endOfLoop;        /* Label for the end of the insertion loop */
   89427   int useTempTable = 0; /* Store SELECT results in intermediate table */
   89428   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   89429   int addrInsTop = 0;   /* Jump to label "D" */
   89430   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   89431   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   89432   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   89433   int iDb;              /* Index of database holding TABLE */
   89434   Db *pDb;              /* The database containing table being inserted into */
   89435   int appendFlag = 0;   /* True if the insert is likely to be an append */
   89436 
   89437   /* Register allocations */
   89438   int regFromSelect = 0;/* Base register for data coming from SELECT */
   89439   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   89440   int regRowCount = 0;  /* Memory cell used for the row counter */
   89441   int regIns;           /* Block of regs holding rowid+data being inserted */
   89442   int regRowid;         /* registers holding insert rowid */
   89443   int regData;          /* register holding first column to insert */
   89444   int regEof = 0;       /* Register recording end of SELECT data */
   89445   int *aRegIdx = 0;     /* One register allocated to each index */
   89446 
   89447 #ifndef SQLITE_OMIT_TRIGGER
   89448   int isView;                 /* True if attempting to insert into a view */
   89449   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   89450   int tmask;                  /* Mask of trigger times */
   89451 #endif
   89452 
   89453   db = pParse->db;
   89454   memset(&dest, 0, sizeof(dest));
   89455   if( pParse->nErr || db->mallocFailed ){
   89456     goto insert_cleanup;
   89457   }
   89458 
   89459   /* Locate the table into which we will be inserting new information.
   89460   */
   89461   assert( pTabList->nSrc==1 );
   89462   zTab = pTabList->a[0].zName;
   89463   if( NEVER(zTab==0) ) goto insert_cleanup;
   89464   pTab = sqlite3SrcListLookup(pParse, pTabList);
   89465   if( pTab==0 ){
   89466     goto insert_cleanup;
   89467   }
   89468   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   89469   assert( iDb<db->nDb );
   89470   pDb = &db->aDb[iDb];
   89471   zDb = pDb->zName;
   89472   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   89473     goto insert_cleanup;
   89474   }
   89475 
   89476   /* Figure out if we have any triggers and if the table being
   89477   ** inserted into is a view
   89478   */
   89479 #ifndef SQLITE_OMIT_TRIGGER
   89480   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   89481   isView = pTab->pSelect!=0;
   89482 #else
   89483 # define pTrigger 0
   89484 # define tmask 0
   89485 # define isView 0
   89486 #endif
   89487 #ifdef SQLITE_OMIT_VIEW
   89488 # undef isView
   89489 # define isView 0
   89490 #endif
   89491   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   89492 
   89493   /* If pTab is really a view, make sure it has been initialized.
   89494   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
   89495   ** module table).
   89496   */
   89497   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   89498     goto insert_cleanup;
   89499   }
   89500 
   89501   /* Ensure that:
   89502   *  (a) the table is not read-only,
   89503   *  (b) that if it is a view then ON INSERT triggers exist
   89504   */
   89505   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   89506     goto insert_cleanup;
   89507   }
   89508 
   89509   /* Allocate a VDBE
   89510   */
   89511   v = sqlite3GetVdbe(pParse);
   89512   if( v==0 ) goto insert_cleanup;
   89513   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   89514   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   89515 
   89516 #ifndef SQLITE_OMIT_XFER_OPT
   89517   /* If the statement is of the form
   89518   **
   89519   **       INSERT INTO <table1> SELECT * FROM <table2>;
   89520   **
   89521   ** Then special optimizations can be applied that make the transfer
   89522   ** very fast and which reduce fragmentation of indices.
   89523   **
   89524   ** This is the 2nd template.
   89525   */
   89526   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   89527     assert( !pTrigger );
   89528     assert( pList==0 );
   89529     goto insert_end;
   89530   }
   89531 #endif /* SQLITE_OMIT_XFER_OPT */
   89532 
   89533   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   89534   ** sqlite_sequence table and store it in memory cell regAutoinc.
   89535   */
   89536   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   89537 
   89538   /* Figure out how many columns of data are supplied.  If the data
   89539   ** is coming from a SELECT statement, then generate a co-routine that
   89540   ** produces a single row of the SELECT on each invocation.  The
   89541   ** co-routine is the common header to the 3rd and 4th templates.
   89542   */
   89543   if( pSelect ){
   89544     /* Data is coming from a SELECT.  Generate code to implement that SELECT
   89545     ** as a co-routine.  The code is common to both the 3rd and 4th
   89546     ** templates:
   89547     **
   89548     **         EOF <- 0
   89549     **         X <- A
   89550     **         goto B
   89551     **      A: setup for the SELECT
   89552     **         loop over the tables in the SELECT
   89553     **           load value into register R..R+n
   89554     **           yield X
   89555     **         end loop
   89556     **         cleanup after the SELECT
   89557     **         EOF <- 1
   89558     **         yield X
   89559     **         halt-error
   89560     **
   89561     ** On each invocation of the co-routine, it puts a single row of the
   89562     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
   89563     ** (These output registers are allocated by sqlite3Select().)  When
   89564     ** the SELECT completes, it sets the EOF flag stored in regEof.
   89565     */
   89566     int rc, j1;
   89567 
   89568     regEof = ++pParse->nMem;
   89569     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
   89570     VdbeComment((v, "SELECT eof flag"));
   89571     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
   89572     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
   89573     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
   89574     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   89575     VdbeComment((v, "Jump over SELECT coroutine"));
   89576 
   89577     /* Resolve the expressions in the SELECT statement and execute it. */
   89578     rc = sqlite3Select(pParse, pSelect, &dest);
   89579     assert( pParse->nErr==0 || rc );
   89580     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
   89581       goto insert_cleanup;
   89582     }
   89583     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
   89584     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
   89585     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
   89586     VdbeComment((v, "End of SELECT coroutine"));
   89587     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
   89588 
   89589     regFromSelect = dest.iMem;
   89590     assert( pSelect->pEList );
   89591     nColumn = pSelect->pEList->nExpr;
   89592     assert( dest.nMem==nColumn );
   89593 
   89594     /* Set useTempTable to TRUE if the result of the SELECT statement
   89595     ** should be written into a temporary table (template 4).  Set to
   89596     ** FALSE if each* row of the SELECT can be written directly into
   89597     ** the destination table (template 3).
   89598     **
   89599     ** A temp table must be used if the table being updated is also one
   89600     ** of the tables being read by the SELECT statement.  Also use a
   89601     ** temp table in the case of row triggers.
   89602     */
   89603     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
   89604       useTempTable = 1;
   89605     }
   89606 
   89607     if( useTempTable ){
   89608       /* Invoke the coroutine to extract information from the SELECT
   89609       ** and add it to a transient table srcTab.  The code generated
   89610       ** here is from the 4th template:
   89611       **
   89612       **      B: open temp table
   89613       **      L: yield X
   89614       **         if EOF goto M
   89615       **         insert row from R..R+n into temp table
   89616       **         goto L
   89617       **      M: ...
   89618       */
   89619       int regRec;          /* Register to hold packed record */
   89620       int regTempRowid;    /* Register to hold temp table ROWID */
   89621       int addrTop;         /* Label "L" */
   89622       int addrIf;          /* Address of jump to M */
   89623 
   89624       srcTab = pParse->nTab++;
   89625       regRec = sqlite3GetTempReg(pParse);
   89626       regTempRowid = sqlite3GetTempReg(pParse);
   89627       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   89628       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   89629       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
   89630       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   89631       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   89632       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   89633       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   89634       sqlite3VdbeJumpHere(v, addrIf);
   89635       sqlite3ReleaseTempReg(pParse, regRec);
   89636       sqlite3ReleaseTempReg(pParse, regTempRowid);
   89637     }
   89638   }else{
   89639     /* This is the case if the data for the INSERT is coming from a VALUES
   89640     ** clause
   89641     */
   89642     NameContext sNC;
   89643     memset(&sNC, 0, sizeof(sNC));
   89644     sNC.pParse = pParse;
   89645     srcTab = -1;
   89646     assert( useTempTable==0 );
   89647     nColumn = pList ? pList->nExpr : 0;
   89648     for(i=0; i<nColumn; i++){
   89649       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   89650         goto insert_cleanup;
   89651       }
   89652     }
   89653   }
   89654 
   89655   /* Make sure the number of columns in the source data matches the number
   89656   ** of columns to be inserted into the table.
   89657   */
   89658   if( IsVirtual(pTab) ){
   89659     for(i=0; i<pTab->nCol; i++){
   89660       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   89661     }
   89662   }
   89663   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   89664     sqlite3ErrorMsg(pParse,
   89665        "table %S has %d columns but %d values were supplied",
   89666        pTabList, 0, pTab->nCol-nHidden, nColumn);
   89667     goto insert_cleanup;
   89668   }
   89669   if( pColumn!=0 && nColumn!=pColumn->nId ){
   89670     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   89671     goto insert_cleanup;
   89672   }
   89673 
   89674   /* If the INSERT statement included an IDLIST term, then make sure
   89675   ** all elements of the IDLIST really are columns of the table and
   89676   ** remember the column indices.
   89677   **
   89678   ** If the table has an INTEGER PRIMARY KEY column and that column
   89679   ** is named in the IDLIST, then record in the keyColumn variable
   89680   ** the index into IDLIST of the primary key column.  keyColumn is
   89681   ** the index of the primary key as it appears in IDLIST, not as
   89682   ** is appears in the original table.  (The index of the primary
   89683   ** key in the original table is pTab->iPKey.)
   89684   */
   89685   if( pColumn ){
   89686     for(i=0; i<pColumn->nId; i++){
   89687       pColumn->a[i].idx = -1;
   89688     }
   89689     for(i=0; i<pColumn->nId; i++){
   89690       for(j=0; j<pTab->nCol; j++){
   89691         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   89692           pColumn->a[i].idx = j;
   89693           if( j==pTab->iPKey ){
   89694             keyColumn = i;
   89695           }
   89696           break;
   89697         }
   89698       }
   89699       if( j>=pTab->nCol ){
   89700         if( sqlite3IsRowid(pColumn->a[i].zName) ){
   89701           keyColumn = i;
   89702         }else{
   89703           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   89704               pTabList, 0, pColumn->a[i].zName);
   89705           pParse->checkSchema = 1;
   89706           goto insert_cleanup;
   89707         }
   89708       }
   89709     }
   89710   }
   89711 
   89712   /* If there is no IDLIST term but the table has an integer primary
   89713   ** key, the set the keyColumn variable to the primary key column index
   89714   ** in the original table definition.
   89715   */
   89716   if( pColumn==0 && nColumn>0 ){
   89717     keyColumn = pTab->iPKey;
   89718   }
   89719 
   89720   /* Initialize the count of rows to be inserted
   89721   */
   89722   if( db->flags & SQLITE_CountRows ){
   89723     regRowCount = ++pParse->nMem;
   89724     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   89725   }
   89726 
   89727   /* If this is not a view, open the table and and all indices */
   89728   if( !isView ){
   89729     int nIdx;
   89730 
   89731     baseCur = pParse->nTab;
   89732     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
   89733     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   89734     if( aRegIdx==0 ){
   89735       goto insert_cleanup;
   89736     }
   89737     for(i=0; i<nIdx; i++){
   89738       aRegIdx[i] = ++pParse->nMem;
   89739     }
   89740   }
   89741 
   89742   /* This is the top of the main insertion loop */
   89743   if( useTempTable ){
   89744     /* This block codes the top of loop only.  The complete loop is the
   89745     ** following pseudocode (template 4):
   89746     **
   89747     **         rewind temp table
   89748     **      C: loop over rows of intermediate table
   89749     **           transfer values form intermediate table into <table>
   89750     **         end loop
   89751     **      D: ...
   89752     */
   89753     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
   89754     addrCont = sqlite3VdbeCurrentAddr(v);
   89755   }else if( pSelect ){
   89756     /* This block codes the top of loop only.  The complete loop is the
   89757     ** following pseudocode (template 3):
   89758     **
   89759     **      C: yield X
   89760     **         if EOF goto D
   89761     **         insert the select result into <table> from R..R+n
   89762     **         goto C
   89763     **      D: ...
   89764     */
   89765     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   89766     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
   89767   }
   89768 
   89769   /* Allocate registers for holding the rowid of the new row,
   89770   ** the content of the new row, and the assemblied row record.
   89771   */
   89772   regRowid = regIns = pParse->nMem+1;
   89773   pParse->nMem += pTab->nCol + 1;
   89774   if( IsVirtual(pTab) ){
   89775     regRowid++;
   89776     pParse->nMem++;
   89777   }
   89778   regData = regRowid+1;
   89779 
   89780   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   89781   */
   89782   endOfLoop = sqlite3VdbeMakeLabel(v);
   89783   if( tmask & TRIGGER_BEFORE ){
   89784     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   89785 
   89786     /* build the NEW.* reference row.  Note that if there is an INTEGER
   89787     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   89788     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   89789     ** we do not know what the unique ID will be (because the insert has
   89790     ** not happened yet) so we substitute a rowid of -1
   89791     */
   89792     if( keyColumn<0 ){
   89793       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   89794     }else{
   89795       int j1;
   89796       if( useTempTable ){
   89797         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
   89798       }else{
   89799         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   89800         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
   89801       }
   89802       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
   89803       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   89804       sqlite3VdbeJumpHere(v, j1);
   89805       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
   89806     }
   89807 
   89808     /* Cannot have triggers on a virtual table. If it were possible,
   89809     ** this block would have to account for hidden column.
   89810     */
   89811     assert( !IsVirtual(pTab) );
   89812 
   89813     /* Create the new column data
   89814     */
   89815     for(i=0; i<pTab->nCol; i++){
   89816       if( pColumn==0 ){
   89817         j = i;
   89818       }else{
   89819         for(j=0; j<pColumn->nId; j++){
   89820           if( pColumn->a[j].idx==i ) break;
   89821         }
   89822       }
   89823       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
   89824         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   89825       }else if( useTempTable ){
   89826         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   89827       }else{
   89828         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   89829         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   89830       }
   89831     }
   89832 
   89833     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   89834     ** do not attempt any conversions before assembling the record.
   89835     ** If this is a real table, attempt conversions as required by the
   89836     ** table column affinities.
   89837     */
   89838     if( !isView ){
   89839       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   89840       sqlite3TableAffinityStr(v, pTab);
   89841     }
   89842 
   89843     /* Fire BEFORE or INSTEAD OF triggers */
   89844     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   89845         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   89846 
   89847     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   89848   }
   89849 
   89850   /* Push the record number for the new entry onto the stack.  The
   89851   ** record number is a randomly generate integer created by NewRowid
   89852   ** except when the table has an INTEGER PRIMARY KEY column, in which
   89853   ** case the record number is the same as that column.
   89854   */
   89855   if( !isView ){
   89856     if( IsVirtual(pTab) ){
   89857       /* The row that the VUpdate opcode will delete: none */
   89858       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   89859     }
   89860     if( keyColumn>=0 ){
   89861       if( useTempTable ){
   89862         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
   89863       }else if( pSelect ){
   89864         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
   89865       }else{
   89866         VdbeOp *pOp;
   89867         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
   89868         pOp = sqlite3VdbeGetOp(v, -1);
   89869         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   89870           appendFlag = 1;
   89871           pOp->opcode = OP_NewRowid;
   89872           pOp->p1 = baseCur;
   89873           pOp->p2 = regRowid;
   89874           pOp->p3 = regAutoinc;
   89875         }
   89876       }
   89877       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   89878       ** to generate a unique primary key value.
   89879       */
   89880       if( !appendFlag ){
   89881         int j1;
   89882         if( !IsVirtual(pTab) ){
   89883           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
   89884           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   89885           sqlite3VdbeJumpHere(v, j1);
   89886         }else{
   89887           j1 = sqlite3VdbeCurrentAddr(v);
   89888           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
   89889         }
   89890         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
   89891       }
   89892     }else if( IsVirtual(pTab) ){
   89893       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   89894     }else{
   89895       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   89896       appendFlag = 1;
   89897     }
   89898     autoIncStep(pParse, regAutoinc, regRowid);
   89899 
   89900     /* Push onto the stack, data for all columns of the new entry, beginning
   89901     ** with the first column.
   89902     */
   89903     nHidden = 0;
   89904     for(i=0; i<pTab->nCol; i++){
   89905       int iRegStore = regRowid+1+i;
   89906       if( i==pTab->iPKey ){
   89907         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   89908         ** Whenever this column is read, the record number will be substituted
   89909         ** in its place.  So will fill this column with a NULL to avoid
   89910         ** taking up data space with information that will never be used. */
   89911         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
   89912         continue;
   89913       }
   89914       if( pColumn==0 ){
   89915         if( IsHiddenColumn(&pTab->aCol[i]) ){
   89916           assert( IsVirtual(pTab) );
   89917           j = -1;
   89918           nHidden++;
   89919         }else{
   89920           j = i - nHidden;
   89921         }
   89922       }else{
   89923         for(j=0; j<pColumn->nId; j++){
   89924           if( pColumn->a[j].idx==i ) break;
   89925         }
   89926       }
   89927       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   89928         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
   89929       }else if( useTempTable ){
   89930         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   89931       }else if( pSelect ){
   89932         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   89933       }else{
   89934         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   89935       }
   89936     }
   89937 
   89938     /* Generate code to check constraints and generate index keys and
   89939     ** do the insertion.
   89940     */
   89941 #ifndef SQLITE_OMIT_VIRTUALTABLE
   89942     if( IsVirtual(pTab) ){
   89943       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   89944       sqlite3VtabMakeWritable(pParse, pTab);
   89945       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   89946       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   89947       sqlite3MayAbort(pParse);
   89948     }else
   89949 #endif
   89950     {
   89951       int isReplace;    /* Set to true if constraints may cause a replace */
   89952       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
   89953           keyColumn>=0, 0, onError, endOfLoop, &isReplace
   89954       );
   89955       sqlite3FkCheck(pParse, pTab, 0, regIns);
   89956       sqlite3CompleteInsertion(
   89957           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
   89958       );
   89959     }
   89960   }
   89961 
   89962   /* Update the count of rows that are inserted
   89963   */
   89964   if( (db->flags & SQLITE_CountRows)!=0 ){
   89965     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   89966   }
   89967 
   89968   if( pTrigger ){
   89969     /* Code AFTER triggers */
   89970     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   89971         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   89972   }
   89973 
   89974   /* The bottom of the main insertion loop, if the data source
   89975   ** is a SELECT statement.
   89976   */
   89977   sqlite3VdbeResolveLabel(v, endOfLoop);
   89978   if( useTempTable ){
   89979     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
   89980     sqlite3VdbeJumpHere(v, addrInsTop);
   89981     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   89982   }else if( pSelect ){
   89983     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   89984     sqlite3VdbeJumpHere(v, addrInsTop);
   89985   }
   89986 
   89987   if( !IsVirtual(pTab) && !isView ){
   89988     /* Close all tables opened */
   89989     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
   89990     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   89991       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
   89992     }
   89993   }
   89994 
   89995 insert_end:
   89996   /* Update the sqlite_sequence table by storing the content of the
   89997   ** maximum rowid counter values recorded while inserting into
   89998   ** autoincrement tables.
   89999   */
   90000   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   90001     sqlite3AutoincrementEnd(pParse);
   90002   }
   90003 
   90004   /*
   90005   ** Return the number of rows inserted. If this routine is
   90006   ** generating code because of a call to sqlite3NestedParse(), do not
   90007   ** invoke the callback function.
   90008   */
   90009   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   90010     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   90011     sqlite3VdbeSetNumCols(v, 1);
   90012     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   90013   }
   90014 
   90015 insert_cleanup:
   90016   sqlite3SrcListDelete(db, pTabList);
   90017   sqlite3ExprListDelete(db, pList);
   90018   sqlite3SelectDelete(db, pSelect);
   90019   sqlite3IdListDelete(db, pColumn);
   90020   sqlite3DbFree(db, aRegIdx);
   90021 }
   90022 
   90023 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   90024 ** thely may interfere with compilation of other functions in this file
   90025 ** (or in another file, if this file becomes part of the amalgamation).  */
   90026 #ifdef isView
   90027  #undef isView
   90028 #endif
   90029 #ifdef pTrigger
   90030  #undef pTrigger
   90031 #endif
   90032 #ifdef tmask
   90033  #undef tmask
   90034 #endif
   90035 
   90036 
   90037 /*
   90038 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
   90039 **
   90040 ** The input is a range of consecutive registers as follows:
   90041 **
   90042 **    1.  The rowid of the row after the update.
   90043 **
   90044 **    2.  The data in the first column of the entry after the update.
   90045 **
   90046 **    i.  Data from middle columns...
   90047 **
   90048 **    N.  The data in the last column of the entry after the update.
   90049 **
   90050 ** The regRowid parameter is the index of the register containing (1).
   90051 **
   90052 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
   90053 ** the address of a register containing the rowid before the update takes
   90054 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
   90055 ** is false, indicating an INSERT statement, then a non-zero rowidChng
   90056 ** indicates that the rowid was explicitly specified as part of the
   90057 ** INSERT statement. If rowidChng is false, it means that  the rowid is
   90058 ** computed automatically in an insert or that the rowid value is not
   90059 ** modified by an update.
   90060 **
   90061 ** The code generated by this routine store new index entries into
   90062 ** registers identified by aRegIdx[].  No index entry is created for
   90063 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   90064 ** the same as the order of indices on the linked list of indices
   90065 ** attached to the table.
   90066 **
   90067 ** This routine also generates code to check constraints.  NOT NULL,
   90068 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   90069 ** then the appropriate action is performed.  There are five possible
   90070 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   90071 **
   90072 **  Constraint type  Action       What Happens
   90073 **  ---------------  ----------   ----------------------------------------
   90074 **  any              ROLLBACK     The current transaction is rolled back and
   90075 **                                sqlite3_exec() returns immediately with a
   90076 **                                return code of SQLITE_CONSTRAINT.
   90077 **
   90078 **  any              ABORT        Back out changes from the current command
   90079 **                                only (do not do a complete rollback) then
   90080 **                                cause sqlite3_exec() to return immediately
   90081 **                                with SQLITE_CONSTRAINT.
   90082 **
   90083 **  any              FAIL         Sqlite3_exec() returns immediately with a
   90084 **                                return code of SQLITE_CONSTRAINT.  The
   90085 **                                transaction is not rolled back and any
   90086 **                                prior changes are retained.
   90087 **
   90088 **  any              IGNORE       The record number and data is popped from
   90089 **                                the stack and there is an immediate jump
   90090 **                                to label ignoreDest.
   90091 **
   90092 **  NOT NULL         REPLACE      The NULL value is replace by the default
   90093 **                                value for that column.  If the default value
   90094 **                                is NULL, the action is the same as ABORT.
   90095 **
   90096 **  UNIQUE           REPLACE      The other row that conflicts with the row
   90097 **                                being inserted is removed.
   90098 **
   90099 **  CHECK            REPLACE      Illegal.  The results in an exception.
   90100 **
   90101 ** Which action to take is determined by the overrideError parameter.
   90102 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   90103 ** is used.  Or if pParse->onError==OE_Default then the onError value
   90104 ** for the constraint is used.
   90105 **
   90106 ** The calling routine must open a read/write cursor for pTab with
   90107 ** cursor number "baseCur".  All indices of pTab must also have open
   90108 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
   90109 ** Except, if there is no possibility of a REPLACE action then
   90110 ** cursors do not need to be open for indices where aRegIdx[i]==0.
   90111 */
   90112 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   90113   Parse *pParse,      /* The parser context */
   90114   Table *pTab,        /* the table into which we are inserting */
   90115   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   90116   int regRowid,       /* Index of the range of input registers */
   90117   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   90118   int rowidChng,      /* True if the rowid might collide with existing entry */
   90119   int isUpdate,       /* True for UPDATE, False for INSERT */
   90120   int overrideError,  /* Override onError to this if not OE_Default */
   90121   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
   90122   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
   90123 ){
   90124   int i;              /* loop counter */
   90125   Vdbe *v;            /* VDBE under constrution */
   90126   int nCol;           /* Number of columns */
   90127   int onError;        /* Conflict resolution strategy */
   90128   int j1;             /* Addresss of jump instruction */
   90129   int j2 = 0, j3;     /* Addresses of jump instructions */
   90130   int regData;        /* Register containing first data column */
   90131   int iCur;           /* Table cursor number */
   90132   Index *pIdx;         /* Pointer to one of the indices */
   90133   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   90134   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
   90135 
   90136   v = sqlite3GetVdbe(pParse);
   90137   assert( v!=0 );
   90138   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   90139   nCol = pTab->nCol;
   90140   regData = regRowid + 1;
   90141 
   90142   /* Test all NOT NULL constraints.
   90143   */
   90144   for(i=0; i<nCol; i++){
   90145     if( i==pTab->iPKey ){
   90146       continue;
   90147     }
   90148     onError = pTab->aCol[i].notNull;
   90149     if( onError==OE_None ) continue;
   90150     if( overrideError!=OE_Default ){
   90151       onError = overrideError;
   90152     }else if( onError==OE_Default ){
   90153       onError = OE_Abort;
   90154     }
   90155     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   90156       onError = OE_Abort;
   90157     }
   90158     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   90159         || onError==OE_Ignore || onError==OE_Replace );
   90160     switch( onError ){
   90161       case OE_Abort:
   90162         sqlite3MayAbort(pParse);
   90163       case OE_Rollback:
   90164       case OE_Fail: {
   90165         char *zMsg;
   90166         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
   90167                                   SQLITE_CONSTRAINT, onError, regData+i);
   90168         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
   90169                               pTab->zName, pTab->aCol[i].zName);
   90170         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
   90171         break;
   90172       }
   90173       case OE_Ignore: {
   90174         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
   90175         break;
   90176       }
   90177       default: {
   90178         assert( onError==OE_Replace );
   90179         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
   90180         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
   90181         sqlite3VdbeJumpHere(v, j1);
   90182         break;
   90183       }
   90184     }
   90185   }
   90186 
   90187   /* Test all CHECK constraints
   90188   */
   90189 #ifndef SQLITE_OMIT_CHECK
   90190   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
   90191     int allOk = sqlite3VdbeMakeLabel(v);
   90192     pParse->ckBase = regData;
   90193     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
   90194     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   90195     if( onError==OE_Ignore ){
   90196       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90197     }else{
   90198       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   90199       sqlite3HaltConstraint(pParse, onError, 0, 0);
   90200     }
   90201     sqlite3VdbeResolveLabel(v, allOk);
   90202   }
   90203 #endif /* !defined(SQLITE_OMIT_CHECK) */
   90204 
   90205   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
   90206   ** of the new record does not previously exist.  Except, if this
   90207   ** is an UPDATE and the primary key is not changing, that is OK.
   90208   */
   90209   if( rowidChng ){
   90210     onError = pTab->keyConf;
   90211     if( overrideError!=OE_Default ){
   90212       onError = overrideError;
   90213     }else if( onError==OE_Default ){
   90214       onError = OE_Abort;
   90215     }
   90216 
   90217     if( isUpdate ){
   90218       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
   90219     }
   90220     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
   90221     switch( onError ){
   90222       default: {
   90223         onError = OE_Abort;
   90224         /* Fall thru into the next case */
   90225       }
   90226       case OE_Rollback:
   90227       case OE_Abort:
   90228       case OE_Fail: {
   90229         sqlite3HaltConstraint(
   90230           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   90231         break;
   90232       }
   90233       case OE_Replace: {
   90234         /* If there are DELETE triggers on this table and the
   90235         ** recursive-triggers flag is set, call GenerateRowDelete() to
   90236         ** remove the conflicting row from the the table. This will fire
   90237         ** the triggers and remove both the table and index b-tree entries.
   90238         **
   90239         ** Otherwise, if there are no triggers or the recursive-triggers
   90240         ** flag is not set, but the table has one or more indexes, call
   90241         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   90242         ** only. The table b-tree entry will be replaced by the new entry
   90243         ** when it is inserted.
   90244         **
   90245         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   90246         ** also invoke MultiWrite() to indicate that this VDBE may require
   90247         ** statement rollback (if the statement is aborted after the delete
   90248         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   90249         ** but being more selective here allows statements like:
   90250         **
   90251         **   REPLACE INTO t(rowid) VALUES($newrowid)
   90252         **
   90253         ** to run without a statement journal if there are no indexes on the
   90254         ** table.
   90255         */
   90256         Trigger *pTrigger = 0;
   90257         if( pParse->db->flags&SQLITE_RecTriggers ){
   90258           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   90259         }
   90260         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   90261           sqlite3MultiWrite(pParse);
   90262           sqlite3GenerateRowDelete(
   90263               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
   90264           );
   90265         }else if( pTab->pIndex ){
   90266           sqlite3MultiWrite(pParse);
   90267           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
   90268         }
   90269         seenReplace = 1;
   90270         break;
   90271       }
   90272       case OE_Ignore: {
   90273         assert( seenReplace==0 );
   90274         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90275         break;
   90276       }
   90277     }
   90278     sqlite3VdbeJumpHere(v, j3);
   90279     if( isUpdate ){
   90280       sqlite3VdbeJumpHere(v, j2);
   90281     }
   90282   }
   90283 
   90284   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   90285   ** index and making sure that duplicate entries do not already exist.
   90286   ** Add the new records to the indices as we go.
   90287   */
   90288   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
   90289     int regIdx;
   90290     int regR;
   90291 
   90292     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
   90293 
   90294     /* Create a key for accessing the index entry */
   90295     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
   90296     for(i=0; i<pIdx->nColumn; i++){
   90297       int idx = pIdx->aiColumn[i];
   90298       if( idx==pTab->iPKey ){
   90299         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   90300       }else{
   90301         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
   90302       }
   90303     }
   90304     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   90305     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
   90306     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
   90307     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
   90308 
   90309     /* Find out what action to take in case there is an indexing conflict */
   90310     onError = pIdx->onError;
   90311     if( onError==OE_None ){
   90312       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   90313       continue;  /* pIdx is not a UNIQUE index */
   90314     }
   90315     if( overrideError!=OE_Default ){
   90316       onError = overrideError;
   90317     }else if( onError==OE_Default ){
   90318       onError = OE_Abort;
   90319     }
   90320     if( seenReplace ){
   90321       if( onError==OE_Ignore ) onError = OE_Replace;
   90322       else if( onError==OE_Fail ) onError = OE_Abort;
   90323     }
   90324 
   90325     /* Check to see if the new index entry will be unique */
   90326     regR = sqlite3GetTempReg(pParse);
   90327     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
   90328     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
   90329                            regR, SQLITE_INT_TO_PTR(regIdx),
   90330                            P4_INT32);
   90331     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   90332 
   90333     /* Generate code that executes if the new index entry is not unique */
   90334     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   90335         || onError==OE_Ignore || onError==OE_Replace );
   90336     switch( onError ){
   90337       case OE_Rollback:
   90338       case OE_Abort:
   90339       case OE_Fail: {
   90340         int j;
   90341         StrAccum errMsg;
   90342         const char *zSep;
   90343         char *zErr;
   90344 
   90345         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   90346         errMsg.db = pParse->db;
   90347         zSep = pIdx->nColumn>1 ? "columns " : "column ";
   90348         for(j=0; j<pIdx->nColumn; j++){
   90349           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   90350           sqlite3StrAccumAppend(&errMsg, zSep, -1);
   90351           zSep = ", ";
   90352           sqlite3StrAccumAppend(&errMsg, zCol, -1);
   90353         }
   90354         sqlite3StrAccumAppend(&errMsg,
   90355             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
   90356         zErr = sqlite3StrAccumFinish(&errMsg);
   90357         sqlite3HaltConstraint(pParse, onError, zErr, 0);
   90358         sqlite3DbFree(errMsg.db, zErr);
   90359         break;
   90360       }
   90361       case OE_Ignore: {
   90362         assert( seenReplace==0 );
   90363         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   90364         break;
   90365       }
   90366       default: {
   90367         Trigger *pTrigger = 0;
   90368         assert( onError==OE_Replace );
   90369         sqlite3MultiWrite(pParse);
   90370         if( pParse->db->flags&SQLITE_RecTriggers ){
   90371           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   90372         }
   90373         sqlite3GenerateRowDelete(
   90374             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
   90375         );
   90376         seenReplace = 1;
   90377         break;
   90378       }
   90379     }
   90380     sqlite3VdbeJumpHere(v, j3);
   90381     sqlite3ReleaseTempReg(pParse, regR);
   90382   }
   90383 
   90384   if( pbMayReplace ){
   90385     *pbMayReplace = seenReplace;
   90386   }
   90387 }
   90388 
   90389 /*
   90390 ** This routine generates code to finish the INSERT or UPDATE operation
   90391 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   90392 ** A consecutive range of registers starting at regRowid contains the
   90393 ** rowid and the content to be inserted.
   90394 **
   90395 ** The arguments to this routine should be the same as the first six
   90396 ** arguments to sqlite3GenerateConstraintChecks.
   90397 */
   90398 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   90399   Parse *pParse,      /* The parser context */
   90400   Table *pTab,        /* the table into which we are inserting */
   90401   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   90402   int regRowid,       /* Range of content */
   90403   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   90404   int isUpdate,       /* True for UPDATE, False for INSERT */
   90405   int appendBias,     /* True if this is likely to be an append */
   90406   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   90407 ){
   90408   int i;
   90409   Vdbe *v;
   90410   int nIdx;
   90411   Index *pIdx;
   90412   u8 pik_flags;
   90413   int regData;
   90414   int regRec;
   90415 
   90416   v = sqlite3GetVdbe(pParse);
   90417   assert( v!=0 );
   90418   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   90419   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   90420   for(i=nIdx-1; i>=0; i--){
   90421     if( aRegIdx[i]==0 ) continue;
   90422     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
   90423     if( useSeekResult ){
   90424       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   90425     }
   90426   }
   90427   regData = regRowid + 1;
   90428   regRec = sqlite3GetTempReg(pParse);
   90429   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   90430   sqlite3TableAffinityStr(v, pTab);
   90431   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   90432   if( pParse->nested ){
   90433     pik_flags = 0;
   90434   }else{
   90435     pik_flags = OPFLAG_NCHANGE;
   90436     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   90437   }
   90438   if( appendBias ){
   90439     pik_flags |= OPFLAG_APPEND;
   90440   }
   90441   if( useSeekResult ){
   90442     pik_flags |= OPFLAG_USESEEKRESULT;
   90443   }
   90444   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
   90445   if( !pParse->nested ){
   90446     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
   90447   }
   90448   sqlite3VdbeChangeP5(v, pik_flags);
   90449 }
   90450 
   90451 /*
   90452 ** Generate code that will open cursors for a table and for all
   90453 ** indices of that table.  The "baseCur" parameter is the cursor number used
   90454 ** for the table.  Indices are opened on subsequent cursors.
   90455 **
   90456 ** Return the number of indices on the table.
   90457 */
   90458 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   90459   Parse *pParse,   /* Parsing context */
   90460   Table *pTab,     /* Table to be opened */
   90461   int baseCur,     /* Cursor number assigned to the table */
   90462   int op           /* OP_OpenRead or OP_OpenWrite */
   90463 ){
   90464   int i;
   90465   int iDb;
   90466   Index *pIdx;
   90467   Vdbe *v;
   90468 
   90469   if( IsVirtual(pTab) ) return 0;
   90470   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   90471   v = sqlite3GetVdbe(pParse);
   90472   assert( v!=0 );
   90473   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
   90474   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   90475     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   90476     assert( pIdx->pSchema==pTab->pSchema );
   90477     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
   90478                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90479     VdbeComment((v, "%s", pIdx->zName));
   90480   }
   90481   if( pParse->nTab<baseCur+i ){
   90482     pParse->nTab = baseCur+i;
   90483   }
   90484   return i-1;
   90485 }
   90486 
   90487 
   90488 #ifdef SQLITE_TEST
   90489 /*
   90490 ** The following global variable is incremented whenever the
   90491 ** transfer optimization is used.  This is used for testing
   90492 ** purposes only - to make sure the transfer optimization really
   90493 ** is happening when it is suppose to.
   90494 */
   90495 SQLITE_API int sqlite3_xferopt_count;
   90496 #endif /* SQLITE_TEST */
   90497 
   90498 
   90499 #ifndef SQLITE_OMIT_XFER_OPT
   90500 /*
   90501 ** Check to collation names to see if they are compatible.
   90502 */
   90503 static int xferCompatibleCollation(const char *z1, const char *z2){
   90504   if( z1==0 ){
   90505     return z2==0;
   90506   }
   90507   if( z2==0 ){
   90508     return 0;
   90509   }
   90510   return sqlite3StrICmp(z1, z2)==0;
   90511 }
   90512 
   90513 
   90514 /*
   90515 ** Check to see if index pSrc is compatible as a source of data
   90516 ** for index pDest in an insert transfer optimization.  The rules
   90517 ** for a compatible index:
   90518 **
   90519 **    *   The index is over the same set of columns
   90520 **    *   The same DESC and ASC markings occurs on all columns
   90521 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   90522 **    *   The same collating sequence on each column
   90523 */
   90524 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   90525   int i;
   90526   assert( pDest && pSrc );
   90527   assert( pDest->pTable!=pSrc->pTable );
   90528   if( pDest->nColumn!=pSrc->nColumn ){
   90529     return 0;   /* Different number of columns */
   90530   }
   90531   if( pDest->onError!=pSrc->onError ){
   90532     return 0;   /* Different conflict resolution strategies */
   90533   }
   90534   for(i=0; i<pSrc->nColumn; i++){
   90535     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   90536       return 0;   /* Different columns indexed */
   90537     }
   90538     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   90539       return 0;   /* Different sort orders */
   90540     }
   90541     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   90542       return 0;   /* Different collating sequences */
   90543     }
   90544   }
   90545 
   90546   /* If no test above fails then the indices must be compatible */
   90547   return 1;
   90548 }
   90549 
   90550 /*
   90551 ** Attempt the transfer optimization on INSERTs of the form
   90552 **
   90553 **     INSERT INTO tab1 SELECT * FROM tab2;
   90554 **
   90555 ** The xfer optimization transfers raw records from tab2 over to tab1.
   90556 ** Columns are not decoded and reassemblied, which greatly improves
   90557 ** performance.  Raw index records are transferred in the same way.
   90558 **
   90559 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
   90560 ** There are lots of rules for determining compatibility - see comments
   90561 ** embedded in the code for details.
   90562 **
   90563 ** This routine returns TRUE if the optimization is guaranteed to be used.
   90564 ** Sometimes the xfer optimization will only work if the destination table
   90565 ** is empty - a factor that can only be determined at run-time.  In that
   90566 ** case, this routine generates code for the xfer optimization but also
   90567 ** does a test to see if the destination table is empty and jumps over the
   90568 ** xfer optimization code if the test fails.  In that case, this routine
   90569 ** returns FALSE so that the caller will know to go ahead and generate
   90570 ** an unoptimized transfer.  This routine also returns FALSE if there
   90571 ** is no chance that the xfer optimization can be applied.
   90572 **
   90573 ** This optimization is particularly useful at making VACUUM run faster.
   90574 */
   90575 static int xferOptimization(
   90576   Parse *pParse,        /* Parser context */
   90577   Table *pDest,         /* The table we are inserting into */
   90578   Select *pSelect,      /* A SELECT statement to use as the data source */
   90579   int onError,          /* How to handle constraint errors */
   90580   int iDbDest           /* The database of pDest */
   90581 ){
   90582   ExprList *pEList;                /* The result set of the SELECT */
   90583   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   90584   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   90585   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   90586   int i;                           /* Loop counter */
   90587   int iDbSrc;                      /* The database of pSrc */
   90588   int iSrc, iDest;                 /* Cursors from source and destination */
   90589   int addr1, addr2;                /* Loop addresses */
   90590   int emptyDestTest;               /* Address of test for empty pDest */
   90591   int emptySrcTest;                /* Address of test for empty pSrc */
   90592   Vdbe *v;                         /* The VDBE we are building */
   90593   KeyInfo *pKey;                   /* Key information for an index */
   90594   int regAutoinc;                  /* Memory register used by AUTOINC */
   90595   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   90596   int regData, regRowid;           /* Registers holding data and rowid */
   90597 
   90598   if( pSelect==0 ){
   90599     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   90600   }
   90601   if( sqlite3TriggerList(pParse, pDest) ){
   90602     return 0;   /* tab1 must not have triggers */
   90603   }
   90604 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90605   if( pDest->tabFlags & TF_Virtual ){
   90606     return 0;   /* tab1 must not be a virtual table */
   90607   }
   90608 #endif
   90609   if( onError==OE_Default ){
   90610     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
   90611     if( onError==OE_Default ) onError = OE_Abort;
   90612   }
   90613   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   90614   if( pSelect->pSrc->nSrc!=1 ){
   90615     return 0;   /* FROM clause must have exactly one term */
   90616   }
   90617   if( pSelect->pSrc->a[0].pSelect ){
   90618     return 0;   /* FROM clause cannot contain a subquery */
   90619   }
   90620   if( pSelect->pWhere ){
   90621     return 0;   /* SELECT may not have a WHERE clause */
   90622   }
   90623   if( pSelect->pOrderBy ){
   90624     return 0;   /* SELECT may not have an ORDER BY clause */
   90625   }
   90626   /* Do not need to test for a HAVING clause.  If HAVING is present but
   90627   ** there is no ORDER BY, we will get an error. */
   90628   if( pSelect->pGroupBy ){
   90629     return 0;   /* SELECT may not have a GROUP BY clause */
   90630   }
   90631   if( pSelect->pLimit ){
   90632     return 0;   /* SELECT may not have a LIMIT clause */
   90633   }
   90634   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   90635   if( pSelect->pPrior ){
   90636     return 0;   /* SELECT may not be a compound query */
   90637   }
   90638   if( pSelect->selFlags & SF_Distinct ){
   90639     return 0;   /* SELECT may not be DISTINCT */
   90640   }
   90641   pEList = pSelect->pEList;
   90642   assert( pEList!=0 );
   90643   if( pEList->nExpr!=1 ){
   90644     return 0;   /* The result set must have exactly one column */
   90645   }
   90646   assert( pEList->a[0].pExpr );
   90647   if( pEList->a[0].pExpr->op!=TK_ALL ){
   90648     return 0;   /* The result set must be the special operator "*" */
   90649   }
   90650 
   90651   /* At this point we have established that the statement is of the
   90652   ** correct syntactic form to participate in this optimization.  Now
   90653   ** we have to check the semantics.
   90654   */
   90655   pItem = pSelect->pSrc->a;
   90656   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   90657   if( pSrc==0 ){
   90658     return 0;   /* FROM clause does not contain a real table */
   90659   }
   90660   if( pSrc==pDest ){
   90661     return 0;   /* tab1 and tab2 may not be the same table */
   90662   }
   90663 #ifndef SQLITE_OMIT_VIRTUALTABLE
   90664   if( pSrc->tabFlags & TF_Virtual ){
   90665     return 0;   /* tab2 must not be a virtual table */
   90666   }
   90667 #endif
   90668   if( pSrc->pSelect ){
   90669     return 0;   /* tab2 may not be a view */
   90670   }
   90671   if( pDest->nCol!=pSrc->nCol ){
   90672     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   90673   }
   90674   if( pDest->iPKey!=pSrc->iPKey ){
   90675     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   90676   }
   90677   for(i=0; i<pDest->nCol; i++){
   90678     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
   90679       return 0;    /* Affinity must be the same on all columns */
   90680     }
   90681     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
   90682       return 0;    /* Collating sequence must be the same on all columns */
   90683     }
   90684     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
   90685       return 0;    /* tab2 must be NOT NULL if tab1 is */
   90686     }
   90687   }
   90688   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   90689     if( pDestIdx->onError!=OE_None ){
   90690       destHasUniqueIdx = 1;
   90691     }
   90692     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   90693       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   90694     }
   90695     if( pSrcIdx==0 ){
   90696       return 0;    /* pDestIdx has no corresponding index in pSrc */
   90697     }
   90698   }
   90699 #ifndef SQLITE_OMIT_CHECK
   90700   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
   90701     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   90702   }
   90703 #endif
   90704 #ifndef SQLITE_OMIT_FOREIGN_KEY
   90705   /* Disallow the transfer optimization if the destination table constains
   90706   ** any foreign key constraints.  This is more restrictive than necessary.
   90707   ** But the main beneficiary of the transfer optimization is the VACUUM
   90708   ** command, and the VACUUM command disables foreign key constraints.  So
   90709   ** the extra complication to make this rule less restrictive is probably
   90710   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
   90711   */
   90712   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
   90713     return 0;
   90714   }
   90715 #endif
   90716   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
   90717     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
   90718   }
   90719 
   90720   /* If we get this far, it means that the xfer optimization is at
   90721   ** least a possibility, though it might only work if the destination
   90722   ** table (tab1) is initially empty.
   90723   */
   90724 #ifdef SQLITE_TEST
   90725   sqlite3_xferopt_count++;
   90726 #endif
   90727   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   90728   v = sqlite3GetVdbe(pParse);
   90729   sqlite3CodeVerifySchema(pParse, iDbSrc);
   90730   iSrc = pParse->nTab++;
   90731   iDest = pParse->nTab++;
   90732   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   90733   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   90734   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
   90735    || destHasUniqueIdx                              /* (2) */
   90736    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
   90737   ){
   90738     /* In some circumstances, we are able to run the xfer optimization
   90739     ** only if the destination table is initially empty.  This code makes
   90740     ** that determination.  Conditions under which the destination must
   90741     ** be empty:
   90742     **
   90743     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
   90744     **     (If the destination is not initially empty, the rowid fields
   90745     **     of index entries might need to change.)
   90746     **
   90747     ** (2) The destination has a unique index.  (The xfer optimization
   90748     **     is unable to test uniqueness.)
   90749     **
   90750     ** (3) onError is something other than OE_Abort and OE_Rollback.
   90751     */
   90752     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
   90753     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   90754     sqlite3VdbeJumpHere(v, addr1);
   90755   }else{
   90756     emptyDestTest = 0;
   90757   }
   90758   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   90759   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   90760   regData = sqlite3GetTempReg(pParse);
   90761   regRowid = sqlite3GetTempReg(pParse);
   90762   if( pDest->iPKey>=0 ){
   90763     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   90764     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   90765     sqlite3HaltConstraint(
   90766         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   90767     sqlite3VdbeJumpHere(v, addr2);
   90768     autoIncStep(pParse, regAutoinc, regRowid);
   90769   }else if( pDest->pIndex==0 ){
   90770     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   90771   }else{
   90772     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   90773     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   90774   }
   90775   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   90776   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   90777   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   90778   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   90779   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
   90780   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   90781     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   90782       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   90783     }
   90784     assert( pSrcIdx );
   90785     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   90786     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90787     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
   90788     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
   90789                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90790     VdbeComment((v, "%s", pSrcIdx->zName));
   90791     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
   90792     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
   90793                       (char*)pKey, P4_KEYINFO_HANDOFF);
   90794     VdbeComment((v, "%s", pDestIdx->zName));
   90795     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   90796     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   90797     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   90798     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
   90799     sqlite3VdbeJumpHere(v, addr1);
   90800   }
   90801   sqlite3VdbeJumpHere(v, emptySrcTest);
   90802   sqlite3ReleaseTempReg(pParse, regRowid);
   90803   sqlite3ReleaseTempReg(pParse, regData);
   90804   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   90805   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90806   if( emptyDestTest ){
   90807     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   90808     sqlite3VdbeJumpHere(v, emptyDestTest);
   90809     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   90810     return 0;
   90811   }else{
   90812     return 1;
   90813   }
   90814 }
   90815 #endif /* SQLITE_OMIT_XFER_OPT */
   90816 
   90817 /************** End of insert.c **********************************************/
   90818 /************** Begin file legacy.c ******************************************/
   90819 /*
   90820 ** 2001 September 15
   90821 **
   90822 ** The author disclaims copyright to this source code.  In place of
   90823 ** a legal notice, here is a blessing:
   90824 **
   90825 **    May you do good and not evil.
   90826 **    May you find forgiveness for yourself and forgive others.
   90827 **    May you share freely, never taking more than you give.
   90828 **
   90829 *************************************************************************
   90830 ** Main file for the SQLite library.  The routines in this file
   90831 ** implement the programmer interface to the library.  Routines in
   90832 ** other files are for internal use by SQLite and should not be
   90833 ** accessed by users of the library.
   90834 */
   90835 
   90836 
   90837 /*
   90838 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   90839 ** codes.  Also write an error message into memory obtained from
   90840 ** malloc() and make *pzErrMsg point to that message.
   90841 **
   90842 ** If the SQL is a query, then for each row in the query result
   90843 ** the xCallback() function is called.  pArg becomes the first
   90844 ** argument to xCallback().  If xCallback=NULL then no callback
   90845 ** is invoked, even for queries.
   90846 */
   90847 SQLITE_API int sqlite3_exec(
   90848   sqlite3 *db,                /* The database on which the SQL executes */
   90849   const char *zSql,           /* The SQL to be executed */
   90850   sqlite3_callback xCallback, /* Invoke this callback routine */
   90851   void *pArg,                 /* First argument to xCallback() */
   90852   char **pzErrMsg             /* Write error messages here */
   90853 ){
   90854   int rc = SQLITE_OK;         /* Return code */
   90855   const char *zLeftover;      /* Tail of unprocessed SQL */
   90856   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   90857   char **azCols = 0;          /* Names of result columns */
   90858   int nRetry = 0;             /* Number of retry attempts */
   90859   int callbackIsInit;         /* True if callback data is initialized */
   90860 
   90861   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   90862   if( zSql==0 ) zSql = "";
   90863 
   90864   sqlite3_mutex_enter(db->mutex);
   90865   sqlite3Error(db, SQLITE_OK, 0);
   90866   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
   90867     int nCol;
   90868     char **azVals = 0;
   90869 
   90870     pStmt = 0;
   90871     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
   90872     assert( rc==SQLITE_OK || pStmt==0 );
   90873     if( rc!=SQLITE_OK ){
   90874       continue;
   90875     }
   90876     if( !pStmt ){
   90877       /* this happens for a comment or white-space */
   90878       zSql = zLeftover;
   90879       continue;
   90880     }
   90881 
   90882     callbackIsInit = 0;
   90883     nCol = sqlite3_column_count(pStmt);
   90884 
   90885     while( 1 ){
   90886       int i;
   90887       rc = sqlite3_step(pStmt);
   90888 
   90889       /* Invoke the callback function if required */
   90890       if( xCallback && (SQLITE_ROW==rc ||
   90891           (SQLITE_DONE==rc && !callbackIsInit
   90892                            && db->flags&SQLITE_NullCallback)) ){
   90893         if( !callbackIsInit ){
   90894           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   90895           if( azCols==0 ){
   90896             goto exec_out;
   90897           }
   90898           for(i=0; i<nCol; i++){
   90899             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   90900             /* sqlite3VdbeSetColName() installs column names as UTF8
   90901             ** strings so there is no way for sqlite3_column_name() to fail. */
   90902             assert( azCols[i]!=0 );
   90903           }
   90904           callbackIsInit = 1;
   90905         }
   90906         if( rc==SQLITE_ROW ){
   90907           azVals = &azCols[nCol];
   90908           for(i=0; i<nCol; i++){
   90909             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   90910             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   90911               db->mallocFailed = 1;
   90912               goto exec_out;
   90913             }
   90914           }
   90915         }
   90916         if( xCallback(pArg, nCol, azVals, azCols) ){
   90917           rc = SQLITE_ABORT;
   90918           sqlite3VdbeFinalize((Vdbe *)pStmt);
   90919           pStmt = 0;
   90920           sqlite3Error(db, SQLITE_ABORT, 0);
   90921           goto exec_out;
   90922         }
   90923       }
   90924 
   90925       if( rc!=SQLITE_ROW ){
   90926         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   90927         pStmt = 0;
   90928         if( rc!=SQLITE_SCHEMA ){
   90929           nRetry = 0;
   90930           zSql = zLeftover;
   90931           while( sqlite3Isspace(zSql[0]) ) zSql++;
   90932         }
   90933         break;
   90934       }
   90935     }
   90936 
   90937     sqlite3DbFree(db, azCols);
   90938     azCols = 0;
   90939   }
   90940 
   90941 exec_out:
   90942   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   90943   sqlite3DbFree(db, azCols);
   90944 
   90945   rc = sqlite3ApiExit(db, rc);
   90946   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   90947     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   90948     *pzErrMsg = sqlite3Malloc(nErrMsg);
   90949     if( *pzErrMsg ){
   90950       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   90951     }else{
   90952       rc = SQLITE_NOMEM;
   90953       sqlite3Error(db, SQLITE_NOMEM, 0);
   90954     }
   90955   }else if( pzErrMsg ){
   90956     *pzErrMsg = 0;
   90957   }
   90958 
   90959   assert( (rc&db->errMask)==rc );
   90960   sqlite3_mutex_leave(db->mutex);
   90961   return rc;
   90962 }
   90963 
   90964 /************** End of legacy.c **********************************************/
   90965 /************** Begin file loadext.c *****************************************/
   90966 /*
   90967 ** 2006 June 7
   90968 **
   90969 ** The author disclaims copyright to this source code.  In place of
   90970 ** a legal notice, here is a blessing:
   90971 **
   90972 **    May you do good and not evil.
   90973 **    May you find forgiveness for yourself and forgive others.
   90974 **    May you share freely, never taking more than you give.
   90975 **
   90976 *************************************************************************
   90977 ** This file contains code used to dynamically load extensions into
   90978 ** the SQLite library.
   90979 */
   90980 
   90981 #ifndef SQLITE_CORE
   90982   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   90983 #endif
   90984 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   90985 /************** Begin file sqlite3ext.h **************************************/
   90986 /*
   90987 ** 2006 June 7
   90988 **
   90989 ** The author disclaims copyright to this source code.  In place of
   90990 ** a legal notice, here is a blessing:
   90991 **
   90992 **    May you do good and not evil.
   90993 **    May you find forgiveness for yourself and forgive others.
   90994 **    May you share freely, never taking more than you give.
   90995 **
   90996 *************************************************************************
   90997 ** This header file defines the SQLite interface for use by
   90998 ** shared libraries that want to be imported as extensions into
   90999 ** an SQLite instance.  Shared libraries that intend to be loaded
   91000 ** as extensions by SQLite should #include this file instead of
   91001 ** sqlite3.h.
   91002 */
   91003 #ifndef _SQLITE3EXT_H_
   91004 #define _SQLITE3EXT_H_
   91005 
   91006 typedef struct sqlite3_api_routines sqlite3_api_routines;
   91007 
   91008 /*
   91009 ** The following structure holds pointers to all of the SQLite API
   91010 ** routines.
   91011 **
   91012 ** WARNING:  In order to maintain backwards compatibility, add new
   91013 ** interfaces to the end of this structure only.  If you insert new
   91014 ** interfaces in the middle of this structure, then older different
   91015 ** versions of SQLite will not be able to load each others' shared
   91016 ** libraries!
   91017 */
   91018 struct sqlite3_api_routines {
   91019   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   91020   int  (*aggregate_count)(sqlite3_context*);
   91021   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   91022   int  (*bind_double)(sqlite3_stmt*,int,double);
   91023   int  (*bind_int)(sqlite3_stmt*,int,int);
   91024   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   91025   int  (*bind_null)(sqlite3_stmt*,int);
   91026   int  (*bind_parameter_count)(sqlite3_stmt*);
   91027   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   91028   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   91029   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   91030   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   91031   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   91032   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   91033   int  (*busy_timeout)(sqlite3*,int ms);
   91034   int  (*changes)(sqlite3*);
   91035   int  (*close)(sqlite3*);
   91036   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
   91037                            int eTextRep,const char*));
   91038   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
   91039                              int eTextRep,const void*));
   91040   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   91041   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   91042   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   91043   int  (*column_count)(sqlite3_stmt*pStmt);
   91044   const char * (*column_database_name)(sqlite3_stmt*,int);
   91045   const void * (*column_database_name16)(sqlite3_stmt*,int);
   91046   const char * (*column_decltype)(sqlite3_stmt*,int i);
   91047   const void * (*column_decltype16)(sqlite3_stmt*,int);
   91048   double  (*column_double)(sqlite3_stmt*,int iCol);
   91049   int  (*column_int)(sqlite3_stmt*,int iCol);
   91050   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   91051   const char * (*column_name)(sqlite3_stmt*,int);
   91052   const void * (*column_name16)(sqlite3_stmt*,int);
   91053   const char * (*column_origin_name)(sqlite3_stmt*,int);
   91054   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   91055   const char * (*column_table_name)(sqlite3_stmt*,int);
   91056   const void * (*column_table_name16)(sqlite3_stmt*,int);
   91057   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   91058   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   91059   int  (*column_type)(sqlite3_stmt*,int iCol);
   91060   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   91061   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   91062   int  (*complete)(const char*sql);
   91063   int  (*complete16)(const void*sql);
   91064   int  (*create_collation)(sqlite3*,const char*,int,void*,
   91065                            int(*)(void*,int,const void*,int,const void*));
   91066   int  (*create_collation16)(sqlite3*,const void*,int,void*,
   91067                              int(*)(void*,int,const void*,int,const void*));
   91068   int  (*create_function)(sqlite3*,const char*,int,int,void*,
   91069                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91070                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91071                           void (*xFinal)(sqlite3_context*));
   91072   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
   91073                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91074                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91075                             void (*xFinal)(sqlite3_context*));
   91076   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   91077   int  (*data_count)(sqlite3_stmt*pStmt);
   91078   sqlite3 * (*db_handle)(sqlite3_stmt*);
   91079   int (*declare_vtab)(sqlite3*,const char*);
   91080   int  (*enable_shared_cache)(int);
   91081   int  (*errcode)(sqlite3*db);
   91082   const char * (*errmsg)(sqlite3*);
   91083   const void * (*errmsg16)(sqlite3*);
   91084   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   91085   int  (*expired)(sqlite3_stmt*);
   91086   int  (*finalize)(sqlite3_stmt*pStmt);
   91087   void  (*free)(void*);
   91088   void  (*free_table)(char**result);
   91089   int  (*get_autocommit)(sqlite3*);
   91090   void * (*get_auxdata)(sqlite3_context*,int);
   91091   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   91092   int  (*global_recover)(void);
   91093   void  (*interruptx)(sqlite3*);
   91094   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   91095   const char * (*libversion)(void);
   91096   int  (*libversion_number)(void);
   91097   void *(*malloc)(int);
   91098   char * (*mprintf)(const char*,...);
   91099   int  (*open)(const char*,sqlite3**);
   91100   int  (*open16)(const void*,sqlite3**);
   91101   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   91102   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   91103   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   91104   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   91105   void *(*realloc)(void*,int);
   91106   int  (*reset)(sqlite3_stmt*pStmt);
   91107   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   91108   void  (*result_double)(sqlite3_context*,double);
   91109   void  (*result_error)(sqlite3_context*,const char*,int);
   91110   void  (*result_error16)(sqlite3_context*,const void*,int);
   91111   void  (*result_int)(sqlite3_context*,int);
   91112   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   91113   void  (*result_null)(sqlite3_context*);
   91114   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   91115   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   91116   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   91117   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   91118   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   91119   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   91120   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   91121                          const char*,const char*),void*);
   91122   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   91123   char * (*snprintf)(int,char*,const char*,...);
   91124   int  (*step)(sqlite3_stmt*);
   91125   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   91126                                 char const**,char const**,int*,int*,int*);
   91127   void  (*thread_cleanup)(void);
   91128   int  (*total_changes)(sqlite3*);
   91129   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   91130   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   91131   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   91132                                          sqlite_int64),void*);
   91133   void * (*user_data)(sqlite3_context*);
   91134   const void * (*value_blob)(sqlite3_value*);
   91135   int  (*value_bytes)(sqlite3_value*);
   91136   int  (*value_bytes16)(sqlite3_value*);
   91137   double  (*value_double)(sqlite3_value*);
   91138   int  (*value_int)(sqlite3_value*);
   91139   sqlite_int64  (*value_int64)(sqlite3_value*);
   91140   int  (*value_numeric_type)(sqlite3_value*);
   91141   const unsigned char * (*value_text)(sqlite3_value*);
   91142   const void * (*value_text16)(sqlite3_value*);
   91143   const void * (*value_text16be)(sqlite3_value*);
   91144   const void * (*value_text16le)(sqlite3_value*);
   91145   int  (*value_type)(sqlite3_value*);
   91146   char *(*vmprintf)(const char*,va_list);
   91147   /* Added ??? */
   91148   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   91149   /* Added by 3.3.13 */
   91150   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   91151   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   91152   int (*clear_bindings)(sqlite3_stmt*);
   91153   /* Added by 3.4.1 */
   91154   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   91155                           void (*xDestroy)(void *));
   91156   /* Added by 3.5.0 */
   91157   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   91158   int (*blob_bytes)(sqlite3_blob*);
   91159   int (*blob_close)(sqlite3_blob*);
   91160   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   91161                    int,sqlite3_blob**);
   91162   int (*blob_read)(sqlite3_blob*,void*,int,int);
   91163   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   91164   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   91165                              int(*)(void*,int,const void*,int,const void*),
   91166                              void(*)(void*));
   91167   int (*file_control)(sqlite3*,const char*,int,void*);
   91168   sqlite3_int64 (*memory_highwater)(int);
   91169   sqlite3_int64 (*memory_used)(void);
   91170   sqlite3_mutex *(*mutex_alloc)(int);
   91171   void (*mutex_enter)(sqlite3_mutex*);
   91172   void (*mutex_free)(sqlite3_mutex*);
   91173   void (*mutex_leave)(sqlite3_mutex*);
   91174   int (*mutex_try)(sqlite3_mutex*);
   91175   int (*open_v2)(const char*,sqlite3**,int,const char*);
   91176   int (*release_memory)(int);
   91177   void (*result_error_nomem)(sqlite3_context*);
   91178   void (*result_error_toobig)(sqlite3_context*);
   91179   int (*sleep)(int);
   91180   void (*soft_heap_limit)(int);
   91181   sqlite3_vfs *(*vfs_find)(const char*);
   91182   int (*vfs_register)(sqlite3_vfs*,int);
   91183   int (*vfs_unregister)(sqlite3_vfs*);
   91184   int (*xthreadsafe)(void);
   91185   void (*result_zeroblob)(sqlite3_context*,int);
   91186   void (*result_error_code)(sqlite3_context*,int);
   91187   int (*test_control)(int, ...);
   91188   void (*randomness)(int,void*);
   91189   sqlite3 *(*context_db_handle)(sqlite3_context*);
   91190   int (*extended_result_codes)(sqlite3*,int);
   91191   int (*limit)(sqlite3*,int,int);
   91192   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   91193   const char *(*sql)(sqlite3_stmt*);
   91194   int (*status)(int,int*,int*,int);
   91195   int (*backup_finish)(sqlite3_backup*);
   91196   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   91197   int (*backup_pagecount)(sqlite3_backup*);
   91198   int (*backup_remaining)(sqlite3_backup*);
   91199   int (*backup_step)(sqlite3_backup*,int);
   91200   const char *(*compileoption_get)(int);
   91201   int (*compileoption_used)(const char*);
   91202   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   91203                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   91204                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   91205                             void (*xFinal)(sqlite3_context*),
   91206                             void(*xDestroy)(void*));
   91207   int (*db_config)(sqlite3*,int,...);
   91208   sqlite3_mutex *(*db_mutex)(sqlite3*);
   91209   int (*db_status)(sqlite3*,int,int*,int*,int);
   91210   int (*extended_errcode)(sqlite3*);
   91211   void (*log)(int,const char*,...);
   91212   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   91213   const char *(*sourceid)(void);
   91214   int (*stmt_status)(sqlite3_stmt*,int,int);
   91215   int (*strnicmp)(const char*,const char*,int);
   91216   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   91217   int (*wal_autocheckpoint)(sqlite3*,int);
   91218   int (*wal_checkpoint)(sqlite3*,const char*);
   91219   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   91220   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   91221   int (*vtab_config)(sqlite3*,int op,...);
   91222   int (*vtab_on_conflict)(sqlite3*);
   91223 };
   91224 
   91225 /*
   91226 ** The following macros redefine the API routines so that they are
   91227 ** redirected throught the global sqlite3_api structure.
   91228 **
   91229 ** This header file is also used by the loadext.c source file
   91230 ** (part of the main SQLite library - not an extension) so that
   91231 ** it can get access to the sqlite3_api_routines structure
   91232 ** definition.  But the main library does not want to redefine
   91233 ** the API.  So the redefinition macros are only valid if the
   91234 ** SQLITE_CORE macros is undefined.
   91235 */
   91236 #ifndef SQLITE_CORE
   91237 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   91238 #ifndef SQLITE_OMIT_DEPRECATED
   91239 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   91240 #endif
   91241 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   91242 #define sqlite3_bind_double            sqlite3_api->bind_double
   91243 #define sqlite3_bind_int               sqlite3_api->bind_int
   91244 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   91245 #define sqlite3_bind_null              sqlite3_api->bind_null
   91246 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   91247 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   91248 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   91249 #define sqlite3_bind_text              sqlite3_api->bind_text
   91250 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   91251 #define sqlite3_bind_value             sqlite3_api->bind_value
   91252 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   91253 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   91254 #define sqlite3_changes                sqlite3_api->changes
   91255 #define sqlite3_close                  sqlite3_api->close
   91256 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   91257 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   91258 #define sqlite3_column_blob            sqlite3_api->column_blob
   91259 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   91260 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   91261 #define sqlite3_column_count           sqlite3_api->column_count
   91262 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   91263 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   91264 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   91265 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   91266 #define sqlite3_column_double          sqlite3_api->column_double
   91267 #define sqlite3_column_int             sqlite3_api->column_int
   91268 #define sqlite3_column_int64           sqlite3_api->column_int64
   91269 #define sqlite3_column_name            sqlite3_api->column_name
   91270 #define sqlite3_column_name16          sqlite3_api->column_name16
   91271 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   91272 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   91273 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   91274 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   91275 #define sqlite3_column_text            sqlite3_api->column_text
   91276 #define sqlite3_column_text16          sqlite3_api->column_text16
   91277 #define sqlite3_column_type            sqlite3_api->column_type
   91278 #define sqlite3_column_value           sqlite3_api->column_value
   91279 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   91280 #define sqlite3_complete               sqlite3_api->complete
   91281 #define sqlite3_complete16             sqlite3_api->complete16
   91282 #define sqlite3_create_collation       sqlite3_api->create_collation
   91283 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   91284 #define sqlite3_create_function        sqlite3_api->create_function
   91285 #define sqlite3_create_function16      sqlite3_api->create_function16
   91286 #define sqlite3_create_module          sqlite3_api->create_module
   91287 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   91288 #define sqlite3_data_count             sqlite3_api->data_count
   91289 #define sqlite3_db_handle              sqlite3_api->db_handle
   91290 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   91291 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   91292 #define sqlite3_errcode                sqlite3_api->errcode
   91293 #define sqlite3_errmsg                 sqlite3_api->errmsg
   91294 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   91295 #define sqlite3_exec                   sqlite3_api->exec
   91296 #ifndef SQLITE_OMIT_DEPRECATED
   91297 #define sqlite3_expired                sqlite3_api->expired
   91298 #endif
   91299 #define sqlite3_finalize               sqlite3_api->finalize
   91300 #define sqlite3_free                   sqlite3_api->free
   91301 #define sqlite3_free_table             sqlite3_api->free_table
   91302 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   91303 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   91304 #define sqlite3_get_table              sqlite3_api->get_table
   91305 #ifndef SQLITE_OMIT_DEPRECATED
   91306 #define sqlite3_global_recover         sqlite3_api->global_recover
   91307 #endif
   91308 #define sqlite3_interrupt              sqlite3_api->interruptx
   91309 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   91310 #define sqlite3_libversion             sqlite3_api->libversion
   91311 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   91312 #define sqlite3_malloc                 sqlite3_api->malloc
   91313 #define sqlite3_mprintf                sqlite3_api->mprintf
   91314 #define sqlite3_open                   sqlite3_api->open
   91315 #define sqlite3_open16                 sqlite3_api->open16
   91316 #define sqlite3_prepare                sqlite3_api->prepare
   91317 #define sqlite3_prepare16              sqlite3_api->prepare16
   91318 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   91319 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   91320 #define sqlite3_profile                sqlite3_api->profile
   91321 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   91322 #define sqlite3_realloc                sqlite3_api->realloc
   91323 #define sqlite3_reset                  sqlite3_api->reset
   91324 #define sqlite3_result_blob            sqlite3_api->result_blob
   91325 #define sqlite3_result_double          sqlite3_api->result_double
   91326 #define sqlite3_result_error           sqlite3_api->result_error
   91327 #define sqlite3_result_error16         sqlite3_api->result_error16
   91328 #define sqlite3_result_int             sqlite3_api->result_int
   91329 #define sqlite3_result_int64           sqlite3_api->result_int64
   91330 #define sqlite3_result_null            sqlite3_api->result_null
   91331 #define sqlite3_result_text            sqlite3_api->result_text
   91332 #define sqlite3_result_text16          sqlite3_api->result_text16
   91333 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   91334 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   91335 #define sqlite3_result_value           sqlite3_api->result_value
   91336 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   91337 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   91338 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   91339 #define sqlite3_snprintf               sqlite3_api->snprintf
   91340 #define sqlite3_step                   sqlite3_api->step
   91341 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   91342 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   91343 #define sqlite3_total_changes          sqlite3_api->total_changes
   91344 #define sqlite3_trace                  sqlite3_api->trace
   91345 #ifndef SQLITE_OMIT_DEPRECATED
   91346 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   91347 #endif
   91348 #define sqlite3_update_hook            sqlite3_api->update_hook
   91349 #define sqlite3_user_data              sqlite3_api->user_data
   91350 #define sqlite3_value_blob             sqlite3_api->value_blob
   91351 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   91352 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   91353 #define sqlite3_value_double           sqlite3_api->value_double
   91354 #define sqlite3_value_int              sqlite3_api->value_int
   91355 #define sqlite3_value_int64            sqlite3_api->value_int64
   91356 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   91357 #define sqlite3_value_text             sqlite3_api->value_text
   91358 #define sqlite3_value_text16           sqlite3_api->value_text16
   91359 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   91360 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   91361 #define sqlite3_value_type             sqlite3_api->value_type
   91362 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   91363 #define sqlite3_overload_function      sqlite3_api->overload_function
   91364 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   91365 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   91366 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   91367 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   91368 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   91369 #define sqlite3_blob_close             sqlite3_api->blob_close
   91370 #define sqlite3_blob_open              sqlite3_api->blob_open
   91371 #define sqlite3_blob_read              sqlite3_api->blob_read
   91372 #define sqlite3_blob_write             sqlite3_api->blob_write
   91373 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   91374 #define sqlite3_file_control           sqlite3_api->file_control
   91375 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   91376 #define sqlite3_memory_used            sqlite3_api->memory_used
   91377 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   91378 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   91379 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   91380 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   91381 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   91382 #define sqlite3_open_v2                sqlite3_api->open_v2
   91383 #define sqlite3_release_memory         sqlite3_api->release_memory
   91384 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   91385 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   91386 #define sqlite3_sleep                  sqlite3_api->sleep
   91387 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   91388 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   91389 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   91390 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   91391 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   91392 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   91393 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   91394 #define sqlite3_test_control           sqlite3_api->test_control
   91395 #define sqlite3_randomness             sqlite3_api->randomness
   91396 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   91397 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   91398 #define sqlite3_limit                  sqlite3_api->limit
   91399 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   91400 #define sqlite3_sql                    sqlite3_api->sql
   91401 #define sqlite3_status                 sqlite3_api->status
   91402 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   91403 #define sqlite3_backup_init            sqlite3_api->backup_init
   91404 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   91405 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   91406 #define sqlite3_backup_step            sqlite3_api->backup_step
   91407 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   91408 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   91409 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   91410 #define sqlite3_db_config              sqlite3_api->db_config
   91411 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   91412 #define sqlite3_db_status              sqlite3_api->db_status
   91413 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   91414 #define sqlite3_log                    sqlite3_api->log
   91415 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   91416 #define sqlite3_sourceid               sqlite3_api->sourceid
   91417 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   91418 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   91419 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   91420 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   91421 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   91422 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   91423 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   91424 #define sqlite3_vtab_config            sqlite3_api->vtab_config
   91425 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   91426 #endif /* SQLITE_CORE */
   91427 
   91428 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
   91429 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
   91430 
   91431 #endif /* _SQLITE3EXT_H_ */
   91432 
   91433 /************** End of sqlite3ext.h ******************************************/
   91434 /************** Continuing where we left off in loadext.c ********************/
   91435 /* #include <string.h> */
   91436 
   91437 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   91438 
   91439 /*
   91440 ** Some API routines are omitted when various features are
   91441 ** excluded from a build of SQLite.  Substitute a NULL pointer
   91442 ** for any missing APIs.
   91443 */
   91444 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   91445 # define sqlite3_column_database_name   0
   91446 # define sqlite3_column_database_name16 0
   91447 # define sqlite3_column_table_name      0
   91448 # define sqlite3_column_table_name16    0
   91449 # define sqlite3_column_origin_name     0
   91450 # define sqlite3_column_origin_name16   0
   91451 # define sqlite3_table_column_metadata  0
   91452 #endif
   91453 
   91454 #ifdef SQLITE_OMIT_AUTHORIZATION
   91455 # define sqlite3_set_authorizer         0
   91456 #endif
   91457 
   91458 #ifdef SQLITE_OMIT_UTF16
   91459 # define sqlite3_bind_text16            0
   91460 # define sqlite3_collation_needed16     0
   91461 # define sqlite3_column_decltype16      0
   91462 # define sqlite3_column_name16          0
   91463 # define sqlite3_column_text16          0
   91464 # define sqlite3_complete16             0
   91465 # define sqlite3_create_collation16     0
   91466 # define sqlite3_create_function16      0
   91467 # define sqlite3_errmsg16               0
   91468 # define sqlite3_open16                 0
   91469 # define sqlite3_prepare16              0
   91470 # define sqlite3_prepare16_v2           0
   91471 # define sqlite3_result_error16         0
   91472 # define sqlite3_result_text16          0
   91473 # define sqlite3_result_text16be        0
   91474 # define sqlite3_result_text16le        0
   91475 # define sqlite3_value_text16           0
   91476 # define sqlite3_value_text16be         0
   91477 # define sqlite3_value_text16le         0
   91478 # define sqlite3_column_database_name16 0
   91479 # define sqlite3_column_table_name16    0
   91480 # define sqlite3_column_origin_name16   0
   91481 #endif
   91482 
   91483 #ifdef SQLITE_OMIT_COMPLETE
   91484 # define sqlite3_complete 0
   91485 # define sqlite3_complete16 0
   91486 #endif
   91487 
   91488 #ifdef SQLITE_OMIT_DECLTYPE
   91489 # define sqlite3_column_decltype16      0
   91490 # define sqlite3_column_decltype        0
   91491 #endif
   91492 
   91493 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   91494 # define sqlite3_progress_handler 0
   91495 #endif
   91496 
   91497 #ifdef SQLITE_OMIT_VIRTUALTABLE
   91498 # define sqlite3_create_module 0
   91499 # define sqlite3_create_module_v2 0
   91500 # define sqlite3_declare_vtab 0
   91501 # define sqlite3_vtab_config 0
   91502 # define sqlite3_vtab_on_conflict 0
   91503 #endif
   91504 
   91505 #ifdef SQLITE_OMIT_SHARED_CACHE
   91506 # define sqlite3_enable_shared_cache 0
   91507 #endif
   91508 
   91509 #ifdef SQLITE_OMIT_TRACE
   91510 # define sqlite3_profile       0
   91511 # define sqlite3_trace         0
   91512 #endif
   91513 
   91514 #ifdef SQLITE_OMIT_GET_TABLE
   91515 # define sqlite3_free_table    0
   91516 # define sqlite3_get_table     0
   91517 #endif
   91518 
   91519 #ifdef SQLITE_OMIT_INCRBLOB
   91520 #define sqlite3_bind_zeroblob  0
   91521 #define sqlite3_blob_bytes     0
   91522 #define sqlite3_blob_close     0
   91523 #define sqlite3_blob_open      0
   91524 #define sqlite3_blob_read      0
   91525 #define sqlite3_blob_write     0
   91526 #define sqlite3_blob_reopen    0
   91527 #endif
   91528 
   91529 /*
   91530 ** The following structure contains pointers to all SQLite API routines.
   91531 ** A pointer to this structure is passed into extensions when they are
   91532 ** loaded so that the extension can make calls back into the SQLite
   91533 ** library.
   91534 **
   91535 ** When adding new APIs, add them to the bottom of this structure
   91536 ** in order to preserve backwards compatibility.
   91537 **
   91538 ** Extensions that use newer APIs should first call the
   91539 ** sqlite3_libversion_number() to make sure that the API they
   91540 ** intend to use is supported by the library.  Extensions should
   91541 ** also check to make sure that the pointer to the function is
   91542 ** not NULL before calling it.
   91543 */
   91544 static const sqlite3_api_routines sqlite3Apis = {
   91545   sqlite3_aggregate_context,
   91546 #ifndef SQLITE_OMIT_DEPRECATED
   91547   sqlite3_aggregate_count,
   91548 #else
   91549   0,
   91550 #endif
   91551   sqlite3_bind_blob,
   91552   sqlite3_bind_double,
   91553   sqlite3_bind_int,
   91554   sqlite3_bind_int64,
   91555   sqlite3_bind_null,
   91556   sqlite3_bind_parameter_count,
   91557   sqlite3_bind_parameter_index,
   91558   sqlite3_bind_parameter_name,
   91559   sqlite3_bind_text,
   91560   sqlite3_bind_text16,
   91561   sqlite3_bind_value,
   91562   sqlite3_busy_handler,
   91563   sqlite3_busy_timeout,
   91564   sqlite3_changes,
   91565   sqlite3_close,
   91566   sqlite3_collation_needed,
   91567   sqlite3_collation_needed16,
   91568   sqlite3_column_blob,
   91569   sqlite3_column_bytes,
   91570   sqlite3_column_bytes16,
   91571   sqlite3_column_count,
   91572   sqlite3_column_database_name,
   91573   sqlite3_column_database_name16,
   91574   sqlite3_column_decltype,
   91575   sqlite3_column_decltype16,
   91576   sqlite3_column_double,
   91577   sqlite3_column_int,
   91578   sqlite3_column_int64,
   91579   sqlite3_column_name,
   91580   sqlite3_column_name16,
   91581   sqlite3_column_origin_name,
   91582   sqlite3_column_origin_name16,
   91583   sqlite3_column_table_name,
   91584   sqlite3_column_table_name16,
   91585   sqlite3_column_text,
   91586   sqlite3_column_text16,
   91587   sqlite3_column_type,
   91588   sqlite3_column_value,
   91589   sqlite3_commit_hook,
   91590   sqlite3_complete,
   91591   sqlite3_complete16,
   91592   sqlite3_create_collation,
   91593   sqlite3_create_collation16,
   91594   sqlite3_create_function,
   91595   sqlite3_create_function16,
   91596   sqlite3_create_module,
   91597   sqlite3_data_count,
   91598   sqlite3_db_handle,
   91599   sqlite3_declare_vtab,
   91600   sqlite3_enable_shared_cache,
   91601   sqlite3_errcode,
   91602   sqlite3_errmsg,
   91603   sqlite3_errmsg16,
   91604   sqlite3_exec,
   91605 #ifndef SQLITE_OMIT_DEPRECATED
   91606   sqlite3_expired,
   91607 #else
   91608   0,
   91609 #endif
   91610   sqlite3_finalize,
   91611   sqlite3_free,
   91612   sqlite3_free_table,
   91613   sqlite3_get_autocommit,
   91614   sqlite3_get_auxdata,
   91615   sqlite3_get_table,
   91616   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   91617   sqlite3_interrupt,
   91618   sqlite3_last_insert_rowid,
   91619   sqlite3_libversion,
   91620   sqlite3_libversion_number,
   91621   sqlite3_malloc,
   91622   sqlite3_mprintf,
   91623   sqlite3_open,
   91624   sqlite3_open16,
   91625   sqlite3_prepare,
   91626   sqlite3_prepare16,
   91627   sqlite3_profile,
   91628   sqlite3_progress_handler,
   91629   sqlite3_realloc,
   91630   sqlite3_reset,
   91631   sqlite3_result_blob,
   91632   sqlite3_result_double,
   91633   sqlite3_result_error,
   91634   sqlite3_result_error16,
   91635   sqlite3_result_int,
   91636   sqlite3_result_int64,
   91637   sqlite3_result_null,
   91638   sqlite3_result_text,
   91639   sqlite3_result_text16,
   91640   sqlite3_result_text16be,
   91641   sqlite3_result_text16le,
   91642   sqlite3_result_value,
   91643   sqlite3_rollback_hook,
   91644   sqlite3_set_authorizer,
   91645   sqlite3_set_auxdata,
   91646   sqlite3_snprintf,
   91647   sqlite3_step,
   91648   sqlite3_table_column_metadata,
   91649 #ifndef SQLITE_OMIT_DEPRECATED
   91650   sqlite3_thread_cleanup,
   91651 #else
   91652   0,
   91653 #endif
   91654   sqlite3_total_changes,
   91655   sqlite3_trace,
   91656 #ifndef SQLITE_OMIT_DEPRECATED
   91657   sqlite3_transfer_bindings,
   91658 #else
   91659   0,
   91660 #endif
   91661   sqlite3_update_hook,
   91662   sqlite3_user_data,
   91663   sqlite3_value_blob,
   91664   sqlite3_value_bytes,
   91665   sqlite3_value_bytes16,
   91666   sqlite3_value_double,
   91667   sqlite3_value_int,
   91668   sqlite3_value_int64,
   91669   sqlite3_value_numeric_type,
   91670   sqlite3_value_text,
   91671   sqlite3_value_text16,
   91672   sqlite3_value_text16be,
   91673   sqlite3_value_text16le,
   91674   sqlite3_value_type,
   91675   sqlite3_vmprintf,
   91676   /*
   91677   ** The original API set ends here.  All extensions can call any
   91678   ** of the APIs above provided that the pointer is not NULL.  But
   91679   ** before calling APIs that follow, extension should check the
   91680   ** sqlite3_libversion_number() to make sure they are dealing with
   91681   ** a library that is new enough to support that API.
   91682   *************************************************************************
   91683   */
   91684   sqlite3_overload_function,
   91685 
   91686   /*
   91687   ** Added after 3.3.13
   91688   */
   91689   sqlite3_prepare_v2,
   91690   sqlite3_prepare16_v2,
   91691   sqlite3_clear_bindings,
   91692 
   91693   /*
   91694   ** Added for 3.4.1
   91695   */
   91696   sqlite3_create_module_v2,
   91697 
   91698   /*
   91699   ** Added for 3.5.0
   91700   */
   91701   sqlite3_bind_zeroblob,
   91702   sqlite3_blob_bytes,
   91703   sqlite3_blob_close,
   91704   sqlite3_blob_open,
   91705   sqlite3_blob_read,
   91706   sqlite3_blob_write,
   91707   sqlite3_create_collation_v2,
   91708   sqlite3_file_control,
   91709   sqlite3_memory_highwater,
   91710   sqlite3_memory_used,
   91711 #ifdef SQLITE_MUTEX_OMIT
   91712   0,
   91713   0,
   91714   0,
   91715   0,
   91716   0,
   91717 #else
   91718   sqlite3_mutex_alloc,
   91719   sqlite3_mutex_enter,
   91720   sqlite3_mutex_free,
   91721   sqlite3_mutex_leave,
   91722   sqlite3_mutex_try,
   91723 #endif
   91724   sqlite3_open_v2,
   91725   sqlite3_release_memory,
   91726   sqlite3_result_error_nomem,
   91727   sqlite3_result_error_toobig,
   91728   sqlite3_sleep,
   91729   sqlite3_soft_heap_limit,
   91730   sqlite3_vfs_find,
   91731   sqlite3_vfs_register,
   91732   sqlite3_vfs_unregister,
   91733 
   91734   /*
   91735   ** Added for 3.5.8
   91736   */
   91737   sqlite3_threadsafe,
   91738   sqlite3_result_zeroblob,
   91739   sqlite3_result_error_code,
   91740   sqlite3_test_control,
   91741   sqlite3_randomness,
   91742   sqlite3_context_db_handle,
   91743 
   91744   /*
   91745   ** Added for 3.6.0
   91746   */
   91747   sqlite3_extended_result_codes,
   91748   sqlite3_limit,
   91749   sqlite3_next_stmt,
   91750   sqlite3_sql,
   91751   sqlite3_status,
   91752 
   91753   /*
   91754   ** Added for 3.7.4
   91755   */
   91756   sqlite3_backup_finish,
   91757   sqlite3_backup_init,
   91758   sqlite3_backup_pagecount,
   91759   sqlite3_backup_remaining,
   91760   sqlite3_backup_step,
   91761 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   91762   sqlite3_compileoption_get,
   91763   sqlite3_compileoption_used,
   91764 #else
   91765   0,
   91766   0,
   91767 #endif
   91768   sqlite3_create_function_v2,
   91769   sqlite3_db_config,
   91770   sqlite3_db_mutex,
   91771   sqlite3_db_status,
   91772   sqlite3_extended_errcode,
   91773   sqlite3_log,
   91774   sqlite3_soft_heap_limit64,
   91775   sqlite3_sourceid,
   91776   sqlite3_stmt_status,
   91777   sqlite3_strnicmp,
   91778 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   91779   sqlite3_unlock_notify,
   91780 #else
   91781   0,
   91782 #endif
   91783 #ifndef SQLITE_OMIT_WAL
   91784   sqlite3_wal_autocheckpoint,
   91785   sqlite3_wal_checkpoint,
   91786   sqlite3_wal_hook,
   91787 #else
   91788   0,
   91789   0,
   91790   0,
   91791 #endif
   91792   sqlite3_blob_reopen,
   91793   sqlite3_vtab_config,
   91794   sqlite3_vtab_on_conflict,
   91795 };
   91796 
   91797 /*
   91798 ** Attempt to load an SQLite extension library contained in the file
   91799 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   91800 ** default entry point name (sqlite3_extension_init) is used.  Use
   91801 ** of the default name is recommended.
   91802 **
   91803 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   91804 **
   91805 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   91806 ** error message text.  The calling function should free this memory
   91807 ** by calling sqlite3DbFree(db, ).
   91808 */
   91809 static int sqlite3LoadExtension(
   91810   sqlite3 *db,          /* Load the extension into this database connection */
   91811   const char *zFile,    /* Name of the shared library containing extension */
   91812   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   91813   char **pzErrMsg       /* Put error message here if not 0 */
   91814 ){
   91815   sqlite3_vfs *pVfs = db->pVfs;
   91816   void *handle;
   91817   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   91818   char *zErrmsg = 0;
   91819   void **aHandle;
   91820   int nMsg = 300 + sqlite3Strlen30(zFile);
   91821 
   91822   if( pzErrMsg ) *pzErrMsg = 0;
   91823 
   91824   /* Ticket #1863.  To avoid a creating security problems for older
   91825   ** applications that relink against newer versions of SQLite, the
   91826   ** ability to run load_extension is turned off by default.  One
   91827   ** must call sqlite3_enable_load_extension() to turn on extension
   91828   ** loading.  Otherwise you get the following error.
   91829   */
   91830   if( (db->flags & SQLITE_LoadExtension)==0 ){
   91831     if( pzErrMsg ){
   91832       *pzErrMsg = sqlite3_mprintf("not authorized");
   91833     }
   91834     return SQLITE_ERROR;
   91835   }
   91836 
   91837   if( zProc==0 ){
   91838     zProc = "sqlite3_extension_init";
   91839   }
   91840 
   91841   handle = sqlite3OsDlOpen(pVfs, zFile);
   91842   if( handle==0 ){
   91843     if( pzErrMsg ){
   91844       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   91845       if( zErrmsg ){
   91846         sqlite3_snprintf(nMsg, zErrmsg,
   91847             "unable to open shared library [%s]", zFile);
   91848         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   91849       }
   91850     }
   91851     return SQLITE_ERROR;
   91852   }
   91853   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   91854                    sqlite3OsDlSym(pVfs, handle, zProc);
   91855   if( xInit==0 ){
   91856     if( pzErrMsg ){
   91857       nMsg += sqlite3Strlen30(zProc);
   91858       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   91859       if( zErrmsg ){
   91860         sqlite3_snprintf(nMsg, zErrmsg,
   91861             "no entry point [%s] in shared library [%s]", zProc,zFile);
   91862         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   91863       }
   91864       sqlite3OsDlClose(pVfs, handle);
   91865     }
   91866     return SQLITE_ERROR;
   91867   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   91868     if( pzErrMsg ){
   91869       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   91870     }
   91871     sqlite3_free(zErrmsg);
   91872     sqlite3OsDlClose(pVfs, handle);
   91873     return SQLITE_ERROR;
   91874   }
   91875 
   91876   /* Append the new shared library handle to the db->aExtension array. */
   91877   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   91878   if( aHandle==0 ){
   91879     return SQLITE_NOMEM;
   91880   }
   91881   if( db->nExtension>0 ){
   91882     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   91883   }
   91884   sqlite3DbFree(db, db->aExtension);
   91885   db->aExtension = aHandle;
   91886 
   91887   db->aExtension[db->nExtension++] = handle;
   91888   return SQLITE_OK;
   91889 }
   91890 SQLITE_API int sqlite3_load_extension(
   91891   sqlite3 *db,          /* Load the extension into this database connection */
   91892   const char *zFile,    /* Name of the shared library containing extension */
   91893   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   91894   char **pzErrMsg       /* Put error message here if not 0 */
   91895 ){
   91896   int rc;
   91897   sqlite3_mutex_enter(db->mutex);
   91898   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   91899   rc = sqlite3ApiExit(db, rc);
   91900   sqlite3_mutex_leave(db->mutex);
   91901   return rc;
   91902 }
   91903 
   91904 /*
   91905 ** Call this routine when the database connection is closing in order
   91906 ** to clean up loaded extensions
   91907 */
   91908 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   91909   int i;
   91910   assert( sqlite3_mutex_held(db->mutex) );
   91911   for(i=0; i<db->nExtension; i++){
   91912     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   91913   }
   91914   sqlite3DbFree(db, db->aExtension);
   91915 }
   91916 
   91917 /*
   91918 ** Enable or disable extension loading.  Extension loading is disabled by
   91919 ** default so as not to open security holes in older applications.
   91920 */
   91921 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   91922   sqlite3_mutex_enter(db->mutex);
   91923   if( onoff ){
   91924     db->flags |= SQLITE_LoadExtension;
   91925   }else{
   91926     db->flags &= ~SQLITE_LoadExtension;
   91927   }
   91928   sqlite3_mutex_leave(db->mutex);
   91929   return SQLITE_OK;
   91930 }
   91931 
   91932 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   91933 
   91934 /*
   91935 ** The auto-extension code added regardless of whether or not extension
   91936 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   91937 ** code if regular extension loading is not available.  This is that
   91938 ** dummy pointer.
   91939 */
   91940 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   91941 static const sqlite3_api_routines sqlite3Apis = { 0 };
   91942 #endif
   91943 
   91944 
   91945 /*
   91946 ** The following object holds the list of automatically loaded
   91947 ** extensions.
   91948 **
   91949 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   91950 ** mutex must be held while accessing this list.
   91951 */
   91952 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   91953 static SQLITE_WSD struct sqlite3AutoExtList {
   91954   int nExt;              /* Number of entries in aExt[] */
   91955   void (**aExt)(void);   /* Pointers to the extension init functions */
   91956 } sqlite3Autoext = { 0, 0 };
   91957 
   91958 /* The "wsdAutoext" macro will resolve to the autoextension
   91959 ** state vector.  If writable static data is unsupported on the target,
   91960 ** we have to locate the state vector at run-time.  In the more common
   91961 ** case where writable static data is supported, wsdStat can refer directly
   91962 ** to the "sqlite3Autoext" state vector declared above.
   91963 */
   91964 #ifdef SQLITE_OMIT_WSD
   91965 # define wsdAutoextInit \
   91966   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   91967 # define wsdAutoext x[0]
   91968 #else
   91969 # define wsdAutoextInit
   91970 # define wsdAutoext sqlite3Autoext
   91971 #endif
   91972 
   91973 
   91974 /*
   91975 ** Register a statically linked extension that is automatically
   91976 ** loaded by every new database connection.
   91977 */
   91978 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   91979   int rc = SQLITE_OK;
   91980 #ifndef SQLITE_OMIT_AUTOINIT
   91981   rc = sqlite3_initialize();
   91982   if( rc ){
   91983     return rc;
   91984   }else
   91985 #endif
   91986   {
   91987     int i;
   91988 #if SQLITE_THREADSAFE
   91989     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   91990 #endif
   91991     wsdAutoextInit;
   91992     sqlite3_mutex_enter(mutex);
   91993     for(i=0; i<wsdAutoext.nExt; i++){
   91994       if( wsdAutoext.aExt[i]==xInit ) break;
   91995     }
   91996     if( i==wsdAutoext.nExt ){
   91997       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   91998       void (**aNew)(void);
   91999       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   92000       if( aNew==0 ){
   92001         rc = SQLITE_NOMEM;
   92002       }else{
   92003         wsdAutoext.aExt = aNew;
   92004         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   92005         wsdAutoext.nExt++;
   92006       }
   92007     }
   92008     sqlite3_mutex_leave(mutex);
   92009     assert( (rc&0xff)==rc );
   92010     return rc;
   92011   }
   92012 }
   92013 
   92014 /*
   92015 ** Reset the automatic extension loading mechanism.
   92016 */
   92017 SQLITE_API void sqlite3_reset_auto_extension(void){
   92018 #ifndef SQLITE_OMIT_AUTOINIT
   92019   if( sqlite3_initialize()==SQLITE_OK )
   92020 #endif
   92021   {
   92022 #if SQLITE_THREADSAFE
   92023     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   92024 #endif
   92025     wsdAutoextInit;
   92026     sqlite3_mutex_enter(mutex);
   92027     sqlite3_free(wsdAutoext.aExt);
   92028     wsdAutoext.aExt = 0;
   92029     wsdAutoext.nExt = 0;
   92030     sqlite3_mutex_leave(mutex);
   92031   }
   92032 }
   92033 
   92034 /*
   92035 ** Load all automatic extensions.
   92036 **
   92037 ** If anything goes wrong, set an error in the database connection.
   92038 */
   92039 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   92040   int i;
   92041   int go = 1;
   92042   int rc;
   92043   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   92044 
   92045   wsdAutoextInit;
   92046   if( wsdAutoext.nExt==0 ){
   92047     /* Common case: early out without every having to acquire a mutex */
   92048     return;
   92049   }
   92050   for(i=0; go; i++){
   92051     char *zErrmsg;
   92052 #if SQLITE_THREADSAFE
   92053     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   92054 #endif
   92055     sqlite3_mutex_enter(mutex);
   92056     if( i>=wsdAutoext.nExt ){
   92057       xInit = 0;
   92058       go = 0;
   92059     }else{
   92060       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   92061               wsdAutoext.aExt[i];
   92062     }
   92063     sqlite3_mutex_leave(mutex);
   92064     zErrmsg = 0;
   92065     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
   92066       sqlite3Error(db, rc,
   92067             "automatic extension loading failed: %s", zErrmsg);
   92068       go = 0;
   92069     }
   92070     sqlite3_free(zErrmsg);
   92071   }
   92072 }
   92073 
   92074 /************** End of loadext.c *********************************************/
   92075 /************** Begin file pragma.c ******************************************/
   92076 /*
   92077 ** 2003 April 6
   92078 **
   92079 ** The author disclaims copyright to this source code.  In place of
   92080 ** a legal notice, here is a blessing:
   92081 **
   92082 **    May you do good and not evil.
   92083 **    May you find forgiveness for yourself and forgive others.
   92084 **    May you share freely, never taking more than you give.
   92085 **
   92086 *************************************************************************
   92087 ** This file contains code used to implement the PRAGMA command.
   92088 */
   92089 
   92090 /*
   92091 ** Interpret the given string as a safety level.  Return 0 for OFF,
   92092 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   92093 ** unrecognized string argument.  The FULL option is disallowed
   92094 ** if the omitFull parameter it 1.
   92095 **
   92096 ** Note that the values returned are one less that the values that
   92097 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   92098 ** to support legacy SQL code.  The safety level used to be boolean
   92099 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   92100 */
   92101 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
   92102                              /* 123456789 123456789 */
   92103   static const char zText[] = "onoffalseyestruefull";
   92104   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   92105   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   92106   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   92107   int i, n;
   92108   if( sqlite3Isdigit(*z) ){
   92109     return (u8)sqlite3Atoi(z);
   92110   }
   92111   n = sqlite3Strlen30(z);
   92112   for(i=0; i<ArraySize(iLength)-omitFull; i++){
   92113     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   92114       return iValue[i];
   92115     }
   92116   }
   92117   return dflt;
   92118 }
   92119 
   92120 /*
   92121 ** Interpret the given string as a boolean value.
   92122 */
   92123 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
   92124   return getSafetyLevel(z,1,dflt)!=0;
   92125 }
   92126 
   92127 /* The sqlite3GetBoolean() function is used by other modules but the
   92128 ** remainder of this file is specific to PRAGMA processing.  So omit
   92129 ** the rest of the file if PRAGMAs are omitted from the build.
   92130 */
   92131 #if !defined(SQLITE_OMIT_PRAGMA)
   92132 
   92133 /*
   92134 ** Interpret the given string as a locking mode value.
   92135 */
   92136 static int getLockingMode(const char *z){
   92137   if( z ){
   92138     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   92139     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   92140   }
   92141   return PAGER_LOCKINGMODE_QUERY;
   92142 }
   92143 
   92144 #ifndef SQLITE_OMIT_AUTOVACUUM
   92145 /*
   92146 ** Interpret the given string as an auto-vacuum mode value.
   92147 **
   92148 ** The following strings, "none", "full" and "incremental" are
   92149 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   92150 */
   92151 static int getAutoVacuum(const char *z){
   92152   int i;
   92153   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   92154   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   92155   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   92156   i = sqlite3Atoi(z);
   92157   return (u8)((i>=0&&i<=2)?i:0);
   92158 }
   92159 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   92160 
   92161 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92162 /*
   92163 ** Interpret the given string as a temp db location. Return 1 for file
   92164 ** backed temporary databases, 2 for the Red-Black tree in memory database
   92165 ** and 0 to use the compile-time default.
   92166 */
   92167 static int getTempStore(const char *z){
   92168   if( z[0]>='0' && z[0]<='2' ){
   92169     return z[0] - '0';
   92170   }else if( sqlite3StrICmp(z, "file")==0 ){
   92171     return 1;
   92172   }else if( sqlite3StrICmp(z, "memory")==0 ){
   92173     return 2;
   92174   }else{
   92175     return 0;
   92176   }
   92177 }
   92178 #endif /* SQLITE_PAGER_PRAGMAS */
   92179 
   92180 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92181 /*
   92182 ** Invalidate temp storage, either when the temp storage is changed
   92183 ** from default, or when 'file' and the temp_store_directory has changed
   92184 */
   92185 static int invalidateTempStorage(Parse *pParse){
   92186   sqlite3 *db = pParse->db;
   92187   if( db->aDb[1].pBt!=0 ){
   92188     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   92189       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   92190         "from within a transaction");
   92191       return SQLITE_ERROR;
   92192     }
   92193     sqlite3BtreeClose(db->aDb[1].pBt);
   92194     db->aDb[1].pBt = 0;
   92195     sqlite3ResetInternalSchema(db, -1);
   92196   }
   92197   return SQLITE_OK;
   92198 }
   92199 #endif /* SQLITE_PAGER_PRAGMAS */
   92200 
   92201 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92202 /*
   92203 ** If the TEMP database is open, close it and mark the database schema
   92204 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   92205 ** or DEFAULT_TEMP_STORE pragmas.
   92206 */
   92207 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   92208   int ts = getTempStore(zStorageType);
   92209   sqlite3 *db = pParse->db;
   92210   if( db->temp_store==ts ) return SQLITE_OK;
   92211   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   92212     return SQLITE_ERROR;
   92213   }
   92214   db->temp_store = (u8)ts;
   92215   return SQLITE_OK;
   92216 }
   92217 #endif /* SQLITE_PAGER_PRAGMAS */
   92218 
   92219 /*
   92220 ** Generate code to return a single integer value.
   92221 */
   92222 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   92223   Vdbe *v = sqlite3GetVdbe(pParse);
   92224   int mem = ++pParse->nMem;
   92225   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   92226   if( pI64 ){
   92227     memcpy(pI64, &value, sizeof(value));
   92228   }
   92229   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   92230   sqlite3VdbeSetNumCols(v, 1);
   92231   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   92232   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   92233 }
   92234 
   92235 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   92236 /*
   92237 ** Check to see if zRight and zLeft refer to a pragma that queries
   92238 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
   92239 ** Also, implement the pragma.
   92240 */
   92241 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
   92242   static const struct sPragmaType {
   92243     const char *zName;  /* Name of the pragma */
   92244     int mask;           /* Mask for the db->flags value */
   92245   } aPragma[] = {
   92246     { "full_column_names",        SQLITE_FullColNames  },
   92247     { "short_column_names",       SQLITE_ShortColNames },
   92248     { "count_changes",            SQLITE_CountRows     },
   92249     { "empty_result_callbacks",   SQLITE_NullCallback  },
   92250     { "legacy_file_format",       SQLITE_LegacyFileFmt },
   92251     { "fullfsync",                SQLITE_FullFSync     },
   92252     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
   92253     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
   92254 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   92255     { "automatic_index",          SQLITE_AutoIndex     },
   92256 #endif
   92257 #ifdef SQLITE_DEBUG
   92258     { "sql_trace",                SQLITE_SqlTrace      },
   92259     { "vdbe_listing",             SQLITE_VdbeListing   },
   92260     { "vdbe_trace",               SQLITE_VdbeTrace     },
   92261 #endif
   92262 #ifndef SQLITE_OMIT_CHECK
   92263     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
   92264 #endif
   92265     /* The following is VERY experimental */
   92266     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
   92267 
   92268     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
   92269     ** flag if there are any active statements. */
   92270     { "read_uncommitted",         SQLITE_ReadUncommitted },
   92271     { "recursive_triggers",       SQLITE_RecTriggers },
   92272 
   92273     /* This flag may only be set if both foreign-key and trigger support
   92274     ** are present in the build.  */
   92275 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   92276     { "foreign_keys",             SQLITE_ForeignKeys },
   92277 #endif
   92278   };
   92279   int i;
   92280   const struct sPragmaType *p;
   92281   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
   92282     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
   92283       sqlite3 *db = pParse->db;
   92284       Vdbe *v;
   92285       v = sqlite3GetVdbe(pParse);
   92286       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
   92287       if( ALWAYS(v) ){
   92288         if( zRight==0 ){
   92289           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
   92290         }else{
   92291           int mask = p->mask;          /* Mask of bits to set or clear. */
   92292           if( db->autoCommit==0 ){
   92293             /* Foreign key support may not be enabled or disabled while not
   92294             ** in auto-commit mode.  */
   92295             mask &= ~(SQLITE_ForeignKeys);
   92296           }
   92297 
   92298           if( sqlite3GetBoolean(zRight, 0) ){
   92299             db->flags |= mask;
   92300           }else{
   92301             db->flags &= ~mask;
   92302           }
   92303 
   92304           /* Many of the flag-pragmas modify the code generated by the SQL
   92305           ** compiler (eg. count_changes). So add an opcode to expire all
   92306           ** compiled SQL statements after modifying a pragma value.
   92307           */
   92308           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   92309         }
   92310       }
   92311 
   92312       return 1;
   92313     }
   92314   }
   92315   return 0;
   92316 }
   92317 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   92318 
   92319 /*
   92320 ** Return a human-readable name for a constraint resolution action.
   92321 */
   92322 #ifndef SQLITE_OMIT_FOREIGN_KEY
   92323 static const char *actionName(u8 action){
   92324   const char *zName;
   92325   switch( action ){
   92326     case OE_SetNull:  zName = "SET NULL";        break;
   92327     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   92328     case OE_Cascade:  zName = "CASCADE";         break;
   92329     case OE_Restrict: zName = "RESTRICT";        break;
   92330     default:          zName = "NO ACTION";
   92331                       assert( action==OE_None ); break;
   92332   }
   92333   return zName;
   92334 }
   92335 #endif
   92336 
   92337 
   92338 /*
   92339 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   92340 ** defined in pager.h. This function returns the associated lowercase
   92341 ** journal-mode name.
   92342 */
   92343 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   92344   static char * const azModeName[] = {
   92345     "delete", "persist", "off", "truncate", "memory"
   92346 #ifndef SQLITE_OMIT_WAL
   92347      , "wal"
   92348 #endif
   92349   };
   92350   assert( PAGER_JOURNALMODE_DELETE==0 );
   92351   assert( PAGER_JOURNALMODE_PERSIST==1 );
   92352   assert( PAGER_JOURNALMODE_OFF==2 );
   92353   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   92354   assert( PAGER_JOURNALMODE_MEMORY==4 );
   92355   assert( PAGER_JOURNALMODE_WAL==5 );
   92356   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   92357 
   92358   if( eMode==ArraySize(azModeName) ) return 0;
   92359   return azModeName[eMode];
   92360 }
   92361 
   92362 /*
   92363 ** Process a pragma statement.
   92364 **
   92365 ** Pragmas are of this form:
   92366 **
   92367 **      PRAGMA [database.]id [= value]
   92368 **
   92369 ** The identifier might also be a string.  The value is a string, and
   92370 ** identifier, or a number.  If minusFlag is true, then the value is
   92371 ** a number that was preceded by a minus sign.
   92372 **
   92373 ** If the left side is "database.id" then pId1 is the database name
   92374 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   92375 ** id and pId2 is any empty string.
   92376 */
   92377 SQLITE_PRIVATE void sqlite3Pragma(
   92378   Parse *pParse,
   92379   Token *pId1,        /* First part of [database.]id field */
   92380   Token *pId2,        /* Second part of [database.]id field, or NULL */
   92381   Token *pValue,      /* Token for <value>, or NULL */
   92382   int minusFlag       /* True if a '-' sign preceded <value> */
   92383 ){
   92384   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   92385   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   92386   const char *zDb = 0;   /* The database name */
   92387   Token *pId;            /* Pointer to <id> token */
   92388   int iDb;               /* Database index for <database> */
   92389   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
   92390   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
   92391   sqlite3 *db = pParse->db;    /* The database connection */
   92392   Db *pDb;                     /* The specific database being pragmaed */
   92393   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
   92394 
   92395   if( v==0 ) return;
   92396   sqlite3VdbeRunOnlyOnce(v);
   92397   pParse->nMem = 2;
   92398 
   92399   /* Interpret the [database.] part of the pragma statement. iDb is the
   92400   ** index of the database this pragma is being applied to in db.aDb[]. */
   92401   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   92402   if( iDb<0 ) return;
   92403   pDb = &db->aDb[iDb];
   92404 
   92405   /* If the temp database has been explicitly named as part of the
   92406   ** pragma, make sure it is open.
   92407   */
   92408   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   92409     return;
   92410   }
   92411 
   92412   zLeft = sqlite3NameFromToken(db, pId);
   92413   if( !zLeft ) return;
   92414   if( minusFlag ){
   92415     zRight = sqlite3MPrintf(db, "-%T", pValue);
   92416   }else{
   92417     zRight = sqlite3NameFromToken(db, pValue);
   92418   }
   92419 
   92420   assert( pId2 );
   92421   zDb = pId2->n>0 ? pDb->zName : 0;
   92422   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   92423     goto pragma_out;
   92424   }
   92425 
   92426   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
   92427   ** connection.  If it returns SQLITE_OK, then assume that the VFS
   92428   ** handled the pragma and generate a no-op prepared statement.
   92429   */
   92430   aFcntl[0] = 0;
   92431   aFcntl[1] = zLeft;
   92432   aFcntl[2] = zRight;
   92433   aFcntl[3] = 0;
   92434   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
   92435   if( rc==SQLITE_OK ){
   92436     if( aFcntl[0] ){
   92437       int mem = ++pParse->nMem;
   92438       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
   92439       sqlite3VdbeSetNumCols(v, 1);
   92440       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
   92441       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   92442       sqlite3_free(aFcntl[0]);
   92443     }
   92444   }else if( rc!=SQLITE_NOTFOUND ){
   92445     if( aFcntl[0] ){
   92446       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
   92447       sqlite3_free(aFcntl[0]);
   92448     }
   92449     pParse->nErr++;
   92450     pParse->rc = rc;
   92451   }else
   92452 
   92453 
   92454 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   92455   /*
   92456   **  PRAGMA [database.]default_cache_size
   92457   **  PRAGMA [database.]default_cache_size=N
   92458   **
   92459   ** The first form reports the current persistent setting for the
   92460   ** page cache size.  The value returned is the maximum number of
   92461   ** pages in the page cache.  The second form sets both the current
   92462   ** page cache size value and the persistent page cache size value
   92463   ** stored in the database file.
   92464   **
   92465   ** Older versions of SQLite would set the default cache size to a
   92466   ** negative number to indicate synchronous=OFF.  These days, synchronous
   92467   ** is always on by default regardless of the sign of the default cache
   92468   ** size.  But continue to take the absolute value of the default cache
   92469   ** size of historical compatibility.
   92470   */
   92471   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
   92472     static const VdbeOpList getCacheSize[] = {
   92473       { OP_Transaction, 0, 0,        0},                         /* 0 */
   92474       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   92475       { OP_IfPos,       1, 7,        0},
   92476       { OP_Integer,     0, 2,        0},
   92477       { OP_Subtract,    1, 2,        1},
   92478       { OP_IfPos,       1, 7,        0},
   92479       { OP_Integer,     0, 1,        0},                         /* 6 */
   92480       { OP_ResultRow,   1, 1,        0},
   92481     };
   92482     int addr;
   92483     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92484     sqlite3VdbeUsesBtree(v, iDb);
   92485     if( !zRight ){
   92486       sqlite3VdbeSetNumCols(v, 1);
   92487       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   92488       pParse->nMem += 2;
   92489       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
   92490       sqlite3VdbeChangeP1(v, addr, iDb);
   92491       sqlite3VdbeChangeP1(v, addr+1, iDb);
   92492       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   92493     }else{
   92494       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   92495       sqlite3BeginWriteOperation(pParse, 0, iDb);
   92496       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   92497       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   92498       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   92499       pDb->pSchema->cache_size = size;
   92500       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   92501     }
   92502   }else
   92503 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   92504 
   92505 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   92506   /*
   92507   **  PRAGMA [database.]page_size
   92508   **  PRAGMA [database.]page_size=N
   92509   **
   92510   ** The first form reports the current setting for the
   92511   ** database page size in bytes.  The second form sets the
   92512   ** database page size value.  The value can only be set if
   92513   ** the database has not yet been created.
   92514   */
   92515   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
   92516     Btree *pBt = pDb->pBt;
   92517     assert( pBt!=0 );
   92518     if( !zRight ){
   92519       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   92520       returnSingleInt(pParse, "page_size", size);
   92521     }else{
   92522       /* Malloc may fail when setting the page-size, as there is an internal
   92523       ** buffer that the pager module resizes using sqlite3_realloc().
   92524       */
   92525       db->nextPagesize = sqlite3Atoi(zRight);
   92526       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   92527         db->mallocFailed = 1;
   92528       }
   92529     }
   92530   }else
   92531 
   92532   /*
   92533   **  PRAGMA [database.]secure_delete
   92534   **  PRAGMA [database.]secure_delete=ON/OFF
   92535   **
   92536   ** The first form reports the current setting for the
   92537   ** secure_delete flag.  The second form changes the secure_delete
   92538   ** flag setting and reports thenew value.
   92539   */
   92540   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
   92541     Btree *pBt = pDb->pBt;
   92542     int b = -1;
   92543     assert( pBt!=0 );
   92544     if( zRight ){
   92545       b = sqlite3GetBoolean(zRight, 0);
   92546     }
   92547     if( pId2->n==0 && b>=0 ){
   92548       int ii;
   92549       for(ii=0; ii<db->nDb; ii++){
   92550         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   92551       }
   92552     }
   92553     b = sqlite3BtreeSecureDelete(pBt, b);
   92554     returnSingleInt(pParse, "secure_delete", b);
   92555   }else
   92556 
   92557   /*
   92558   **  PRAGMA [database.]max_page_count
   92559   **  PRAGMA [database.]max_page_count=N
   92560   **
   92561   ** The first form reports the current setting for the
   92562   ** maximum number of pages in the database file.  The
   92563   ** second form attempts to change this setting.  Both
   92564   ** forms return the current setting.
   92565   **
   92566   ** The absolute value of N is used.  This is undocumented and might
   92567   ** change.  The only purpose is to provide an easy way to test
   92568   ** the sqlite3AbsInt32() function.
   92569   **
   92570   **  PRAGMA [database.]page_count
   92571   **
   92572   ** Return the number of pages in the specified database.
   92573   */
   92574   if( sqlite3StrICmp(zLeft,"page_count")==0
   92575    || sqlite3StrICmp(zLeft,"max_page_count")==0
   92576   ){
   92577     int iReg;
   92578     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92579     sqlite3CodeVerifySchema(pParse, iDb);
   92580     iReg = ++pParse->nMem;
   92581     if( sqlite3Tolower(zLeft[0])=='p' ){
   92582       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   92583     }else{
   92584       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
   92585                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
   92586     }
   92587     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   92588     sqlite3VdbeSetNumCols(v, 1);
   92589     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   92590   }else
   92591 
   92592   /*
   92593   **  PRAGMA [database.]locking_mode
   92594   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   92595   */
   92596   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
   92597     const char *zRet = "normal";
   92598     int eMode = getLockingMode(zRight);
   92599 
   92600     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   92601       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   92602       ** the current default locking mode (which may be different to
   92603       ** the locking-mode of the main database).
   92604       */
   92605       eMode = db->dfltLockMode;
   92606     }else{
   92607       Pager *pPager;
   92608       if( pId2->n==0 ){
   92609         /* This indicates that no database name was specified as part
   92610         ** of the PRAGMA command. In this case the locking-mode must be
   92611         ** set on all attached databases, as well as the main db file.
   92612         **
   92613         ** Also, the sqlite3.dfltLockMode variable is set so that
   92614         ** any subsequently attached databases also use the specified
   92615         ** locking mode.
   92616         */
   92617         int ii;
   92618         assert(pDb==&db->aDb[0]);
   92619         for(ii=2; ii<db->nDb; ii++){
   92620           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   92621           sqlite3PagerLockingMode(pPager, eMode);
   92622         }
   92623         db->dfltLockMode = (u8)eMode;
   92624       }
   92625       pPager = sqlite3BtreePager(pDb->pBt);
   92626       eMode = sqlite3PagerLockingMode(pPager, eMode);
   92627     }
   92628 
   92629     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
   92630     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   92631       zRet = "exclusive";
   92632     }
   92633     sqlite3VdbeSetNumCols(v, 1);
   92634     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   92635     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   92636     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92637   }else
   92638 
   92639   /*
   92640   **  PRAGMA [database.]journal_mode
   92641   **  PRAGMA [database.]journal_mode =
   92642   **                      (delete|persist|off|truncate|memory|wal|off)
   92643   */
   92644   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
   92645     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   92646     int ii;           /* Loop counter */
   92647 
   92648     /* Force the schema to be loaded on all databases.  This causes all
   92649     ** database files to be opened and the journal_modes set.  This is
   92650     ** necessary because subsequent processing must know if the databases
   92651     ** are in WAL mode. */
   92652     if( sqlite3ReadSchema(pParse) ){
   92653       goto pragma_out;
   92654     }
   92655 
   92656     sqlite3VdbeSetNumCols(v, 1);
   92657     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   92658 
   92659     if( zRight==0 ){
   92660       /* If there is no "=MODE" part of the pragma, do a query for the
   92661       ** current mode */
   92662       eMode = PAGER_JOURNALMODE_QUERY;
   92663     }else{
   92664       const char *zMode;
   92665       int n = sqlite3Strlen30(zRight);
   92666       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   92667         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   92668       }
   92669       if( !zMode ){
   92670         /* If the "=MODE" part does not match any known journal mode,
   92671         ** then do a query */
   92672         eMode = PAGER_JOURNALMODE_QUERY;
   92673       }
   92674     }
   92675     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   92676       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   92677       iDb = 0;
   92678       pId2->n = 1;
   92679     }
   92680     for(ii=db->nDb-1; ii>=0; ii--){
   92681       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   92682         sqlite3VdbeUsesBtree(v, ii);
   92683         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   92684       }
   92685     }
   92686     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92687   }else
   92688 
   92689   /*
   92690   **  PRAGMA [database.]journal_size_limit
   92691   **  PRAGMA [database.]journal_size_limit=N
   92692   **
   92693   ** Get or set the size limit on rollback journal files.
   92694   */
   92695   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
   92696     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92697     i64 iLimit = -2;
   92698     if( zRight ){
   92699       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
   92700       if( iLimit<-1 ) iLimit = -1;
   92701     }
   92702     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   92703     returnSingleInt(pParse, "journal_size_limit", iLimit);
   92704   }else
   92705 
   92706 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   92707 
   92708   /*
   92709   **  PRAGMA [database.]auto_vacuum
   92710   **  PRAGMA [database.]auto_vacuum=N
   92711   **
   92712   ** Get or set the value of the database 'auto-vacuum' parameter.
   92713   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   92714   */
   92715 #ifndef SQLITE_OMIT_AUTOVACUUM
   92716   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
   92717     Btree *pBt = pDb->pBt;
   92718     assert( pBt!=0 );
   92719     if( sqlite3ReadSchema(pParse) ){
   92720       goto pragma_out;
   92721     }
   92722     if( !zRight ){
   92723       int auto_vacuum;
   92724       if( ALWAYS(pBt) ){
   92725          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
   92726       }else{
   92727          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
   92728       }
   92729       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
   92730     }else{
   92731       int eAuto = getAutoVacuum(zRight);
   92732       assert( eAuto>=0 && eAuto<=2 );
   92733       db->nextAutovac = (u8)eAuto;
   92734       if( ALWAYS(eAuto>=0) ){
   92735         /* Call SetAutoVacuum() to set initialize the internal auto and
   92736         ** incr-vacuum flags. This is required in case this connection
   92737         ** creates the database file. It is important that it is created
   92738         ** as an auto-vacuum capable db.
   92739         */
   92740         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   92741         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   92742           /* When setting the auto_vacuum mode to either "full" or
   92743           ** "incremental", write the value of meta[6] in the database
   92744           ** file. Before writing to meta[6], check that meta[3] indicates
   92745           ** that this really is an auto-vacuum capable database.
   92746           */
   92747           static const VdbeOpList setMeta6[] = {
   92748             { OP_Transaction,    0,         1,                 0},    /* 0 */
   92749             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   92750             { OP_If,             1,         0,                 0},    /* 2 */
   92751             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   92752             { OP_Integer,        0,         1,                 0},    /* 4 */
   92753             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   92754           };
   92755           int iAddr;
   92756           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
   92757           sqlite3VdbeChangeP1(v, iAddr, iDb);
   92758           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   92759           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   92760           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   92761           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   92762           sqlite3VdbeUsesBtree(v, iDb);
   92763         }
   92764       }
   92765     }
   92766   }else
   92767 #endif
   92768 
   92769   /*
   92770   **  PRAGMA [database.]incremental_vacuum(N)
   92771   **
   92772   ** Do N steps of incremental vacuuming on a database.
   92773   */
   92774 #ifndef SQLITE_OMIT_AUTOVACUUM
   92775   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
   92776     int iLimit, addr;
   92777     if( sqlite3ReadSchema(pParse) ){
   92778       goto pragma_out;
   92779     }
   92780     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   92781       iLimit = 0x7fffffff;
   92782     }
   92783     sqlite3BeginWriteOperation(pParse, 0, iDb);
   92784     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   92785     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
   92786     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   92787     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   92788     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
   92789     sqlite3VdbeJumpHere(v, addr);
   92790   }else
   92791 #endif
   92792 
   92793 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   92794   /*
   92795   **  PRAGMA [database.]cache_size
   92796   **  PRAGMA [database.]cache_size=N
   92797   **
   92798   ** The first form reports the current local setting for the
   92799   ** page cache size. The second form sets the local
   92800   ** page cache size value.  If N is positive then that is the
   92801   ** number of pages in the cache.  If N is negative, then the
   92802   ** number of pages is adjusted so that the cache uses -N kibibytes
   92803   ** of memory.
   92804   */
   92805   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
   92806     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92807     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   92808     if( !zRight ){
   92809       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   92810     }else{
   92811       int size = sqlite3Atoi(zRight);
   92812       pDb->pSchema->cache_size = size;
   92813       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   92814     }
   92815   }else
   92816 
   92817   /*
   92818   **   PRAGMA temp_store
   92819   **   PRAGMA temp_store = "default"|"memory"|"file"
   92820   **
   92821   ** Return or set the local value of the temp_store flag.  Changing
   92822   ** the local value does not make changes to the disk file and the default
   92823   ** value will be restored the next time the database is opened.
   92824   **
   92825   ** Note that it is possible for the library compile-time options to
   92826   ** override this setting
   92827   */
   92828   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
   92829     if( !zRight ){
   92830       returnSingleInt(pParse, "temp_store", db->temp_store);
   92831     }else{
   92832       changeTempStorage(pParse, zRight);
   92833     }
   92834   }else
   92835 
   92836   /*
   92837   **   PRAGMA temp_store_directory
   92838   **   PRAGMA temp_store_directory = ""|"directory_name"
   92839   **
   92840   ** Return or set the local value of the temp_store_directory flag.  Changing
   92841   ** the value sets a specific directory to be used for temporary files.
   92842   ** Setting to a null string reverts to the default temporary directory search.
   92843   ** If temporary directory is changed, then invalidateTempStorage.
   92844   **
   92845   */
   92846   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
   92847     if( !zRight ){
   92848       if( sqlite3_temp_directory ){
   92849         sqlite3VdbeSetNumCols(v, 1);
   92850         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   92851             "temp_store_directory", SQLITE_STATIC);
   92852         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   92853         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92854       }
   92855     }else{
   92856 #ifndef SQLITE_OMIT_WSD
   92857       if( zRight[0] ){
   92858         int res;
   92859         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   92860         if( rc!=SQLITE_OK || res==0 ){
   92861           sqlite3ErrorMsg(pParse, "not a writable directory");
   92862           goto pragma_out;
   92863         }
   92864       }
   92865       if( SQLITE_TEMP_STORE==0
   92866        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   92867        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   92868       ){
   92869         invalidateTempStorage(pParse);
   92870       }
   92871       sqlite3_free(sqlite3_temp_directory);
   92872       if( zRight[0] ){
   92873         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   92874       }else{
   92875         sqlite3_temp_directory = 0;
   92876       }
   92877 #endif /* SQLITE_OMIT_WSD */
   92878     }
   92879   }else
   92880 
   92881 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   92882 #  if defined(__APPLE__)
   92883 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   92884 #  else
   92885 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   92886 #  endif
   92887 #endif
   92888 #if SQLITE_ENABLE_LOCKING_STYLE
   92889   /*
   92890    **   PRAGMA [database.]lock_proxy_file
   92891    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   92892    **
   92893    ** Return or set the value of the lock_proxy_file flag.  Changing
   92894    ** the value sets a specific file to be used for database access locks.
   92895    **
   92896    */
   92897   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
   92898     if( !zRight ){
   92899       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92900       char *proxy_file_path = NULL;
   92901       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   92902       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
   92903                            &proxy_file_path);
   92904 
   92905       if( proxy_file_path ){
   92906         sqlite3VdbeSetNumCols(v, 1);
   92907         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   92908                               "lock_proxy_file", SQLITE_STATIC);
   92909         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   92910         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   92911       }
   92912     }else{
   92913       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   92914       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   92915       int res;
   92916       if( zRight[0] ){
   92917         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   92918                                      zRight);
   92919       } else {
   92920         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   92921                                      NULL);
   92922       }
   92923       if( res!=SQLITE_OK ){
   92924         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   92925         goto pragma_out;
   92926       }
   92927     }
   92928   }else
   92929 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   92930 
   92931   /*
   92932   **   PRAGMA [database.]synchronous
   92933   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   92934   **
   92935   ** Return or set the local value of the synchronous flag.  Changing
   92936   ** the local value does not make changes to the disk file and the
   92937   ** default value will be restored the next time the database is
   92938   ** opened.
   92939   */
   92940   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
   92941     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92942     if( !zRight ){
   92943       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   92944     }else{
   92945       if( !db->autoCommit ){
   92946         sqlite3ErrorMsg(pParse,
   92947             "Safety level may not be changed inside a transaction");
   92948       }else{
   92949         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
   92950       }
   92951     }
   92952   }else
   92953 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   92954 
   92955 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   92956   if( flagPragma(pParse, zLeft, zRight) ){
   92957     /* The flagPragma() subroutine also generates any necessary code
   92958     ** there is nothing more to do here */
   92959   }else
   92960 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   92961 
   92962 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   92963   /*
   92964   **   PRAGMA table_info(<table>)
   92965   **
   92966   ** Return a single row for each column of the named table. The columns of
   92967   ** the returned data set are:
   92968   **
   92969   ** cid:        Column id (numbered from left to right, starting at 0)
   92970   ** name:       Column name
   92971   ** type:       Column declaration type.
   92972   ** notnull:    True if 'NOT NULL' is part of column declaration
   92973   ** dflt_value: The default value for the column, if any.
   92974   */
   92975   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
   92976     Table *pTab;
   92977     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   92978     pTab = sqlite3FindTable(db, zRight, zDb);
   92979     if( pTab ){
   92980       int i;
   92981       int nHidden = 0;
   92982       Column *pCol;
   92983       sqlite3VdbeSetNumCols(v, 6);
   92984       pParse->nMem = 6;
   92985       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   92986       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   92987       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   92988       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   92989       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   92990       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   92991       sqlite3ViewGetColumnNames(pParse, pTab);
   92992       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   92993         if( IsHiddenColumn(pCol) ){
   92994           nHidden++;
   92995           continue;
   92996         }
   92997         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   92998         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   92999         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93000            pCol->zType ? pCol->zType : "", 0);
   93001         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   93002         if( pCol->zDflt ){
   93003           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   93004         }else{
   93005           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   93006         }
   93007         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
   93008         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   93009       }
   93010     }
   93011   }else
   93012 
   93013   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
   93014     Index *pIdx;
   93015     Table *pTab;
   93016     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93017     pIdx = sqlite3FindIndex(db, zRight, zDb);
   93018     if( pIdx ){
   93019       int i;
   93020       pTab = pIdx->pTable;
   93021       sqlite3VdbeSetNumCols(v, 3);
   93022       pParse->nMem = 3;
   93023       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   93024       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   93025       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   93026       for(i=0; i<pIdx->nColumn; i++){
   93027         int cnum = pIdx->aiColumn[i];
   93028         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93029         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   93030         assert( pTab->nCol>cnum );
   93031         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   93032         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93033       }
   93034     }
   93035   }else
   93036 
   93037   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
   93038     Index *pIdx;
   93039     Table *pTab;
   93040     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93041     pTab = sqlite3FindTable(db, zRight, zDb);
   93042     if( pTab ){
   93043       v = sqlite3GetVdbe(pParse);
   93044       pIdx = pTab->pIndex;
   93045       if( pIdx ){
   93046         int i = 0;
   93047         sqlite3VdbeSetNumCols(v, 3);
   93048         pParse->nMem = 3;
   93049         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93050         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93051         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   93052         while(pIdx){
   93053           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93054           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   93055           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
   93056           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93057           ++i;
   93058           pIdx = pIdx->pNext;
   93059         }
   93060       }
   93061     }
   93062   }else
   93063 
   93064   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
   93065     int i;
   93066     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93067     sqlite3VdbeSetNumCols(v, 3);
   93068     pParse->nMem = 3;
   93069     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93070     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93071     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   93072     for(i=0; i<db->nDb; i++){
   93073       if( db->aDb[i].pBt==0 ) continue;
   93074       assert( db->aDb[i].zName!=0 );
   93075       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93076       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   93077       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93078            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   93079       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93080     }
   93081   }else
   93082 
   93083   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
   93084     int i = 0;
   93085     HashElem *p;
   93086     sqlite3VdbeSetNumCols(v, 2);
   93087     pParse->nMem = 2;
   93088     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   93089     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   93090     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   93091       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   93092       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   93093       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   93094       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   93095     }
   93096   }else
   93097 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   93098 
   93099 #ifndef SQLITE_OMIT_FOREIGN_KEY
   93100   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
   93101     FKey *pFK;
   93102     Table *pTab;
   93103     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93104     pTab = sqlite3FindTable(db, zRight, zDb);
   93105     if( pTab ){
   93106       v = sqlite3GetVdbe(pParse);
   93107       pFK = pTab->pFKey;
   93108       if( pFK ){
   93109         int i = 0;
   93110         sqlite3VdbeSetNumCols(v, 8);
   93111         pParse->nMem = 8;
   93112         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   93113         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   93114         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   93115         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   93116         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   93117         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   93118         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   93119         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   93120         while(pFK){
   93121           int j;
   93122           for(j=0; j<pFK->nCol; j++){
   93123             char *zCol = pFK->aCol[j].zCol;
   93124             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   93125             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   93126             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   93127             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   93128             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   93129             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   93130                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   93131             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   93132             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   93133             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   93134             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   93135             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   93136           }
   93137           ++i;
   93138           pFK = pFK->pNextFrom;
   93139         }
   93140       }
   93141     }
   93142   }else
   93143 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   93144 
   93145 #ifndef NDEBUG
   93146   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
   93147     if( zRight ){
   93148       if( sqlite3GetBoolean(zRight, 0) ){
   93149         sqlite3ParserTrace(stderr, "parser: ");
   93150       }else{
   93151         sqlite3ParserTrace(0, 0);
   93152       }
   93153     }
   93154   }else
   93155 #endif
   93156 
   93157   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   93158   ** used will be case sensitive or not depending on the RHS.
   93159   */
   93160   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
   93161     if( zRight ){
   93162       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
   93163     }
   93164   }else
   93165 
   93166 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   93167 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   93168 #endif
   93169 
   93170 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   93171   /* Pragma "quick_check" is an experimental reduced version of
   93172   ** integrity_check designed to detect most database corruption
   93173   ** without most of the overhead of a full integrity-check.
   93174   */
   93175   if( sqlite3StrICmp(zLeft, "integrity_check")==0
   93176    || sqlite3StrICmp(zLeft, "quick_check")==0
   93177   ){
   93178     int i, j, addr, mxErr;
   93179 
   93180     /* Code that appears at the end of the integrity check.  If no error
   93181     ** messages have been generated, output OK.  Otherwise output the
   93182     ** error message
   93183     */
   93184     static const VdbeOpList endCode[] = {
   93185       { OP_AddImm,      1, 0,        0},    /* 0 */
   93186       { OP_IfNeg,       1, 0,        0},    /* 1 */
   93187       { OP_String8,     0, 3,        0},    /* 2 */
   93188       { OP_ResultRow,   3, 1,        0},
   93189     };
   93190 
   93191     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
   93192 
   93193     /* Initialize the VDBE program */
   93194     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93195     pParse->nMem = 6;
   93196     sqlite3VdbeSetNumCols(v, 1);
   93197     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   93198 
   93199     /* Set the maximum error count */
   93200     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   93201     if( zRight ){
   93202       sqlite3GetInt32(zRight, &mxErr);
   93203       if( mxErr<=0 ){
   93204         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   93205       }
   93206     }
   93207     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   93208 
   93209     /* Do an integrity check on each database file */
   93210     for(i=0; i<db->nDb; i++){
   93211       HashElem *x;
   93212       Hash *pTbls;
   93213       int cnt = 0;
   93214 
   93215       if( OMIT_TEMPDB && i==1 ) continue;
   93216 
   93217       sqlite3CodeVerifySchema(pParse, i);
   93218       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   93219       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93220       sqlite3VdbeJumpHere(v, addr);
   93221 
   93222       /* Do an integrity check of the B-Tree
   93223       **
   93224       ** Begin by filling registers 2, 3, ... with the root pages numbers
   93225       ** for all tables and indices in the database.
   93226       */
   93227       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   93228       pTbls = &db->aDb[i].pSchema->tblHash;
   93229       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   93230         Table *pTab = sqliteHashData(x);
   93231         Index *pIdx;
   93232         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   93233         cnt++;
   93234         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   93235           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   93236           cnt++;
   93237         }
   93238       }
   93239 
   93240       /* Make sure sufficient number of registers have been allocated */
   93241       if( pParse->nMem < cnt+4 ){
   93242         pParse->nMem = cnt+4;
   93243       }
   93244 
   93245       /* Do the b-tree integrity checks */
   93246       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   93247       sqlite3VdbeChangeP5(v, (u8)i);
   93248       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
   93249       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   93250          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   93251          P4_DYNAMIC);
   93252       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   93253       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   93254       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   93255       sqlite3VdbeJumpHere(v, addr);
   93256 
   93257       /* Make sure all the indices are constructed correctly.
   93258       */
   93259       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   93260         Table *pTab = sqliteHashData(x);
   93261         Index *pIdx;
   93262         int loopTop;
   93263 
   93264         if( pTab->pIndex==0 ) continue;
   93265         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   93266         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93267         sqlite3VdbeJumpHere(v, addr);
   93268         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
   93269         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
   93270         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
   93271         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
   93272         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   93273           int jmp2;
   93274           int r1;
   93275           static const VdbeOpList idxErr[] = {
   93276             { OP_AddImm,      1, -1,  0},
   93277             { OP_String8,     0,  3,  0},    /* 1 */
   93278             { OP_Rowid,       1,  4,  0},
   93279             { OP_String8,     0,  5,  0},    /* 3 */
   93280             { OP_String8,     0,  6,  0},    /* 4 */
   93281             { OP_Concat,      4,  3,  3},
   93282             { OP_Concat,      5,  3,  3},
   93283             { OP_Concat,      6,  3,  3},
   93284             { OP_ResultRow,   3,  1,  0},
   93285             { OP_IfPos,       1,  0,  0},    /* 9 */
   93286             { OP_Halt,        0,  0,  0},
   93287           };
   93288           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
   93289           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
   93290           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
   93291           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
   93292           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
   93293           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
   93294           sqlite3VdbeJumpHere(v, addr+9);
   93295           sqlite3VdbeJumpHere(v, jmp2);
   93296         }
   93297         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
   93298         sqlite3VdbeJumpHere(v, loopTop);
   93299         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   93300           static const VdbeOpList cntIdx[] = {
   93301              { OP_Integer,      0,  3,  0},
   93302              { OP_Rewind,       0,  0,  0},  /* 1 */
   93303              { OP_AddImm,       3,  1,  0},
   93304              { OP_Next,         0,  0,  0},  /* 3 */
   93305              { OP_Eq,           2,  0,  3},  /* 4 */
   93306              { OP_AddImm,       1, -1,  0},
   93307              { OP_String8,      0,  2,  0},  /* 6 */
   93308              { OP_String8,      0,  3,  0},  /* 7 */
   93309              { OP_Concat,       3,  2,  2},
   93310              { OP_ResultRow,    2,  1,  0},
   93311           };
   93312           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
   93313           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   93314           sqlite3VdbeJumpHere(v, addr);
   93315           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
   93316           sqlite3VdbeChangeP1(v, addr+1, j+2);
   93317           sqlite3VdbeChangeP2(v, addr+1, addr+4);
   93318           sqlite3VdbeChangeP1(v, addr+3, j+2);
   93319           sqlite3VdbeChangeP2(v, addr+3, addr+2);
   93320           sqlite3VdbeJumpHere(v, addr+4);
   93321           sqlite3VdbeChangeP4(v, addr+6,
   93322                      "wrong # of entries in index ", P4_STATIC);
   93323           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
   93324         }
   93325       }
   93326     }
   93327     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
   93328     sqlite3VdbeChangeP2(v, addr, -mxErr);
   93329     sqlite3VdbeJumpHere(v, addr+1);
   93330     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
   93331   }else
   93332 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   93333 
   93334 #ifndef SQLITE_OMIT_UTF16
   93335   /*
   93336   **   PRAGMA encoding
   93337   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   93338   **
   93339   ** In its first form, this pragma returns the encoding of the main
   93340   ** database. If the database is not initialized, it is initialized now.
   93341   **
   93342   ** The second form of this pragma is a no-op if the main database file
   93343   ** has not already been initialized. In this case it sets the default
   93344   ** encoding that will be used for the main database file if a new file
   93345   ** is created. If an existing main database file is opened, then the
   93346   ** default text encoding for the existing database is used.
   93347   **
   93348   ** In all cases new databases created using the ATTACH command are
   93349   ** created to use the same default text encoding as the main database. If
   93350   ** the main database has not been initialized and/or created when ATTACH
   93351   ** is executed, this is done before the ATTACH operation.
   93352   **
   93353   ** In the second form this pragma sets the text encoding to be used in
   93354   ** new database files created using this database handle. It is only
   93355   ** useful if invoked immediately after the main database i
   93356   */
   93357   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
   93358     static const struct EncName {
   93359       char *zName;
   93360       u8 enc;
   93361     } encnames[] = {
   93362       { "UTF8",     SQLITE_UTF8        },
   93363       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   93364       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   93365       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   93366       { "UTF16le",  SQLITE_UTF16LE     },
   93367       { "UTF16be",  SQLITE_UTF16BE     },
   93368       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   93369       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   93370       { 0, 0 }
   93371     };
   93372     const struct EncName *pEnc;
   93373     if( !zRight ){    /* "PRAGMA encoding" */
   93374       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93375       sqlite3VdbeSetNumCols(v, 1);
   93376       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   93377       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   93378       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   93379       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   93380       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   93381       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   93382       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   93383     }else{                        /* "PRAGMA encoding = XXX" */
   93384       /* Only change the value of sqlite.enc if the database handle is not
   93385       ** initialized. If the main database exists, the new sqlite.enc value
   93386       ** will be overwritten when the schema is next loaded. If it does not
   93387       ** already exists, it will be created to use the new encoding value.
   93388       */
   93389       if(
   93390         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   93391         DbHasProperty(db, 0, DB_Empty)
   93392       ){
   93393         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   93394           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   93395             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   93396             break;
   93397           }
   93398         }
   93399         if( !pEnc->zName ){
   93400           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   93401         }
   93402       }
   93403     }
   93404   }else
   93405 #endif /* SQLITE_OMIT_UTF16 */
   93406 
   93407 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   93408   /*
   93409   **   PRAGMA [database.]schema_version
   93410   **   PRAGMA [database.]schema_version = <integer>
   93411   **
   93412   **   PRAGMA [database.]user_version
   93413   **   PRAGMA [database.]user_version = <integer>
   93414   **
   93415   ** The pragma's schema_version and user_version are used to set or get
   93416   ** the value of the schema-version and user-version, respectively. Both
   93417   ** the schema-version and the user-version are 32-bit signed integers
   93418   ** stored in the database header.
   93419   **
   93420   ** The schema-cookie is usually only manipulated internally by SQLite. It
   93421   ** is incremented by SQLite whenever the database schema is modified (by
   93422   ** creating or dropping a table or index). The schema version is used by
   93423   ** SQLite each time a query is executed to ensure that the internal cache
   93424   ** of the schema used when compiling the SQL query matches the schema of
   93425   ** the database against which the compiled query is actually executed.
   93426   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   93427   ** the schema-version is potentially dangerous and may lead to program
   93428   ** crashes or database corruption. Use with caution!
   93429   **
   93430   ** The user-version is not used internally by SQLite. It may be used by
   93431   ** applications for any purpose.
   93432   */
   93433   if( sqlite3StrICmp(zLeft, "schema_version")==0
   93434    || sqlite3StrICmp(zLeft, "user_version")==0
   93435    || sqlite3StrICmp(zLeft, "freelist_count")==0
   93436   ){
   93437     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   93438     sqlite3VdbeUsesBtree(v, iDb);
   93439     switch( zLeft[0] ){
   93440       case 'f': case 'F':
   93441         iCookie = BTREE_FREE_PAGE_COUNT;
   93442         break;
   93443       case 's': case 'S':
   93444         iCookie = BTREE_SCHEMA_VERSION;
   93445         break;
   93446       default:
   93447         iCookie = BTREE_USER_VERSION;
   93448         break;
   93449     }
   93450 
   93451     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   93452       /* Write the specified cookie value */
   93453       static const VdbeOpList setCookie[] = {
   93454         { OP_Transaction,    0,  1,  0},    /* 0 */
   93455         { OP_Integer,        0,  1,  0},    /* 1 */
   93456         { OP_SetCookie,      0,  0,  1},    /* 2 */
   93457       };
   93458       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
   93459       sqlite3VdbeChangeP1(v, addr, iDb);
   93460       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
   93461       sqlite3VdbeChangeP1(v, addr+2, iDb);
   93462       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   93463     }else{
   93464       /* Read the specified cookie value */
   93465       static const VdbeOpList readCookie[] = {
   93466         { OP_Transaction,     0,  0,  0},    /* 0 */
   93467         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   93468         { OP_ResultRow,       1,  1,  0}
   93469       };
   93470       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
   93471       sqlite3VdbeChangeP1(v, addr, iDb);
   93472       sqlite3VdbeChangeP1(v, addr+1, iDb);
   93473       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   93474       sqlite3VdbeSetNumCols(v, 1);
   93475       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   93476     }
   93477   }else
   93478 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   93479 
   93480 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   93481   /*
   93482   **   PRAGMA compile_options
   93483   **
   93484   ** Return the names of all compile-time options used in this build,
   93485   ** one option per row.
   93486   */
   93487   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
   93488     int i = 0;
   93489     const char *zOpt;
   93490     sqlite3VdbeSetNumCols(v, 1);
   93491     pParse->nMem = 1;
   93492     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
   93493     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   93494       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
   93495       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   93496     }
   93497   }else
   93498 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   93499 
   93500 #ifndef SQLITE_OMIT_WAL
   93501   /*
   93502   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
   93503   **
   93504   ** Checkpoint the database.
   93505   */
   93506   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
   93507     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
   93508     int eMode = SQLITE_CHECKPOINT_PASSIVE;
   93509     if( zRight ){
   93510       if( sqlite3StrICmp(zRight, "full")==0 ){
   93511         eMode = SQLITE_CHECKPOINT_FULL;
   93512       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
   93513         eMode = SQLITE_CHECKPOINT_RESTART;
   93514       }
   93515     }
   93516     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   93517     sqlite3VdbeSetNumCols(v, 3);
   93518     pParse->nMem = 3;
   93519     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
   93520     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
   93521     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
   93522 
   93523     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
   93524     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   93525   }else
   93526 
   93527   /*
   93528   **   PRAGMA wal_autocheckpoint
   93529   **   PRAGMA wal_autocheckpoint = N
   93530   **
   93531   ** Configure a database connection to automatically checkpoint a database
   93532   ** after accumulating N frames in the log. Or query for the current value
   93533   ** of N.
   93534   */
   93535   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
   93536     if( zRight ){
   93537       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   93538     }
   93539     returnSingleInt(pParse, "wal_autocheckpoint",
   93540        db->xWalCallback==sqlite3WalDefaultHook ?
   93541            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   93542   }else
   93543 #endif
   93544 
   93545   /*
   93546   **  PRAGMA shrink_memory
   93547   **
   93548   ** This pragma attempts to free as much memory as possible from the
   93549   ** current database connection.
   93550   */
   93551   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
   93552     sqlite3_db_release_memory(db);
   93553   }else
   93554 
   93555 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   93556   /*
   93557   ** Report the current state of file logs for all databases
   93558   */
   93559   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
   93560     static const char *const azLockName[] = {
   93561       "unlocked", "shared", "reserved", "pending", "exclusive"
   93562     };
   93563     int i;
   93564     sqlite3VdbeSetNumCols(v, 2);
   93565     pParse->nMem = 2;
   93566     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   93567     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   93568     for(i=0; i<db->nDb; i++){
   93569       Btree *pBt;
   93570       Pager *pPager;
   93571       const char *zState = "unknown";
   93572       int j;
   93573       if( db->aDb[i].zName==0 ) continue;
   93574       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   93575       pBt = db->aDb[i].pBt;
   93576       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
   93577         zState = "closed";
   93578       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   93579                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   93580          zState = azLockName[j];
   93581       }
   93582       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   93583       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   93584     }
   93585 
   93586   }else
   93587 #endif
   93588 
   93589 #ifdef SQLITE_HAS_CODEC
   93590   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
   93591     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
   93592   }else
   93593   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
   93594     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
   93595   }else
   93596   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
   93597                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
   93598     int i, h1, h2;
   93599     char zKey[40];
   93600     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
   93601       h1 += 9*(1&(h1>>6));
   93602       h2 += 9*(1&(h2>>6));
   93603       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
   93604     }
   93605     if( (zLeft[3] & 0xf)==0xb ){
   93606       sqlite3_key(db, zKey, i/2);
   93607     }else{
   93608       sqlite3_rekey(db, zKey, i/2);
   93609     }
   93610   }else
   93611 #endif
   93612 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   93613   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
   93614 #ifdef SQLITE_HAS_CODEC
   93615     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   93616       sqlite3_activate_see(&zRight[4]);
   93617     }
   93618 #endif
   93619 #ifdef SQLITE_ENABLE_CEROD
   93620     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   93621       sqlite3_activate_cerod(&zRight[6]);
   93622     }
   93623 #endif
   93624   }else
   93625 #endif
   93626 
   93627 
   93628   {/* Empty ELSE clause */}
   93629 
   93630   /*
   93631   ** Reset the safety level, in case the fullfsync flag or synchronous
   93632   ** setting changed.
   93633   */
   93634 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   93635   if( db->autoCommit ){
   93636     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
   93637                (db->flags&SQLITE_FullFSync)!=0,
   93638                (db->flags&SQLITE_CkptFullFSync)!=0);
   93639   }
   93640 #endif
   93641 pragma_out:
   93642   sqlite3DbFree(db, zLeft);
   93643   sqlite3DbFree(db, zRight);
   93644 }
   93645 
   93646 #endif /* SQLITE_OMIT_PRAGMA */
   93647 
   93648 /************** End of pragma.c **********************************************/
   93649 /************** Begin file prepare.c *****************************************/
   93650 /*
   93651 ** 2005 May 25
   93652 **
   93653 ** The author disclaims copyright to this source code.  In place of
   93654 ** a legal notice, here is a blessing:
   93655 **
   93656 **    May you do good and not evil.
   93657 **    May you find forgiveness for yourself and forgive others.
   93658 **    May you share freely, never taking more than you give.
   93659 **
   93660 *************************************************************************
   93661 ** This file contains the implementation of the sqlite3_prepare()
   93662 ** interface, and routines that contribute to loading the database schema
   93663 ** from disk.
   93664 */
   93665 
   93666 /*
   93667 ** Fill the InitData structure with an error message that indicates
   93668 ** that the database is corrupt.
   93669 */
   93670 static void corruptSchema(
   93671   InitData *pData,     /* Initialization context */
   93672   const char *zObj,    /* Object being parsed at the point of error */
   93673   const char *zExtra   /* Error information */
   93674 ){
   93675   sqlite3 *db = pData->db;
   93676   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   93677     if( zObj==0 ) zObj = "?";
   93678     sqlite3SetString(pData->pzErrMsg, db,
   93679       "malformed database schema (%s)", zObj);
   93680     if( zExtra ){
   93681       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   93682                                  "%s - %s", *pData->pzErrMsg, zExtra);
   93683     }
   93684   }
   93685   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
   93686 }
   93687 
   93688 /*
   93689 ** This is the callback routine for the code that initializes the
   93690 ** database.  See sqlite3Init() below for additional information.
   93691 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   93692 **
   93693 ** Each callback contains the following information:
   93694 **
   93695 **     argv[0] = name of thing being created
   93696 **     argv[1] = root page number for table or index. 0 for trigger or view.
   93697 **     argv[2] = SQL text for the CREATE statement.
   93698 **
   93699 */
   93700 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   93701   InitData *pData = (InitData*)pInit;
   93702   sqlite3 *db = pData->db;
   93703   int iDb = pData->iDb;
   93704 
   93705   assert( argc==3 );
   93706   UNUSED_PARAMETER2(NotUsed, argc);
   93707   assert( sqlite3_mutex_held(db->mutex) );
   93708   DbClearProperty(db, iDb, DB_Empty);
   93709   if( db->mallocFailed ){
   93710     corruptSchema(pData, argv[0], 0);
   93711     return 1;
   93712   }
   93713 
   93714   assert( iDb>=0 && iDb<db->nDb );
   93715   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   93716   if( argv[1]==0 ){
   93717     corruptSchema(pData, argv[0], 0);
   93718   }else if( argv[2] && argv[2][0] ){
   93719     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   93720     ** But because db->init.busy is set to 1, no VDBE code is generated
   93721     ** or executed.  All the parser does is build the internal data
   93722     ** structures that describe the table, index, or view.
   93723     */
   93724     int rc;
   93725     sqlite3_stmt *pStmt;
   93726     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   93727 
   93728     assert( db->init.busy );
   93729     db->init.iDb = iDb;
   93730     db->init.newTnum = sqlite3Atoi(argv[1]);
   93731     db->init.orphanTrigger = 0;
   93732     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   93733     rc = db->errCode;
   93734     assert( (rc&0xFF)==(rcp&0xFF) );
   93735     db->init.iDb = 0;
   93736     if( SQLITE_OK!=rc ){
   93737       if( db->init.orphanTrigger ){
   93738         assert( iDb==1 );
   93739       }else{
   93740         pData->rc = rc;
   93741         if( rc==SQLITE_NOMEM ){
   93742           db->mallocFailed = 1;
   93743         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   93744           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   93745         }
   93746       }
   93747     }
   93748     sqlite3_finalize(pStmt);
   93749   }else if( argv[0]==0 ){
   93750     corruptSchema(pData, 0, 0);
   93751   }else{
   93752     /* If the SQL column is blank it means this is an index that
   93753     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   93754     ** constraint for a CREATE TABLE.  The index should have already
   93755     ** been created when we processed the CREATE TABLE.  All we have
   93756     ** to do here is record the root page number for that index.
   93757     */
   93758     Index *pIndex;
   93759     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   93760     if( pIndex==0 ){
   93761       /* This can occur if there exists an index on a TEMP table which
   93762       ** has the same name as another index on a permanent index.  Since
   93763       ** the permanent table is hidden by the TEMP table, we can also
   93764       ** safely ignore the index on the permanent table.
   93765       */
   93766       /* Do Nothing */;
   93767     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   93768       corruptSchema(pData, argv[0], "invalid rootpage");
   93769     }
   93770   }
   93771   return 0;
   93772 }
   93773 
   93774 /*
   93775 ** Attempt to read the database schema and initialize internal
   93776 ** data structures for a single database file.  The index of the
   93777 ** database file is given by iDb.  iDb==0 is used for the main
   93778 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   93779 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   93780 ** indicate success or failure.
   93781 */
   93782 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   93783   int rc;
   93784   int i;
   93785   int size;
   93786   Table *pTab;
   93787   Db *pDb;
   93788   char const *azArg[4];
   93789   int meta[5];
   93790   InitData initData;
   93791   char const *zMasterSchema;
   93792   char const *zMasterName;
   93793   int openedTransaction = 0;
   93794 
   93795   /*
   93796   ** The master database table has a structure like this
   93797   */
   93798   static const char master_schema[] =
   93799      "CREATE TABLE sqlite_master(\n"
   93800      "  type text,\n"
   93801      "  name text,\n"
   93802      "  tbl_name text,\n"
   93803      "  rootpage integer,\n"
   93804      "  sql text\n"
   93805      ")"
   93806   ;
   93807 #ifndef SQLITE_OMIT_TEMPDB
   93808   static const char temp_master_schema[] =
   93809      "CREATE TEMP TABLE sqlite_temp_master(\n"
   93810      "  type text,\n"
   93811      "  name text,\n"
   93812      "  tbl_name text,\n"
   93813      "  rootpage integer,\n"
   93814      "  sql text\n"
   93815      ")"
   93816   ;
   93817 #else
   93818   #define temp_master_schema 0
   93819 #endif
   93820 
   93821   assert( iDb>=0 && iDb<db->nDb );
   93822   assert( db->aDb[iDb].pSchema );
   93823   assert( sqlite3_mutex_held(db->mutex) );
   93824   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   93825 
   93826   /* zMasterSchema and zInitScript are set to point at the master schema
   93827   ** and initialisation script appropriate for the database being
   93828   ** initialised. zMasterName is the name of the master table.
   93829   */
   93830   if( !OMIT_TEMPDB && iDb==1 ){
   93831     zMasterSchema = temp_master_schema;
   93832   }else{
   93833     zMasterSchema = master_schema;
   93834   }
   93835   zMasterName = SCHEMA_TABLE(iDb);
   93836 
   93837   /* Construct the schema tables.  */
   93838   azArg[0] = zMasterName;
   93839   azArg[1] = "1";
   93840   azArg[2] = zMasterSchema;
   93841   azArg[3] = 0;
   93842   initData.db = db;
   93843   initData.iDb = iDb;
   93844   initData.rc = SQLITE_OK;
   93845   initData.pzErrMsg = pzErrMsg;
   93846   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   93847   if( initData.rc ){
   93848     rc = initData.rc;
   93849     goto error_out;
   93850   }
   93851   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   93852   if( ALWAYS(pTab) ){
   93853     pTab->tabFlags |= TF_Readonly;
   93854   }
   93855 
   93856   /* Create a cursor to hold the database open
   93857   */
   93858   pDb = &db->aDb[iDb];
   93859   if( pDb->pBt==0 ){
   93860     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   93861       DbSetProperty(db, 1, DB_SchemaLoaded);
   93862     }
   93863     return SQLITE_OK;
   93864   }
   93865 
   93866   /* If there is not already a read-only (or read-write) transaction opened
   93867   ** on the b-tree database, open one now. If a transaction is opened, it
   93868   ** will be closed before this function returns.  */
   93869   sqlite3BtreeEnter(pDb->pBt);
   93870   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   93871     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   93872     if( rc!=SQLITE_OK ){
   93873       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   93874       goto initone_error_out;
   93875     }
   93876     openedTransaction = 1;
   93877   }
   93878 
   93879   /* Get the database meta information.
   93880   **
   93881   ** Meta values are as follows:
   93882   **    meta[0]   Schema cookie.  Changes with each schema change.
   93883   **    meta[1]   File format of schema layer.
   93884   **    meta[2]   Size of the page cache.
   93885   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   93886   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   93887   **    meta[5]   User version
   93888   **    meta[6]   Incremental vacuum mode
   93889   **    meta[7]   unused
   93890   **    meta[8]   unused
   93891   **    meta[9]   unused
   93892   **
   93893   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   93894   ** the possible values of meta[4].
   93895   */
   93896   for(i=0; i<ArraySize(meta); i++){
   93897     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   93898   }
   93899   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   93900 
   93901   /* If opening a non-empty database, check the text encoding. For the
   93902   ** main database, set sqlite3.enc to the encoding of the main database.
   93903   ** For an attached db, it is an error if the encoding is not the same
   93904   ** as sqlite3.enc.
   93905   */
   93906   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   93907     if( iDb==0 ){
   93908       u8 encoding;
   93909       /* If opening the main database, set ENC(db). */
   93910       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   93911       if( encoding==0 ) encoding = SQLITE_UTF8;
   93912       ENC(db) = encoding;
   93913       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   93914     }else{
   93915       /* If opening an attached database, the encoding much match ENC(db) */
   93916       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   93917         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   93918             " text encoding as main database");
   93919         rc = SQLITE_ERROR;
   93920         goto initone_error_out;
   93921       }
   93922     }
   93923   }else{
   93924     DbSetProperty(db, iDb, DB_Empty);
   93925   }
   93926   pDb->pSchema->enc = ENC(db);
   93927 
   93928   if( pDb->pSchema->cache_size==0 ){
   93929 #ifndef SQLITE_OMIT_DEPRECATED
   93930     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   93931     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   93932     pDb->pSchema->cache_size = size;
   93933 #else
   93934     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
   93935 #endif
   93936     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   93937   }
   93938 
   93939   /*
   93940   ** file_format==1    Version 3.0.0.
   93941   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   93942   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   93943   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   93944   */
   93945   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   93946   if( pDb->pSchema->file_format==0 ){
   93947     pDb->pSchema->file_format = 1;
   93948   }
   93949   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   93950     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   93951     rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
   93952     goto initone_error_out;
   93953   }
   93954 
   93955   /* Ticket #2804:  When we open a database in the newer file format,
   93956   ** clear the legacy_file_format pragma flag so that a VACUUM will
   93957   ** not downgrade the database and thus invalidate any descending
   93958   ** indices that the user might have created.
   93959   */
   93960   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   93961     db->flags &= ~SQLITE_LegacyFileFmt;
   93962   }
   93963 
   93964   /* Read the schema information out of the schema tables
   93965   */
   93966   assert( db->init.busy );
   93967   {
   93968     char *zSql;
   93969     zSql = sqlite3MPrintf(db,
   93970         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
   93971         db->aDb[iDb].zName, zMasterName);
   93972 #ifndef SQLITE_OMIT_AUTHORIZATION
   93973     {
   93974       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   93975       xAuth = db->xAuth;
   93976       db->xAuth = 0;
   93977 #endif
   93978       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   93979 #ifndef SQLITE_OMIT_AUTHORIZATION
   93980       db->xAuth = xAuth;
   93981     }
   93982 #endif
   93983     if( rc==SQLITE_OK ) rc = initData.rc;
   93984     sqlite3DbFree(db, zSql);
   93985 #ifndef SQLITE_OMIT_ANALYZE
   93986     if( rc==SQLITE_OK ){
   93987       sqlite3AnalysisLoad(db, iDb);
   93988     }
   93989 #endif
   93990   }
   93991   if( db->mallocFailed ){
   93992     rc = SQLITE_NOMEM;
   93993     sqlite3ResetInternalSchema(db, -1);
   93994   }
   93995   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   93996     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   93997     ** the schema loaded, even if errors occurred. In this situation the
   93998     ** current sqlite3_prepare() operation will fail, but the following one
   93999     ** will attempt to compile the supplied statement against whatever subset
   94000     ** of the schema was loaded before the error occurred. The primary
   94001     ** purpose of this is to allow access to the sqlite_master table
   94002     ** even when its contents have been corrupted.
   94003     */
   94004     DbSetProperty(db, iDb, DB_SchemaLoaded);
   94005     rc = SQLITE_OK;
   94006   }
   94007 
   94008   /* Jump here for an error that occurs after successfully allocating
   94009   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   94010   ** before that point, jump to error_out.
   94011   */
   94012 initone_error_out:
   94013   if( openedTransaction ){
   94014     sqlite3BtreeCommit(pDb->pBt);
   94015   }
   94016   sqlite3BtreeLeave(pDb->pBt);
   94017 
   94018 error_out:
   94019   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   94020     db->mallocFailed = 1;
   94021   }
   94022   return rc;
   94023 }
   94024 
   94025 /*
   94026 ** Initialize all database files - the main database file, the file
   94027 ** used to store temporary tables, and any additional database files
   94028 ** created using ATTACH statements.  Return a success code.  If an
   94029 ** error occurs, write an error message into *pzErrMsg.
   94030 **
   94031 ** After a database is initialized, the DB_SchemaLoaded bit is set
   94032 ** bit is set in the flags field of the Db structure. If the database
   94033 ** file was of zero-length, then the DB_Empty flag is also set.
   94034 */
   94035 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   94036   int i, rc;
   94037   int commit_internal = !(db->flags&SQLITE_InternChanges);
   94038 
   94039   assert( sqlite3_mutex_held(db->mutex) );
   94040   rc = SQLITE_OK;
   94041   db->init.busy = 1;
   94042   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   94043     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   94044     rc = sqlite3InitOne(db, i, pzErrMsg);
   94045     if( rc ){
   94046       sqlite3ResetInternalSchema(db, i);
   94047     }
   94048   }
   94049 
   94050   /* Once all the other databases have been initialised, load the schema
   94051   ** for the TEMP database. This is loaded last, as the TEMP database
   94052   ** schema may contain references to objects in other databases.
   94053   */
   94054 #ifndef SQLITE_OMIT_TEMPDB
   94055   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   94056                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   94057     rc = sqlite3InitOne(db, 1, pzErrMsg);
   94058     if( rc ){
   94059       sqlite3ResetInternalSchema(db, 1);
   94060     }
   94061   }
   94062 #endif
   94063 
   94064   db->init.busy = 0;
   94065   if( rc==SQLITE_OK && commit_internal ){
   94066     sqlite3CommitInternalChanges(db);
   94067   }
   94068 
   94069   return rc;
   94070 }
   94071 
   94072 /*
   94073 ** This routine is a no-op if the database schema is already initialised.
   94074 ** Otherwise, the schema is loaded. An error code is returned.
   94075 */
   94076 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   94077   int rc = SQLITE_OK;
   94078   sqlite3 *db = pParse->db;
   94079   assert( sqlite3_mutex_held(db->mutex) );
   94080   if( !db->init.busy ){
   94081     rc = sqlite3Init(db, &pParse->zErrMsg);
   94082   }
   94083   if( rc!=SQLITE_OK ){
   94084     pParse->rc = rc;
   94085     pParse->nErr++;
   94086   }
   94087   return rc;
   94088 }
   94089 
   94090 
   94091 /*
   94092 ** Check schema cookies in all databases.  If any cookie is out
   94093 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   94094 ** make no changes to pParse->rc.
   94095 */
   94096 static void schemaIsValid(Parse *pParse){
   94097   sqlite3 *db = pParse->db;
   94098   int iDb;
   94099   int rc;
   94100   int cookie;
   94101 
   94102   assert( pParse->checkSchema );
   94103   assert( sqlite3_mutex_held(db->mutex) );
   94104   for(iDb=0; iDb<db->nDb; iDb++){
   94105     int openedTransaction = 0;         /* True if a transaction is opened */
   94106     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   94107     if( pBt==0 ) continue;
   94108 
   94109     /* If there is not already a read-only (or read-write) transaction opened
   94110     ** on the b-tree database, open one now. If a transaction is opened, it
   94111     ** will be closed immediately after reading the meta-value. */
   94112     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   94113       rc = sqlite3BtreeBeginTrans(pBt, 0);
   94114       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   94115         db->mallocFailed = 1;
   94116       }
   94117       if( rc!=SQLITE_OK ) return;
   94118       openedTransaction = 1;
   94119     }
   94120 
   94121     /* Read the schema cookie from the database. If it does not match the
   94122     ** value stored as part of the in-memory schema representation,
   94123     ** set Parse.rc to SQLITE_SCHEMA. */
   94124     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   94125     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   94126     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   94127       sqlite3ResetInternalSchema(db, iDb);
   94128       pParse->rc = SQLITE_SCHEMA;
   94129     }
   94130 
   94131     /* Close the transaction, if one was opened. */
   94132     if( openedTransaction ){
   94133       sqlite3BtreeCommit(pBt);
   94134     }
   94135   }
   94136 }
   94137 
   94138 /*
   94139 ** Convert a schema pointer into the iDb index that indicates
   94140 ** which database file in db->aDb[] the schema refers to.
   94141 **
   94142 ** If the same database is attached more than once, the first
   94143 ** attached database is returned.
   94144 */
   94145 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   94146   int i = -1000000;
   94147 
   94148   /* If pSchema is NULL, then return -1000000. This happens when code in
   94149   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   94150   ** created by a sub-select). In this case the return value of this
   94151   ** function should never be used.
   94152   **
   94153   ** We return -1000000 instead of the more usual -1 simply because using
   94154   ** -1000000 as the incorrect index into db->aDb[] is much
   94155   ** more likely to cause a segfault than -1 (of course there are assert()
   94156   ** statements too, but it never hurts to play the odds).
   94157   */
   94158   assert( sqlite3_mutex_held(db->mutex) );
   94159   if( pSchema ){
   94160     for(i=0; ALWAYS(i<db->nDb); i++){
   94161       if( db->aDb[i].pSchema==pSchema ){
   94162         break;
   94163       }
   94164     }
   94165     assert( i>=0 && i<db->nDb );
   94166   }
   94167   return i;
   94168 }
   94169 
   94170 /*
   94171 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   94172 */
   94173 static int sqlite3Prepare(
   94174   sqlite3 *db,              /* Database handle. */
   94175   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94176   int nBytes,               /* Length of zSql in bytes. */
   94177   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   94178   Vdbe *pReprepare,         /* VM being reprepared */
   94179   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94180   const char **pzTail       /* OUT: End of parsed string */
   94181 ){
   94182   Parse *pParse;            /* Parsing context */
   94183   char *zErrMsg = 0;        /* Error message */
   94184   int rc = SQLITE_OK;       /* Result code */
   94185   int i;                    /* Loop counter */
   94186 
   94187   /* Allocate the parsing context */
   94188   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   94189   if( pParse==0 ){
   94190     rc = SQLITE_NOMEM;
   94191     goto end_prepare;
   94192   }
   94193   pParse->pReprepare = pReprepare;
   94194   assert( ppStmt && *ppStmt==0 );
   94195   assert( !db->mallocFailed );
   94196   assert( sqlite3_mutex_held(db->mutex) );
   94197 
   94198   /* Check to verify that it is possible to get a read lock on all
   94199   ** database schemas.  The inability to get a read lock indicates that
   94200   ** some other database connection is holding a write-lock, which in
   94201   ** turn means that the other connection has made uncommitted changes
   94202   ** to the schema.
   94203   **
   94204   ** Were we to proceed and prepare the statement against the uncommitted
   94205   ** schema changes and if those schema changes are subsequently rolled
   94206   ** back and different changes are made in their place, then when this
   94207   ** prepared statement goes to run the schema cookie would fail to detect
   94208   ** the schema change.  Disaster would follow.
   94209   **
   94210   ** This thread is currently holding mutexes on all Btrees (because
   94211   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   94212   ** is not possible for another thread to start a new schema change
   94213   ** while this routine is running.  Hence, we do not need to hold
   94214   ** locks on the schema, we just need to make sure nobody else is
   94215   ** holding them.
   94216   **
   94217   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   94218   ** but it does *not* override schema lock detection, so this all still
   94219   ** works even if READ_UNCOMMITTED is set.
   94220   */
   94221   for(i=0; i<db->nDb; i++) {
   94222     Btree *pBt = db->aDb[i].pBt;
   94223     if( pBt ){
   94224       assert( sqlite3BtreeHoldsMutex(pBt) );
   94225       rc = sqlite3BtreeSchemaLocked(pBt);
   94226       if( rc ){
   94227         const char *zDb = db->aDb[i].zName;
   94228         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   94229         testcase( db->flags & SQLITE_ReadUncommitted );
   94230         goto end_prepare;
   94231       }
   94232     }
   94233   }
   94234 
   94235   sqlite3VtabUnlockList(db);
   94236 
   94237   pParse->db = db;
   94238   pParse->nQueryLoop = (double)1;
   94239   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   94240     char *zSqlCopy;
   94241     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   94242     testcase( nBytes==mxLen );
   94243     testcase( nBytes==mxLen+1 );
   94244     if( nBytes>mxLen ){
   94245       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   94246       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   94247       goto end_prepare;
   94248     }
   94249     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   94250     if( zSqlCopy ){
   94251       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   94252       sqlite3DbFree(db, zSqlCopy);
   94253       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   94254     }else{
   94255       pParse->zTail = &zSql[nBytes];
   94256     }
   94257   }else{
   94258     sqlite3RunParser(pParse, zSql, &zErrMsg);
   94259   }
   94260   assert( 1==(int)pParse->nQueryLoop );
   94261 
   94262   if( db->mallocFailed ){
   94263     pParse->rc = SQLITE_NOMEM;
   94264   }
   94265   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   94266   if( pParse->checkSchema ){
   94267     schemaIsValid(pParse);
   94268   }
   94269   if( db->mallocFailed ){
   94270     pParse->rc = SQLITE_NOMEM;
   94271   }
   94272   if( pzTail ){
   94273     *pzTail = pParse->zTail;
   94274   }
   94275   rc = pParse->rc;
   94276 
   94277 #ifndef SQLITE_OMIT_EXPLAIN
   94278   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   94279     static const char * const azColName[] = {
   94280        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   94281        "selectid", "order", "from", "detail"
   94282     };
   94283     int iFirst, mx;
   94284     if( pParse->explain==2 ){
   94285       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
   94286       iFirst = 8;
   94287       mx = 12;
   94288     }else{
   94289       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   94290       iFirst = 0;
   94291       mx = 8;
   94292     }
   94293     for(i=iFirst; i<mx; i++){
   94294       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   94295                             azColName[i], SQLITE_STATIC);
   94296     }
   94297   }
   94298 #endif
   94299 
   94300   assert( db->init.busy==0 || saveSqlFlag==0 );
   94301   if( db->init.busy==0 ){
   94302     Vdbe *pVdbe = pParse->pVdbe;
   94303     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   94304   }
   94305   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   94306     sqlite3VdbeFinalize(pParse->pVdbe);
   94307     assert(!(*ppStmt));
   94308   }else{
   94309     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   94310   }
   94311 
   94312   if( zErrMsg ){
   94313     sqlite3Error(db, rc, "%s", zErrMsg);
   94314     sqlite3DbFree(db, zErrMsg);
   94315   }else{
   94316     sqlite3Error(db, rc, 0);
   94317   }
   94318 
   94319   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   94320   while( pParse->pTriggerPrg ){
   94321     TriggerPrg *pT = pParse->pTriggerPrg;
   94322     pParse->pTriggerPrg = pT->pNext;
   94323     sqlite3DbFree(db, pT);
   94324   }
   94325 
   94326 end_prepare:
   94327 
   94328   sqlite3StackFree(db, pParse);
   94329   rc = sqlite3ApiExit(db, rc);
   94330   assert( (rc&db->errMask)==rc );
   94331   return rc;
   94332 }
   94333 static int sqlite3LockAndPrepare(
   94334   sqlite3 *db,              /* Database handle. */
   94335   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94336   int nBytes,               /* Length of zSql in bytes. */
   94337   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   94338   Vdbe *pOld,               /* VM being reprepared */
   94339   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94340   const char **pzTail       /* OUT: End of parsed string */
   94341 ){
   94342   int rc;
   94343   assert( ppStmt!=0 );
   94344   *ppStmt = 0;
   94345   if( !sqlite3SafetyCheckOk(db) ){
   94346     return SQLITE_MISUSE_BKPT;
   94347   }
   94348   sqlite3_mutex_enter(db->mutex);
   94349   sqlite3BtreeEnterAll(db);
   94350   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   94351   if( rc==SQLITE_SCHEMA ){
   94352     sqlite3_finalize(*ppStmt);
   94353     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   94354   }
   94355   sqlite3BtreeLeaveAll(db);
   94356   sqlite3_mutex_leave(db->mutex);
   94357   return rc;
   94358 }
   94359 
   94360 /*
   94361 ** Rerun the compilation of a statement after a schema change.
   94362 **
   94363 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   94364 ** if the statement cannot be recompiled because another connection has
   94365 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   94366 ** occurs, return SQLITE_SCHEMA.
   94367 */
   94368 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   94369   int rc;
   94370   sqlite3_stmt *pNew;
   94371   const char *zSql;
   94372   sqlite3 *db;
   94373 
   94374   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   94375   zSql = sqlite3_sql((sqlite3_stmt *)p);
   94376   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   94377   db = sqlite3VdbeDb(p);
   94378   assert( sqlite3_mutex_held(db->mutex) );
   94379   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   94380   if( rc ){
   94381     if( rc==SQLITE_NOMEM ){
   94382       db->mallocFailed = 1;
   94383     }
   94384     assert( pNew==0 );
   94385     return rc;
   94386   }else{
   94387     assert( pNew!=0 );
   94388   }
   94389   sqlite3VdbeSwap((Vdbe*)pNew, p);
   94390   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   94391   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   94392   sqlite3VdbeFinalize((Vdbe*)pNew);
   94393   return SQLITE_OK;
   94394 }
   94395 
   94396 
   94397 /*
   94398 ** Two versions of the official API.  Legacy and new use.  In the legacy
   94399 ** version, the original SQL text is not saved in the prepared statement
   94400 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   94401 ** sqlite3_step().  In the new version, the original SQL text is retained
   94402 ** and the statement is automatically recompiled if an schema change
   94403 ** occurs.
   94404 */
   94405 SQLITE_API int sqlite3_prepare(
   94406   sqlite3 *db,              /* Database handle. */
   94407   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94408   int nBytes,               /* Length of zSql in bytes. */
   94409   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94410   const char **pzTail       /* OUT: End of parsed string */
   94411 ){
   94412   int rc;
   94413   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   94414   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94415   return rc;
   94416 }
   94417 SQLITE_API int sqlite3_prepare_v2(
   94418   sqlite3 *db,              /* Database handle. */
   94419   const char *zSql,         /* UTF-8 encoded SQL statement. */
   94420   int nBytes,               /* Length of zSql in bytes. */
   94421   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94422   const char **pzTail       /* OUT: End of parsed string */
   94423 ){
   94424   int rc;
   94425   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   94426   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94427   return rc;
   94428 }
   94429 
   94430 
   94431 #ifndef SQLITE_OMIT_UTF16
   94432 /*
   94433 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   94434 */
   94435 static int sqlite3Prepare16(
   94436   sqlite3 *db,              /* Database handle. */
   94437   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94438   int nBytes,               /* Length of zSql in bytes. */
   94439   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   94440   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94441   const void **pzTail       /* OUT: End of parsed string */
   94442 ){
   94443   /* This function currently works by first transforming the UTF-16
   94444   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   94445   ** tricky bit is figuring out the pointer to return in *pzTail.
   94446   */
   94447   char *zSql8;
   94448   const char *zTail8 = 0;
   94449   int rc = SQLITE_OK;
   94450 
   94451   assert( ppStmt );
   94452   *ppStmt = 0;
   94453   if( !sqlite3SafetyCheckOk(db) ){
   94454     return SQLITE_MISUSE_BKPT;
   94455   }
   94456   sqlite3_mutex_enter(db->mutex);
   94457   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   94458   if( zSql8 ){
   94459     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   94460   }
   94461 
   94462   if( zTail8 && pzTail ){
   94463     /* If sqlite3_prepare returns a tail pointer, we calculate the
   94464     ** equivalent pointer into the UTF-16 string by counting the unicode
   94465     ** characters between zSql8 and zTail8, and then returning a pointer
   94466     ** the same number of characters into the UTF-16 string.
   94467     */
   94468     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   94469     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   94470   }
   94471   sqlite3DbFree(db, zSql8);
   94472   rc = sqlite3ApiExit(db, rc);
   94473   sqlite3_mutex_leave(db->mutex);
   94474   return rc;
   94475 }
   94476 
   94477 /*
   94478 ** Two versions of the official API.  Legacy and new use.  In the legacy
   94479 ** version, the original SQL text is not saved in the prepared statement
   94480 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   94481 ** sqlite3_step().  In the new version, the original SQL text is retained
   94482 ** and the statement is automatically recompiled if an schema change
   94483 ** occurs.
   94484 */
   94485 SQLITE_API int sqlite3_prepare16(
   94486   sqlite3 *db,              /* Database handle. */
   94487   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94488   int nBytes,               /* Length of zSql in bytes. */
   94489   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94490   const void **pzTail       /* OUT: End of parsed string */
   94491 ){
   94492   int rc;
   94493   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   94494   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94495   return rc;
   94496 }
   94497 SQLITE_API int sqlite3_prepare16_v2(
   94498   sqlite3 *db,              /* Database handle. */
   94499   const void *zSql,         /* UTF-16 encoded SQL statement. */
   94500   int nBytes,               /* Length of zSql in bytes. */
   94501   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   94502   const void **pzTail       /* OUT: End of parsed string */
   94503 ){
   94504   int rc;
   94505   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   94506   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   94507   return rc;
   94508 }
   94509 
   94510 #endif /* SQLITE_OMIT_UTF16 */
   94511 
   94512 /************** End of prepare.c *********************************************/
   94513 /************** Begin file select.c ******************************************/
   94514 /*
   94515 ** 2001 September 15
   94516 **
   94517 ** The author disclaims copyright to this source code.  In place of
   94518 ** a legal notice, here is a blessing:
   94519 **
   94520 **    May you do good and not evil.
   94521 **    May you find forgiveness for yourself and forgive others.
   94522 **    May you share freely, never taking more than you give.
   94523 **
   94524 *************************************************************************
   94525 ** This file contains C code routines that are called by the parser
   94526 ** to handle SELECT statements in SQLite.
   94527 */
   94528 
   94529 
   94530 /*
   94531 ** Delete all the content of a Select structure but do not deallocate
   94532 ** the select structure itself.
   94533 */
   94534 static void clearSelect(sqlite3 *db, Select *p){
   94535   sqlite3ExprListDelete(db, p->pEList);
   94536   sqlite3SrcListDelete(db, p->pSrc);
   94537   sqlite3ExprDelete(db, p->pWhere);
   94538   sqlite3ExprListDelete(db, p->pGroupBy);
   94539   sqlite3ExprDelete(db, p->pHaving);
   94540   sqlite3ExprListDelete(db, p->pOrderBy);
   94541   sqlite3SelectDelete(db, p->pPrior);
   94542   sqlite3ExprDelete(db, p->pLimit);
   94543   sqlite3ExprDelete(db, p->pOffset);
   94544 }
   94545 
   94546 /*
   94547 ** Initialize a SelectDest structure.
   94548 */
   94549 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   94550   pDest->eDest = (u8)eDest;
   94551   pDest->iParm = iParm;
   94552   pDest->affinity = 0;
   94553   pDest->iMem = 0;
   94554   pDest->nMem = 0;
   94555 }
   94556 
   94557 
   94558 /*
   94559 ** Allocate a new Select structure and return a pointer to that
   94560 ** structure.
   94561 */
   94562 SQLITE_PRIVATE Select *sqlite3SelectNew(
   94563   Parse *pParse,        /* Parsing context */
   94564   ExprList *pEList,     /* which columns to include in the result */
   94565   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   94566   Expr *pWhere,         /* the WHERE clause */
   94567   ExprList *pGroupBy,   /* the GROUP BY clause */
   94568   Expr *pHaving,        /* the HAVING clause */
   94569   ExprList *pOrderBy,   /* the ORDER BY clause */
   94570   int isDistinct,       /* true if the DISTINCT keyword is present */
   94571   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   94572   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   94573 ){
   94574   Select *pNew;
   94575   Select standin;
   94576   sqlite3 *db = pParse->db;
   94577   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   94578   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   94579   if( pNew==0 ){
   94580     assert( db->mallocFailed );
   94581     pNew = &standin;
   94582     memset(pNew, 0, sizeof(*pNew));
   94583   }
   94584   if( pEList==0 ){
   94585     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   94586   }
   94587   pNew->pEList = pEList;
   94588   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
   94589   pNew->pSrc = pSrc;
   94590   pNew->pWhere = pWhere;
   94591   pNew->pGroupBy = pGroupBy;
   94592   pNew->pHaving = pHaving;
   94593   pNew->pOrderBy = pOrderBy;
   94594   pNew->selFlags = isDistinct ? SF_Distinct : 0;
   94595   pNew->op = TK_SELECT;
   94596   pNew->pLimit = pLimit;
   94597   pNew->pOffset = pOffset;
   94598   assert( pOffset==0 || pLimit!=0 );
   94599   pNew->addrOpenEphm[0] = -1;
   94600   pNew->addrOpenEphm[1] = -1;
   94601   pNew->addrOpenEphm[2] = -1;
   94602   if( db->mallocFailed ) {
   94603     clearSelect(db, pNew);
   94604     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   94605     pNew = 0;
   94606   }else{
   94607     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   94608   }
   94609   assert( pNew!=&standin );
   94610   return pNew;
   94611 }
   94612 
   94613 /*
   94614 ** Delete the given Select structure and all of its substructures.
   94615 */
   94616 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   94617   if( p ){
   94618     clearSelect(db, p);
   94619     sqlite3DbFree(db, p);
   94620   }
   94621 }
   94622 
   94623 /*
   94624 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   94625 ** type of join.  Return an integer constant that expresses that type
   94626 ** in terms of the following bit values:
   94627 **
   94628 **     JT_INNER
   94629 **     JT_CROSS
   94630 **     JT_OUTER
   94631 **     JT_NATURAL
   94632 **     JT_LEFT
   94633 **     JT_RIGHT
   94634 **
   94635 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   94636 **
   94637 ** If an illegal or unsupported join type is seen, then still return
   94638 ** a join type, but put an error in the pParse structure.
   94639 */
   94640 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   94641   int jointype = 0;
   94642   Token *apAll[3];
   94643   Token *p;
   94644                              /*   0123456789 123456789 123456789 123 */
   94645   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   94646   static const struct {
   94647     u8 i;        /* Beginning of keyword text in zKeyText[] */
   94648     u8 nChar;    /* Length of the keyword in characters */
   94649     u8 code;     /* Join type mask */
   94650   } aKeyword[] = {
   94651     /* natural */ { 0,  7, JT_NATURAL                },
   94652     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   94653     /* outer   */ { 10, 5, JT_OUTER                  },
   94654     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   94655     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   94656     /* inner   */ { 23, 5, JT_INNER                  },
   94657     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   94658   };
   94659   int i, j;
   94660   apAll[0] = pA;
   94661   apAll[1] = pB;
   94662   apAll[2] = pC;
   94663   for(i=0; i<3 && apAll[i]; i++){
   94664     p = apAll[i];
   94665     for(j=0; j<ArraySize(aKeyword); j++){
   94666       if( p->n==aKeyword[j].nChar
   94667           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   94668         jointype |= aKeyword[j].code;
   94669         break;
   94670       }
   94671     }
   94672     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   94673     if( j>=ArraySize(aKeyword) ){
   94674       jointype |= JT_ERROR;
   94675       break;
   94676     }
   94677   }
   94678   if(
   94679      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   94680      (jointype & JT_ERROR)!=0
   94681   ){
   94682     const char *zSp = " ";
   94683     assert( pB!=0 );
   94684     if( pC==0 ){ zSp++; }
   94685     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   94686        "%T %T%s%T", pA, pB, zSp, pC);
   94687     jointype = JT_INNER;
   94688   }else if( (jointype & JT_OUTER)!=0
   94689          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   94690     sqlite3ErrorMsg(pParse,
   94691       "RIGHT and FULL OUTER JOINs are not currently supported");
   94692     jointype = JT_INNER;
   94693   }
   94694   return jointype;
   94695 }
   94696 
   94697 /*
   94698 ** Return the index of a column in a table.  Return -1 if the column
   94699 ** is not contained in the table.
   94700 */
   94701 static int columnIndex(Table *pTab, const char *zCol){
   94702   int i;
   94703   for(i=0; i<pTab->nCol; i++){
   94704     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   94705   }
   94706   return -1;
   94707 }
   94708 
   94709 /*
   94710 ** Search the first N tables in pSrc, from left to right, looking for a
   94711 ** table that has a column named zCol.
   94712 **
   94713 ** When found, set *piTab and *piCol to the table index and column index
   94714 ** of the matching column and return TRUE.
   94715 **
   94716 ** If not found, return FALSE.
   94717 */
   94718 static int tableAndColumnIndex(
   94719   SrcList *pSrc,       /* Array of tables to search */
   94720   int N,               /* Number of tables in pSrc->a[] to search */
   94721   const char *zCol,    /* Name of the column we are looking for */
   94722   int *piTab,          /* Write index of pSrc->a[] here */
   94723   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   94724 ){
   94725   int i;               /* For looping over tables in pSrc */
   94726   int iCol;            /* Index of column matching zCol */
   94727 
   94728   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   94729   for(i=0; i<N; i++){
   94730     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   94731     if( iCol>=0 ){
   94732       if( piTab ){
   94733         *piTab = i;
   94734         *piCol = iCol;
   94735       }
   94736       return 1;
   94737     }
   94738   }
   94739   return 0;
   94740 }
   94741 
   94742 /*
   94743 ** This function is used to add terms implied by JOIN syntax to the
   94744 ** WHERE clause expression of a SELECT statement. The new term, which
   94745 ** is ANDed with the existing WHERE clause, is of the form:
   94746 **
   94747 **    (tab1.col1 = tab2.col2)
   94748 **
   94749 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   94750 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   94751 ** column iColRight of tab2.
   94752 */
   94753 static void addWhereTerm(
   94754   Parse *pParse,                  /* Parsing context */
   94755   SrcList *pSrc,                  /* List of tables in FROM clause */
   94756   int iLeft,                      /* Index of first table to join in pSrc */
   94757   int iColLeft,                   /* Index of column in first table */
   94758   int iRight,                     /* Index of second table in pSrc */
   94759   int iColRight,                  /* Index of column in second table */
   94760   int isOuterJoin,                /* True if this is an OUTER join */
   94761   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   94762 ){
   94763   sqlite3 *db = pParse->db;
   94764   Expr *pE1;
   94765   Expr *pE2;
   94766   Expr *pEq;
   94767 
   94768   assert( iLeft<iRight );
   94769   assert( pSrc->nSrc>iRight );
   94770   assert( pSrc->a[iLeft].pTab );
   94771   assert( pSrc->a[iRight].pTab );
   94772 
   94773   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   94774   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   94775 
   94776   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   94777   if( pEq && isOuterJoin ){
   94778     ExprSetProperty(pEq, EP_FromJoin);
   94779     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
   94780     ExprSetIrreducible(pEq);
   94781     pEq->iRightJoinTable = (i16)pE2->iTable;
   94782   }
   94783   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   94784 }
   94785 
   94786 /*
   94787 ** Set the EP_FromJoin property on all terms of the given expression.
   94788 ** And set the Expr.iRightJoinTable to iTable for every term in the
   94789 ** expression.
   94790 **
   94791 ** The EP_FromJoin property is used on terms of an expression to tell
   94792 ** the LEFT OUTER JOIN processing logic that this term is part of the
   94793 ** join restriction specified in the ON or USING clause and not a part
   94794 ** of the more general WHERE clause.  These terms are moved over to the
   94795 ** WHERE clause during join processing but we need to remember that they
   94796 ** originated in the ON or USING clause.
   94797 **
   94798 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   94799 ** expression depends on table iRightJoinTable even if that table is not
   94800 ** explicitly mentioned in the expression.  That information is needed
   94801 ** for cases like this:
   94802 **
   94803 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   94804 **
   94805 ** The where clause needs to defer the handling of the t1.x=5
   94806 ** term until after the t2 loop of the join.  In that way, a
   94807 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   94808 ** defer the handling of t1.x=5, it will be processed immediately
   94809 ** after the t1 loop and rows with t1.x!=5 will never appear in
   94810 ** the output, which is incorrect.
   94811 */
   94812 static void setJoinExpr(Expr *p, int iTable){
   94813   while( p ){
   94814     ExprSetProperty(p, EP_FromJoin);
   94815     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   94816     ExprSetIrreducible(p);
   94817     p->iRightJoinTable = (i16)iTable;
   94818     setJoinExpr(p->pLeft, iTable);
   94819     p = p->pRight;
   94820   }
   94821 }
   94822 
   94823 /*
   94824 ** This routine processes the join information for a SELECT statement.
   94825 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   94826 ** NATURAL joins also create extra WHERE clause terms.
   94827 **
   94828 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   94829 ** The left most table is the first entry in Select.pSrc.  The right-most
   94830 ** table is the last entry.  The join operator is held in the entry to
   94831 ** the left.  Thus entry 0 contains the join operator for the join between
   94832 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   94833 ** also attached to the left entry.
   94834 **
   94835 ** This routine returns the number of errors encountered.
   94836 */
   94837 static int sqliteProcessJoin(Parse *pParse, Select *p){
   94838   SrcList *pSrc;                  /* All tables in the FROM clause */
   94839   int i, j;                       /* Loop counters */
   94840   struct SrcList_item *pLeft;     /* Left table being joined */
   94841   struct SrcList_item *pRight;    /* Right table being joined */
   94842 
   94843   pSrc = p->pSrc;
   94844   pLeft = &pSrc->a[0];
   94845   pRight = &pLeft[1];
   94846   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   94847     Table *pLeftTab = pLeft->pTab;
   94848     Table *pRightTab = pRight->pTab;
   94849     int isOuter;
   94850 
   94851     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   94852     isOuter = (pRight->jointype & JT_OUTER)!=0;
   94853 
   94854     /* When the NATURAL keyword is present, add WHERE clause terms for
   94855     ** every column that the two tables have in common.
   94856     */
   94857     if( pRight->jointype & JT_NATURAL ){
   94858       if( pRight->pOn || pRight->pUsing ){
   94859         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   94860            "an ON or USING clause", 0);
   94861         return 1;
   94862       }
   94863       for(j=0; j<pRightTab->nCol; j++){
   94864         char *zName;   /* Name of column in the right table */
   94865         int iLeft;     /* Matching left table */
   94866         int iLeftCol;  /* Matching column in the left table */
   94867 
   94868         zName = pRightTab->aCol[j].zName;
   94869         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   94870           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   94871                        isOuter, &p->pWhere);
   94872         }
   94873       }
   94874     }
   94875 
   94876     /* Disallow both ON and USING clauses in the same join
   94877     */
   94878     if( pRight->pOn && pRight->pUsing ){
   94879       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   94880         "clauses in the same join");
   94881       return 1;
   94882     }
   94883 
   94884     /* Add the ON clause to the end of the WHERE clause, connected by
   94885     ** an AND operator.
   94886     */
   94887     if( pRight->pOn ){
   94888       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   94889       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   94890       pRight->pOn = 0;
   94891     }
   94892 
   94893     /* Create extra terms on the WHERE clause for each column named
   94894     ** in the USING clause.  Example: If the two tables to be joined are
   94895     ** A and B and the USING clause names X, Y, and Z, then add this
   94896     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   94897     ** Report an error if any column mentioned in the USING clause is
   94898     ** not contained in both tables to be joined.
   94899     */
   94900     if( pRight->pUsing ){
   94901       IdList *pList = pRight->pUsing;
   94902       for(j=0; j<pList->nId; j++){
   94903         char *zName;     /* Name of the term in the USING clause */
   94904         int iLeft;       /* Table on the left with matching column name */
   94905         int iLeftCol;    /* Column number of matching column on the left */
   94906         int iRightCol;   /* Column number of matching column on the right */
   94907 
   94908         zName = pList->a[j].zName;
   94909         iRightCol = columnIndex(pRightTab, zName);
   94910         if( iRightCol<0
   94911          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   94912         ){
   94913           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   94914             "not present in both tables", zName);
   94915           return 1;
   94916         }
   94917         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   94918                      isOuter, &p->pWhere);
   94919       }
   94920     }
   94921   }
   94922   return 0;
   94923 }
   94924 
   94925 /*
   94926 ** Insert code into "v" that will push the record on the top of the
   94927 ** stack into the sorter.
   94928 */
   94929 static void pushOntoSorter(
   94930   Parse *pParse,         /* Parser context */
   94931   ExprList *pOrderBy,    /* The ORDER BY clause */
   94932   Select *pSelect,       /* The whole SELECT statement */
   94933   int regData            /* Register holding data to be sorted */
   94934 ){
   94935   Vdbe *v = pParse->pVdbe;
   94936   int nExpr = pOrderBy->nExpr;
   94937   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
   94938   int regRecord = sqlite3GetTempReg(pParse);
   94939   int op;
   94940   sqlite3ExprCacheClear(pParse);
   94941   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
   94942   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
   94943   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   94944   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
   94945   if( pSelect->selFlags & SF_UseSorter ){
   94946     op = OP_SorterInsert;
   94947   }else{
   94948     op = OP_IdxInsert;
   94949   }
   94950   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
   94951   sqlite3ReleaseTempReg(pParse, regRecord);
   94952   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
   94953   if( pSelect->iLimit ){
   94954     int addr1, addr2;
   94955     int iLimit;
   94956     if( pSelect->iOffset ){
   94957       iLimit = pSelect->iOffset+1;
   94958     }else{
   94959       iLimit = pSelect->iLimit;
   94960     }
   94961     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
   94962     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   94963     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   94964     sqlite3VdbeJumpHere(v, addr1);
   94965     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   94966     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   94967     sqlite3VdbeJumpHere(v, addr2);
   94968   }
   94969 }
   94970 
   94971 /*
   94972 ** Add code to implement the OFFSET
   94973 */
   94974 static void codeOffset(
   94975   Vdbe *v,          /* Generate code into this VM */
   94976   Select *p,        /* The SELECT statement being coded */
   94977   int iContinue     /* Jump here to skip the current record */
   94978 ){
   94979   if( p->iOffset && iContinue!=0 ){
   94980     int addr;
   94981     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
   94982     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
   94983     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   94984     VdbeComment((v, "skip OFFSET records"));
   94985     sqlite3VdbeJumpHere(v, addr);
   94986   }
   94987 }
   94988 
   94989 /*
   94990 ** Add code that will check to make sure the N registers starting at iMem
   94991 ** form a distinct entry.  iTab is a sorting index that holds previously
   94992 ** seen combinations of the N values.  A new entry is made in iTab
   94993 ** if the current N values are new.
   94994 **
   94995 ** A jump to addrRepeat is made and the N+1 values are popped from the
   94996 ** stack if the top N elements are not distinct.
   94997 */
   94998 static void codeDistinct(
   94999   Parse *pParse,     /* Parsing and code generating context */
   95000   int iTab,          /* A sorting index used to test for distinctness */
   95001   int addrRepeat,    /* Jump to here if not distinct */
   95002   int N,             /* Number of elements */
   95003   int iMem           /* First element */
   95004 ){
   95005   Vdbe *v;
   95006   int r1;
   95007 
   95008   v = pParse->pVdbe;
   95009   r1 = sqlite3GetTempReg(pParse);
   95010   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
   95011   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   95012   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   95013   sqlite3ReleaseTempReg(pParse, r1);
   95014 }
   95015 
   95016 #ifndef SQLITE_OMIT_SUBQUERY
   95017 /*
   95018 ** Generate an error message when a SELECT is used within a subexpression
   95019 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   95020 ** column.  We do this in a subroutine because the error used to occur
   95021 ** in multiple places.  (The error only occurs in one place now, but we
   95022 ** retain the subroutine to minimize code disruption.)
   95023 */
   95024 static int checkForMultiColumnSelectError(
   95025   Parse *pParse,       /* Parse context. */
   95026   SelectDest *pDest,   /* Destination of SELECT results */
   95027   int nExpr            /* Number of result columns returned by SELECT */
   95028 ){
   95029   int eDest = pDest->eDest;
   95030   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   95031     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   95032        "a SELECT that is part of an expression");
   95033     return 1;
   95034   }else{
   95035     return 0;
   95036   }
   95037 }
   95038 #endif
   95039 
   95040 /*
   95041 ** This routine generates the code for the inside of the inner loop
   95042 ** of a SELECT.
   95043 **
   95044 ** If srcTab and nColumn are both zero, then the pEList expressions
   95045 ** are evaluated in order to get the data for this row.  If nColumn>0
   95046 ** then data is pulled from srcTab and pEList is used only to get the
   95047 ** datatypes for each column.
   95048 */
   95049 static void selectInnerLoop(
   95050   Parse *pParse,          /* The parser context */
   95051   Select *p,              /* The complete select statement being coded */
   95052   ExprList *pEList,       /* List of values being extracted */
   95053   int srcTab,             /* Pull data from this table */
   95054   int nColumn,            /* Number of columns in the source table */
   95055   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   95056   int distinct,           /* If >=0, make sure results are distinct */
   95057   SelectDest *pDest,      /* How to dispose of the results */
   95058   int iContinue,          /* Jump here to continue with next row */
   95059   int iBreak              /* Jump here to break out of the inner loop */
   95060 ){
   95061   Vdbe *v = pParse->pVdbe;
   95062   int i;
   95063   int hasDistinct;        /* True if the DISTINCT keyword is present */
   95064   int regResult;              /* Start of memory holding result set */
   95065   int eDest = pDest->eDest;   /* How to dispose of results */
   95066   int iParm = pDest->iParm;   /* First argument to disposal method */
   95067   int nResultCol;             /* Number of result columns */
   95068 
   95069   assert( v );
   95070   if( NEVER(v==0) ) return;
   95071   assert( pEList!=0 );
   95072   hasDistinct = distinct>=0;
   95073   if( pOrderBy==0 && !hasDistinct ){
   95074     codeOffset(v, p, iContinue);
   95075   }
   95076 
   95077   /* Pull the requested columns.
   95078   */
   95079   if( nColumn>0 ){
   95080     nResultCol = nColumn;
   95081   }else{
   95082     nResultCol = pEList->nExpr;
   95083   }
   95084   if( pDest->iMem==0 ){
   95085     pDest->iMem = pParse->nMem+1;
   95086     pDest->nMem = nResultCol;
   95087     pParse->nMem += nResultCol;
   95088   }else{
   95089     assert( pDest->nMem==nResultCol );
   95090   }
   95091   regResult = pDest->iMem;
   95092   if( nColumn>0 ){
   95093     for(i=0; i<nColumn; i++){
   95094       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   95095     }
   95096   }else if( eDest!=SRT_Exists ){
   95097     /* If the destination is an EXISTS(...) expression, the actual
   95098     ** values returned by the SELECT are not required.
   95099     */
   95100     sqlite3ExprCacheClear(pParse);
   95101     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
   95102   }
   95103   nColumn = nResultCol;
   95104 
   95105   /* If the DISTINCT keyword was present on the SELECT statement
   95106   ** and this row has been seen before, then do not make this row
   95107   ** part of the result.
   95108   */
   95109   if( hasDistinct ){
   95110     assert( pEList!=0 );
   95111     assert( pEList->nExpr==nColumn );
   95112     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
   95113     if( pOrderBy==0 ){
   95114       codeOffset(v, p, iContinue);
   95115     }
   95116   }
   95117 
   95118   switch( eDest ){
   95119     /* In this mode, write each query result to the key of the temporary
   95120     ** table iParm.
   95121     */
   95122 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   95123     case SRT_Union: {
   95124       int r1;
   95125       r1 = sqlite3GetTempReg(pParse);
   95126       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95127       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   95128       sqlite3ReleaseTempReg(pParse, r1);
   95129       break;
   95130     }
   95131 
   95132     /* Construct a record from the query result, but instead of
   95133     ** saving that record, use it as a key to delete elements from
   95134     ** the temporary table iParm.
   95135     */
   95136     case SRT_Except: {
   95137       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
   95138       break;
   95139     }
   95140 #endif
   95141 
   95142     /* Store the result as data using a unique key.
   95143     */
   95144     case SRT_Table:
   95145     case SRT_EphemTab: {
   95146       int r1 = sqlite3GetTempReg(pParse);
   95147       testcase( eDest==SRT_Table );
   95148       testcase( eDest==SRT_EphemTab );
   95149       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95150       if( pOrderBy ){
   95151         pushOntoSorter(pParse, pOrderBy, p, r1);
   95152       }else{
   95153         int r2 = sqlite3GetTempReg(pParse);
   95154         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   95155         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   95156         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95157         sqlite3ReleaseTempReg(pParse, r2);
   95158       }
   95159       sqlite3ReleaseTempReg(pParse, r1);
   95160       break;
   95161     }
   95162 
   95163 #ifndef SQLITE_OMIT_SUBQUERY
   95164     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   95165     ** then there should be a single item on the stack.  Write this
   95166     ** item into the set table with bogus data.
   95167     */
   95168     case SRT_Set: {
   95169       assert( nColumn==1 );
   95170       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
   95171       if( pOrderBy ){
   95172         /* At first glance you would think we could optimize out the
   95173         ** ORDER BY in this case since the order of entries in the set
   95174         ** does not matter.  But there might be a LIMIT clause, in which
   95175         ** case the order does matter */
   95176         pushOntoSorter(pParse, pOrderBy, p, regResult);
   95177       }else{
   95178         int r1 = sqlite3GetTempReg(pParse);
   95179         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
   95180         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   95181         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   95182         sqlite3ReleaseTempReg(pParse, r1);
   95183       }
   95184       break;
   95185     }
   95186 
   95187     /* If any row exist in the result set, record that fact and abort.
   95188     */
   95189     case SRT_Exists: {
   95190       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   95191       /* The LIMIT clause will terminate the loop for us */
   95192       break;
   95193     }
   95194 
   95195     /* If this is a scalar select that is part of an expression, then
   95196     ** store the results in the appropriate memory cell and break out
   95197     ** of the scan loop.
   95198     */
   95199     case SRT_Mem: {
   95200       assert( nColumn==1 );
   95201       if( pOrderBy ){
   95202         pushOntoSorter(pParse, pOrderBy, p, regResult);
   95203       }else{
   95204         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   95205         /* The LIMIT clause will jump out of the loop for us */
   95206       }
   95207       break;
   95208     }
   95209 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   95210 
   95211     /* Send the data to the callback function or to a subroutine.  In the
   95212     ** case of a subroutine, the subroutine itself is responsible for
   95213     ** popping the data from the stack.
   95214     */
   95215     case SRT_Coroutine:
   95216     case SRT_Output: {
   95217       testcase( eDest==SRT_Coroutine );
   95218       testcase( eDest==SRT_Output );
   95219       if( pOrderBy ){
   95220         int r1 = sqlite3GetTempReg(pParse);
   95221         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   95222         pushOntoSorter(pParse, pOrderBy, p, r1);
   95223         sqlite3ReleaseTempReg(pParse, r1);
   95224       }else if( eDest==SRT_Coroutine ){
   95225         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   95226       }else{
   95227         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
   95228         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
   95229       }
   95230       break;
   95231     }
   95232 
   95233 #if !defined(SQLITE_OMIT_TRIGGER)
   95234     /* Discard the results.  This is used for SELECT statements inside
   95235     ** the body of a TRIGGER.  The purpose of such selects is to call
   95236     ** user-defined functions that have side effects.  We do not care
   95237     ** about the actual results of the select.
   95238     */
   95239     default: {
   95240       assert( eDest==SRT_Discard );
   95241       break;
   95242     }
   95243 #endif
   95244   }
   95245 
   95246   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   95247   ** there is a sorter, in which case the sorter has already limited
   95248   ** the output for us.
   95249   */
   95250   if( pOrderBy==0 && p->iLimit ){
   95251     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   95252   }
   95253 }
   95254 
   95255 /*
   95256 ** Given an expression list, generate a KeyInfo structure that records
   95257 ** the collating sequence for each expression in that expression list.
   95258 **
   95259 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   95260 ** KeyInfo structure is appropriate for initializing a virtual index to
   95261 ** implement that clause.  If the ExprList is the result set of a SELECT
   95262 ** then the KeyInfo structure is appropriate for initializing a virtual
   95263 ** index to implement a DISTINCT test.
   95264 **
   95265 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   95266 ** function is responsible for seeing that this structure is eventually
   95267 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   95268 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   95269 */
   95270 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   95271   sqlite3 *db = pParse->db;
   95272   int nExpr;
   95273   KeyInfo *pInfo;
   95274   struct ExprList_item *pItem;
   95275   int i;
   95276 
   95277   nExpr = pList->nExpr;
   95278   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   95279   if( pInfo ){
   95280     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   95281     pInfo->nField = (u16)nExpr;
   95282     pInfo->enc = ENC(db);
   95283     pInfo->db = db;
   95284     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   95285       CollSeq *pColl;
   95286       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   95287       if( !pColl ){
   95288         pColl = db->pDfltColl;
   95289       }
   95290       pInfo->aColl[i] = pColl;
   95291       pInfo->aSortOrder[i] = pItem->sortOrder;
   95292     }
   95293   }
   95294   return pInfo;
   95295 }
   95296 
   95297 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   95298 /*
   95299 ** Name of the connection operator, used for error messages.
   95300 */
   95301 static const char *selectOpName(int id){
   95302   char *z;
   95303   switch( id ){
   95304     case TK_ALL:       z = "UNION ALL";   break;
   95305     case TK_INTERSECT: z = "INTERSECT";   break;
   95306     case TK_EXCEPT:    z = "EXCEPT";      break;
   95307     default:           z = "UNION";       break;
   95308   }
   95309   return z;
   95310 }
   95311 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   95312 
   95313 #ifndef SQLITE_OMIT_EXPLAIN
   95314 /*
   95315 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   95316 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   95317 ** where the caption is of the form:
   95318 **
   95319 **   "USE TEMP B-TREE FOR xxx"
   95320 **
   95321 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   95322 ** is determined by the zUsage argument.
   95323 */
   95324 static void explainTempTable(Parse *pParse, const char *zUsage){
   95325   if( pParse->explain==2 ){
   95326     Vdbe *v = pParse->pVdbe;
   95327     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   95328     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   95329   }
   95330 }
   95331 
   95332 /*
   95333 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   95334 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   95335 ** in sqlite3Select() to assign values to structure member variables that
   95336 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   95337 ** code with #ifndef directives.
   95338 */
   95339 # define explainSetInteger(a, b) a = b
   95340 
   95341 #else
   95342 /* No-op versions of the explainXXX() functions and macros. */
   95343 # define explainTempTable(y,z)
   95344 # define explainSetInteger(y,z)
   95345 #endif
   95346 
   95347 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
   95348 /*
   95349 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   95350 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   95351 ** where the caption is of one of the two forms:
   95352 **
   95353 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   95354 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   95355 **
   95356 ** where iSub1 and iSub2 are the integers passed as the corresponding
   95357 ** function parameters, and op is the text representation of the parameter
   95358 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   95359 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   95360 ** false, or the second form if it is true.
   95361 */
   95362 static void explainComposite(
   95363   Parse *pParse,                  /* Parse context */
   95364   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   95365   int iSub1,                      /* Subquery id 1 */
   95366   int iSub2,                      /* Subquery id 2 */
   95367   int bUseTmp                     /* True if a temp table was used */
   95368 ){
   95369   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   95370   if( pParse->explain==2 ){
   95371     Vdbe *v = pParse->pVdbe;
   95372     char *zMsg = sqlite3MPrintf(
   95373         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   95374         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   95375     );
   95376     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   95377   }
   95378 }
   95379 #else
   95380 /* No-op versions of the explainXXX() functions and macros. */
   95381 # define explainComposite(v,w,x,y,z)
   95382 #endif
   95383 
   95384 /*
   95385 ** If the inner loop was generated using a non-null pOrderBy argument,
   95386 ** then the results were placed in a sorter.  After the loop is terminated
   95387 ** we need to run the sorter and output the results.  The following
   95388 ** routine generates the code needed to do that.
   95389 */
   95390 static void generateSortTail(
   95391   Parse *pParse,    /* Parsing context */
   95392   Select *p,        /* The SELECT statement */
   95393   Vdbe *v,          /* Generate code into this VDBE */
   95394   int nColumn,      /* Number of columns of data */
   95395   SelectDest *pDest /* Write the sorted results here */
   95396 ){
   95397   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   95398   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   95399   int addr;
   95400   int iTab;
   95401   int pseudoTab = 0;
   95402   ExprList *pOrderBy = p->pOrderBy;
   95403 
   95404   int eDest = pDest->eDest;
   95405   int iParm = pDest->iParm;
   95406 
   95407   int regRow;
   95408   int regRowid;
   95409 
   95410   iTab = pOrderBy->iECursor;
   95411   regRow = sqlite3GetTempReg(pParse);
   95412   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   95413     pseudoTab = pParse->nTab++;
   95414     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   95415     regRowid = 0;
   95416   }else{
   95417     regRowid = sqlite3GetTempReg(pParse);
   95418   }
   95419   if( p->selFlags & SF_UseSorter ){
   95420     int regSortOut = ++pParse->nMem;
   95421     int ptab2 = pParse->nTab++;
   95422     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
   95423     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
   95424     codeOffset(v, p, addrContinue);
   95425     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
   95426     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
   95427     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   95428   }else{
   95429     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
   95430     codeOffset(v, p, addrContinue);
   95431     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
   95432   }
   95433   switch( eDest ){
   95434     case SRT_Table:
   95435     case SRT_EphemTab: {
   95436       testcase( eDest==SRT_Table );
   95437       testcase( eDest==SRT_EphemTab );
   95438       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   95439       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   95440       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   95441       break;
   95442     }
   95443 #ifndef SQLITE_OMIT_SUBQUERY
   95444     case SRT_Set: {
   95445       assert( nColumn==1 );
   95446       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
   95447       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   95448       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   95449       break;
   95450     }
   95451     case SRT_Mem: {
   95452       assert( nColumn==1 );
   95453       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   95454       /* The LIMIT clause will terminate the loop for us */
   95455       break;
   95456     }
   95457 #endif
   95458     default: {
   95459       int i;
   95460       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   95461       testcase( eDest==SRT_Output );
   95462       testcase( eDest==SRT_Coroutine );
   95463       for(i=0; i<nColumn; i++){
   95464         assert( regRow!=pDest->iMem+i );
   95465         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
   95466         if( i==0 ){
   95467           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   95468         }
   95469       }
   95470       if( eDest==SRT_Output ){
   95471         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
   95472         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
   95473       }else{
   95474         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   95475       }
   95476       break;
   95477     }
   95478   }
   95479   sqlite3ReleaseTempReg(pParse, regRow);
   95480   sqlite3ReleaseTempReg(pParse, regRowid);
   95481 
   95482   /* The bottom of the loop
   95483   */
   95484   sqlite3VdbeResolveLabel(v, addrContinue);
   95485   if( p->selFlags & SF_UseSorter ){
   95486     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
   95487   }else{
   95488     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
   95489   }
   95490   sqlite3VdbeResolveLabel(v, addrBreak);
   95491   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   95492     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
   95493   }
   95494 }
   95495 
   95496 /*
   95497 ** Return a pointer to a string containing the 'declaration type' of the
   95498 ** expression pExpr. The string may be treated as static by the caller.
   95499 **
   95500 ** The declaration type is the exact datatype definition extracted from the
   95501 ** original CREATE TABLE statement if the expression is a column. The
   95502 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   95503 ** is considered a column can be complex in the presence of subqueries. The
   95504 ** result-set expression in all of the following SELECT statements is
   95505 ** considered a column by this function.
   95506 **
   95507 **   SELECT col FROM tbl;
   95508 **   SELECT (SELECT col FROM tbl;
   95509 **   SELECT (SELECT col FROM tbl);
   95510 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   95511 **
   95512 ** The declaration type for any expression other than a column is NULL.
   95513 */
   95514 static const char *columnType(
   95515   NameContext *pNC,
   95516   Expr *pExpr,
   95517   const char **pzOriginDb,
   95518   const char **pzOriginTab,
   95519   const char **pzOriginCol
   95520 ){
   95521   char const *zType = 0;
   95522   char const *zOriginDb = 0;
   95523   char const *zOriginTab = 0;
   95524   char const *zOriginCol = 0;
   95525   int j;
   95526   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   95527 
   95528   switch( pExpr->op ){
   95529     case TK_AGG_COLUMN:
   95530     case TK_COLUMN: {
   95531       /* The expression is a column. Locate the table the column is being
   95532       ** extracted from in NameContext.pSrcList. This table may be real
   95533       ** database table or a subquery.
   95534       */
   95535       Table *pTab = 0;            /* Table structure column is extracted from */
   95536       Select *pS = 0;             /* Select the column is extracted from */
   95537       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   95538       testcase( pExpr->op==TK_AGG_COLUMN );
   95539       testcase( pExpr->op==TK_COLUMN );
   95540       while( pNC && !pTab ){
   95541         SrcList *pTabList = pNC->pSrcList;
   95542         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   95543         if( j<pTabList->nSrc ){
   95544           pTab = pTabList->a[j].pTab;
   95545           pS = pTabList->a[j].pSelect;
   95546         }else{
   95547           pNC = pNC->pNext;
   95548         }
   95549       }
   95550 
   95551       if( pTab==0 ){
   95552         /* At one time, code such as "SELECT new.x" within a trigger would
   95553         ** cause this condition to run.  Since then, we have restructured how
   95554         ** trigger code is generated and so this condition is no longer
   95555         ** possible. However, it can still be true for statements like
   95556         ** the following:
   95557         **
   95558         **   CREATE TABLE t1(col INTEGER);
   95559         **   SELECT (SELECT t1.col) FROM FROM t1;
   95560         **
   95561         ** when columnType() is called on the expression "t1.col" in the
   95562         ** sub-select. In this case, set the column type to NULL, even
   95563         ** though it should really be "INTEGER".
   95564         **
   95565         ** This is not a problem, as the column type of "t1.col" is never
   95566         ** used. When columnType() is called on the expression
   95567         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   95568         ** branch below.  */
   95569         break;
   95570       }
   95571 
   95572       assert( pTab && pExpr->pTab==pTab );
   95573       if( pS ){
   95574         /* The "table" is actually a sub-select or a view in the FROM clause
   95575         ** of the SELECT statement. Return the declaration type and origin
   95576         ** data for the result-set column of the sub-select.
   95577         */
   95578         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   95579           /* If iCol is less than zero, then the expression requests the
   95580           ** rowid of the sub-select or view. This expression is legal (see
   95581           ** test case misc2.2.2) - it always evaluates to NULL.
   95582           */
   95583           NameContext sNC;
   95584           Expr *p = pS->pEList->a[iCol].pExpr;
   95585           sNC.pSrcList = pS->pSrc;
   95586           sNC.pNext = pNC;
   95587           sNC.pParse = pNC->pParse;
   95588           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   95589         }
   95590       }else if( ALWAYS(pTab->pSchema) ){
   95591         /* A real table */
   95592         assert( !pS );
   95593         if( iCol<0 ) iCol = pTab->iPKey;
   95594         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   95595         if( iCol<0 ){
   95596           zType = "INTEGER";
   95597           zOriginCol = "rowid";
   95598         }else{
   95599           zType = pTab->aCol[iCol].zType;
   95600           zOriginCol = pTab->aCol[iCol].zName;
   95601         }
   95602         zOriginTab = pTab->zName;
   95603         if( pNC->pParse ){
   95604           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   95605           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   95606         }
   95607       }
   95608       break;
   95609     }
   95610 #ifndef SQLITE_OMIT_SUBQUERY
   95611     case TK_SELECT: {
   95612       /* The expression is a sub-select. Return the declaration type and
   95613       ** origin info for the single column in the result set of the SELECT
   95614       ** statement.
   95615       */
   95616       NameContext sNC;
   95617       Select *pS = pExpr->x.pSelect;
   95618       Expr *p = pS->pEList->a[0].pExpr;
   95619       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   95620       sNC.pSrcList = pS->pSrc;
   95621       sNC.pNext = pNC;
   95622       sNC.pParse = pNC->pParse;
   95623       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   95624       break;
   95625     }
   95626 #endif
   95627   }
   95628 
   95629   if( pzOriginDb ){
   95630     assert( pzOriginTab && pzOriginCol );
   95631     *pzOriginDb = zOriginDb;
   95632     *pzOriginTab = zOriginTab;
   95633     *pzOriginCol = zOriginCol;
   95634   }
   95635   return zType;
   95636 }
   95637 
   95638 /*
   95639 ** Generate code that will tell the VDBE the declaration types of columns
   95640 ** in the result set.
   95641 */
   95642 static void generateColumnTypes(
   95643   Parse *pParse,      /* Parser context */
   95644   SrcList *pTabList,  /* List of tables */
   95645   ExprList *pEList    /* Expressions defining the result set */
   95646 ){
   95647 #ifndef SQLITE_OMIT_DECLTYPE
   95648   Vdbe *v = pParse->pVdbe;
   95649   int i;
   95650   NameContext sNC;
   95651   sNC.pSrcList = pTabList;
   95652   sNC.pParse = pParse;
   95653   for(i=0; i<pEList->nExpr; i++){
   95654     Expr *p = pEList->a[i].pExpr;
   95655     const char *zType;
   95656 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   95657     const char *zOrigDb = 0;
   95658     const char *zOrigTab = 0;
   95659     const char *zOrigCol = 0;
   95660     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   95661 
   95662     /* The vdbe must make its own copy of the column-type and other
   95663     ** column specific strings, in case the schema is reset before this
   95664     ** virtual machine is deleted.
   95665     */
   95666     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   95667     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   95668     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   95669 #else
   95670     zType = columnType(&sNC, p, 0, 0, 0);
   95671 #endif
   95672     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   95673   }
   95674 #endif /* SQLITE_OMIT_DECLTYPE */
   95675 }
   95676 
   95677 /*
   95678 ** Generate code that will tell the VDBE the names of columns
   95679 ** in the result set.  This information is used to provide the
   95680 ** azCol[] values in the callback.
   95681 */
   95682 static void generateColumnNames(
   95683   Parse *pParse,      /* Parser context */
   95684   SrcList *pTabList,  /* List of tables */
   95685   ExprList *pEList    /* Expressions defining the result set */
   95686 ){
   95687   Vdbe *v = pParse->pVdbe;
   95688   int i, j;
   95689   sqlite3 *db = pParse->db;
   95690   int fullNames, shortNames;
   95691 
   95692 #ifndef SQLITE_OMIT_EXPLAIN
   95693   /* If this is an EXPLAIN, skip this step */
   95694   if( pParse->explain ){
   95695     return;
   95696   }
   95697 #endif
   95698 
   95699   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   95700   pParse->colNamesSet = 1;
   95701   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   95702   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   95703   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   95704   for(i=0; i<pEList->nExpr; i++){
   95705     Expr *p;
   95706     p = pEList->a[i].pExpr;
   95707     if( NEVER(p==0) ) continue;
   95708     if( pEList->a[i].zName ){
   95709       char *zName = pEList->a[i].zName;
   95710       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   95711     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   95712       Table *pTab;
   95713       char *zCol;
   95714       int iCol = p->iColumn;
   95715       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   95716         if( pTabList->a[j].iCursor==p->iTable ) break;
   95717       }
   95718       assert( j<pTabList->nSrc );
   95719       pTab = pTabList->a[j].pTab;
   95720       if( iCol<0 ) iCol = pTab->iPKey;
   95721       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   95722       if( iCol<0 ){
   95723         zCol = "rowid";
   95724       }else{
   95725         zCol = pTab->aCol[iCol].zName;
   95726       }
   95727       if( !shortNames && !fullNames ){
   95728         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   95729             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   95730       }else if( fullNames ){
   95731         char *zName = 0;
   95732         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   95733         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   95734       }else{
   95735         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   95736       }
   95737     }else{
   95738       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   95739           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   95740     }
   95741   }
   95742   generateColumnTypes(pParse, pTabList, pEList);
   95743 }
   95744 
   95745 /*
   95746 ** Given a an expression list (which is really the list of expressions
   95747 ** that form the result set of a SELECT statement) compute appropriate
   95748 ** column names for a table that would hold the expression list.
   95749 **
   95750 ** All column names will be unique.
   95751 **
   95752 ** Only the column names are computed.  Column.zType, Column.zColl,
   95753 ** and other fields of Column are zeroed.
   95754 **
   95755 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   95756 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   95757 */
   95758 static int selectColumnsFromExprList(
   95759   Parse *pParse,          /* Parsing context */
   95760   ExprList *pEList,       /* Expr list from which to derive column names */
   95761   int *pnCol,             /* Write the number of columns here */
   95762   Column **paCol          /* Write the new column list here */
   95763 ){
   95764   sqlite3 *db = pParse->db;   /* Database connection */
   95765   int i, j;                   /* Loop counters */
   95766   int cnt;                    /* Index added to make the name unique */
   95767   Column *aCol, *pCol;        /* For looping over result columns */
   95768   int nCol;                   /* Number of columns in the result set */
   95769   Expr *p;                    /* Expression for a single result column */
   95770   char *zName;                /* Column name */
   95771   int nName;                  /* Size of name in zName[] */
   95772 
   95773   *pnCol = nCol = pEList ? pEList->nExpr : 0;
   95774   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   95775   if( aCol==0 ) return SQLITE_NOMEM;
   95776   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   95777     /* Get an appropriate name for the column
   95778     */
   95779     p = pEList->a[i].pExpr;
   95780     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
   95781                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
   95782     if( (zName = pEList->a[i].zName)!=0 ){
   95783       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   95784       zName = sqlite3DbStrDup(db, zName);
   95785     }else{
   95786       Expr *pColExpr = p;  /* The expression that is the result column name */
   95787       Table *pTab;         /* Table associated with this expression */
   95788       while( pColExpr->op==TK_DOT ){
   95789         pColExpr = pColExpr->pRight;
   95790         assert( pColExpr!=0 );
   95791       }
   95792       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   95793         /* For columns use the column name name */
   95794         int iCol = pColExpr->iColumn;
   95795         pTab = pColExpr->pTab;
   95796         if( iCol<0 ) iCol = pTab->iPKey;
   95797         zName = sqlite3MPrintf(db, "%s",
   95798                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   95799       }else if( pColExpr->op==TK_ID ){
   95800         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   95801         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   95802       }else{
   95803         /* Use the original text of the column expression as its name */
   95804         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   95805       }
   95806     }
   95807     if( db->mallocFailed ){
   95808       sqlite3DbFree(db, zName);
   95809       break;
   95810     }
   95811 
   95812     /* Make sure the column name is unique.  If the name is not unique,
   95813     ** append a integer to the name so that it becomes unique.
   95814     */
   95815     nName = sqlite3Strlen30(zName);
   95816     for(j=cnt=0; j<i; j++){
   95817       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   95818         char *zNewName;
   95819         zName[nName] = 0;
   95820         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   95821         sqlite3DbFree(db, zName);
   95822         zName = zNewName;
   95823         j = -1;
   95824         if( zName==0 ) break;
   95825       }
   95826     }
   95827     pCol->zName = zName;
   95828   }
   95829   if( db->mallocFailed ){
   95830     for(j=0; j<i; j++){
   95831       sqlite3DbFree(db, aCol[j].zName);
   95832     }
   95833     sqlite3DbFree(db, aCol);
   95834     *paCol = 0;
   95835     *pnCol = 0;
   95836     return SQLITE_NOMEM;
   95837   }
   95838   return SQLITE_OK;
   95839 }
   95840 
   95841 /*
   95842 ** Add type and collation information to a column list based on
   95843 ** a SELECT statement.
   95844 **
   95845 ** The column list presumably came from selectColumnNamesFromExprList().
   95846 ** The column list has only names, not types or collations.  This
   95847 ** routine goes through and adds the types and collations.
   95848 **
   95849 ** This routine requires that all identifiers in the SELECT
   95850 ** statement be resolved.
   95851 */
   95852 static void selectAddColumnTypeAndCollation(
   95853   Parse *pParse,        /* Parsing contexts */
   95854   int nCol,             /* Number of columns */
   95855   Column *aCol,         /* List of columns */
   95856   Select *pSelect       /* SELECT used to determine types and collations */
   95857 ){
   95858   sqlite3 *db = pParse->db;
   95859   NameContext sNC;
   95860   Column *pCol;
   95861   CollSeq *pColl;
   95862   int i;
   95863   Expr *p;
   95864   struct ExprList_item *a;
   95865 
   95866   assert( pSelect!=0 );
   95867   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   95868   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
   95869   if( db->mallocFailed ) return;
   95870   memset(&sNC, 0, sizeof(sNC));
   95871   sNC.pSrcList = pSelect->pSrc;
   95872   a = pSelect->pEList->a;
   95873   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   95874     p = a[i].pExpr;
   95875     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
   95876     pCol->affinity = sqlite3ExprAffinity(p);
   95877     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   95878     pColl = sqlite3ExprCollSeq(pParse, p);
   95879     if( pColl ){
   95880       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   95881     }
   95882   }
   95883 }
   95884 
   95885 /*
   95886 ** Given a SELECT statement, generate a Table structure that describes
   95887 ** the result set of that SELECT.
   95888 */
   95889 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   95890   Table *pTab;
   95891   sqlite3 *db = pParse->db;
   95892   int savedFlags;
   95893 
   95894   savedFlags = db->flags;
   95895   db->flags &= ~SQLITE_FullColNames;
   95896   db->flags |= SQLITE_ShortColNames;
   95897   sqlite3SelectPrep(pParse, pSelect, 0);
   95898   if( pParse->nErr ) return 0;
   95899   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   95900   db->flags = savedFlags;
   95901   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   95902   if( pTab==0 ){
   95903     return 0;
   95904   }
   95905   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   95906   ** is disabled */
   95907   assert( db->lookaside.bEnabled==0 );
   95908   pTab->nRef = 1;
   95909   pTab->zName = 0;
   95910   pTab->nRowEst = 1000000;
   95911   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   95912   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
   95913   pTab->iPKey = -1;
   95914   if( db->mallocFailed ){
   95915     sqlite3DeleteTable(db, pTab);
   95916     return 0;
   95917   }
   95918   return pTab;
   95919 }
   95920 
   95921 /*
   95922 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   95923 ** If an error occurs, return NULL and leave a message in pParse.
   95924 */
   95925 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   95926   Vdbe *v = pParse->pVdbe;
   95927   if( v==0 ){
   95928     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
   95929 #ifndef SQLITE_OMIT_TRACE
   95930     if( v ){
   95931       sqlite3VdbeAddOp0(v, OP_Trace);
   95932     }
   95933 #endif
   95934   }
   95935   return v;
   95936 }
   95937 
   95938 
   95939 /*
   95940 ** Compute the iLimit and iOffset fields of the SELECT based on the
   95941 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   95942 ** that appear in the original SQL statement after the LIMIT and OFFSET
   95943 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   95944 ** are the integer memory register numbers for counters used to compute
   95945 ** the limit and offset.  If there is no limit and/or offset, then
   95946 ** iLimit and iOffset are negative.
   95947 **
   95948 ** This routine changes the values of iLimit and iOffset only if
   95949 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   95950 ** iOffset should have been preset to appropriate default values
   95951 ** (usually but not always -1) prior to calling this routine.
   95952 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   95953 ** redefined.  The UNION ALL operator uses this property to force
   95954 ** the reuse of the same limit and offset registers across multiple
   95955 ** SELECT statements.
   95956 */
   95957 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   95958   Vdbe *v = 0;
   95959   int iLimit = 0;
   95960   int iOffset;
   95961   int addr1, n;
   95962   if( p->iLimit ) return;
   95963 
   95964   /*
   95965   ** "LIMIT -1" always shows all rows.  There is some
   95966   ** contraversy about what the correct behavior should be.
   95967   ** The current implementation interprets "LIMIT 0" to mean
   95968   ** no rows.
   95969   */
   95970   sqlite3ExprCacheClear(pParse);
   95971   assert( p->pOffset==0 || p->pLimit!=0 );
   95972   if( p->pLimit ){
   95973     p->iLimit = iLimit = ++pParse->nMem;
   95974     v = sqlite3GetVdbe(pParse);
   95975     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
   95976     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   95977       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   95978       VdbeComment((v, "LIMIT counter"));
   95979       if( n==0 ){
   95980         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   95981       }else{
   95982         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
   95983       }
   95984     }else{
   95985       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   95986       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
   95987       VdbeComment((v, "LIMIT counter"));
   95988       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
   95989     }
   95990     if( p->pOffset ){
   95991       p->iOffset = iOffset = ++pParse->nMem;
   95992       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   95993       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   95994       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
   95995       VdbeComment((v, "OFFSET counter"));
   95996       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
   95997       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   95998       sqlite3VdbeJumpHere(v, addr1);
   95999       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   96000       VdbeComment((v, "LIMIT+OFFSET"));
   96001       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
   96002       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   96003       sqlite3VdbeJumpHere(v, addr1);
   96004     }
   96005   }
   96006 }
   96007 
   96008 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96009 /*
   96010 ** Return the appropriate collating sequence for the iCol-th column of
   96011 ** the result set for the compound-select statement "p".  Return NULL if
   96012 ** the column has no default collating sequence.
   96013 **
   96014 ** The collating sequence for the compound select is taken from the
   96015 ** left-most term of the select that has a collating sequence.
   96016 */
   96017 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   96018   CollSeq *pRet;
   96019   if( p->pPrior ){
   96020     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   96021   }else{
   96022     pRet = 0;
   96023   }
   96024   assert( iCol>=0 );
   96025   if( pRet==0 && iCol<p->pEList->nExpr ){
   96026     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   96027   }
   96028   return pRet;
   96029 }
   96030 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   96031 
   96032 /* Forward reference */
   96033 static int multiSelectOrderBy(
   96034   Parse *pParse,        /* Parsing context */
   96035   Select *p,            /* The right-most of SELECTs to be coded */
   96036   SelectDest *pDest     /* What to do with query results */
   96037 );
   96038 
   96039 
   96040 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96041 /*
   96042 ** This routine is called to process a compound query form from
   96043 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   96044 ** INTERSECT
   96045 **
   96046 ** "p" points to the right-most of the two queries.  the query on the
   96047 ** left is p->pPrior.  The left query could also be a compound query
   96048 ** in which case this routine will be called recursively.
   96049 **
   96050 ** The results of the total query are to be written into a destination
   96051 ** of type eDest with parameter iParm.
   96052 **
   96053 ** Example 1:  Consider a three-way compound SQL statement.
   96054 **
   96055 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   96056 **
   96057 ** This statement is parsed up as follows:
   96058 **
   96059 **     SELECT c FROM t3
   96060 **      |
   96061 **      `----->  SELECT b FROM t2
   96062 **                |
   96063 **                `------>  SELECT a FROM t1
   96064 **
   96065 ** The arrows in the diagram above represent the Select.pPrior pointer.
   96066 ** So if this routine is called with p equal to the t3 query, then
   96067 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   96068 **
   96069 ** Notice that because of the way SQLite parses compound SELECTs, the
   96070 ** individual selects always group from left to right.
   96071 */
   96072 static int multiSelect(
   96073   Parse *pParse,        /* Parsing context */
   96074   Select *p,            /* The right-most of SELECTs to be coded */
   96075   SelectDest *pDest     /* What to do with query results */
   96076 ){
   96077   int rc = SQLITE_OK;   /* Success code from a subroutine */
   96078   Select *pPrior;       /* Another SELECT immediately to our left */
   96079   Vdbe *v;              /* Generate code to this VDBE */
   96080   SelectDest dest;      /* Alternative data destination */
   96081   Select *pDelete = 0;  /* Chain of simple selects to delete */
   96082   sqlite3 *db;          /* Database connection */
   96083 #ifndef SQLITE_OMIT_EXPLAIN
   96084   int iSub1;            /* EQP id of left-hand query */
   96085   int iSub2;            /* EQP id of right-hand query */
   96086 #endif
   96087 
   96088   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   96089   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   96090   */
   96091   assert( p && p->pPrior );  /* Calling function guarantees this much */
   96092   db = pParse->db;
   96093   pPrior = p->pPrior;
   96094   assert( pPrior->pRightmost!=pPrior );
   96095   assert( pPrior->pRightmost==p->pRightmost );
   96096   dest = *pDest;
   96097   if( pPrior->pOrderBy ){
   96098     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   96099       selectOpName(p->op));
   96100     rc = 1;
   96101     goto multi_select_end;
   96102   }
   96103   if( pPrior->pLimit ){
   96104     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   96105       selectOpName(p->op));
   96106     rc = 1;
   96107     goto multi_select_end;
   96108   }
   96109 
   96110   v = sqlite3GetVdbe(pParse);
   96111   assert( v!=0 );  /* The VDBE already created by calling function */
   96112 
   96113   /* Create the destination temporary table if necessary
   96114   */
   96115   if( dest.eDest==SRT_EphemTab ){
   96116     assert( p->pEList );
   96117     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
   96118     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   96119     dest.eDest = SRT_Table;
   96120   }
   96121 
   96122   /* Make sure all SELECTs in the statement have the same number of elements
   96123   ** in their result sets.
   96124   */
   96125   assert( p->pEList && pPrior->pEList );
   96126   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   96127     if( p->selFlags & SF_Values ){
   96128       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
   96129     }else{
   96130       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   96131         " do not have the same number of result columns", selectOpName(p->op));
   96132     }
   96133     rc = 1;
   96134     goto multi_select_end;
   96135   }
   96136 
   96137   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   96138   */
   96139   if( p->pOrderBy ){
   96140     return multiSelectOrderBy(pParse, p, pDest);
   96141   }
   96142 
   96143   /* Generate code for the left and right SELECT statements.
   96144   */
   96145   switch( p->op ){
   96146     case TK_ALL: {
   96147       int addr = 0;
   96148       int nLimit;
   96149       assert( !pPrior->pLimit );
   96150       pPrior->pLimit = p->pLimit;
   96151       pPrior->pOffset = p->pOffset;
   96152       explainSetInteger(iSub1, pParse->iNextSelectId);
   96153       rc = sqlite3Select(pParse, pPrior, &dest);
   96154       p->pLimit = 0;
   96155       p->pOffset = 0;
   96156       if( rc ){
   96157         goto multi_select_end;
   96158       }
   96159       p->pPrior = 0;
   96160       p->iLimit = pPrior->iLimit;
   96161       p->iOffset = pPrior->iOffset;
   96162       if( p->iLimit ){
   96163         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
   96164         VdbeComment((v, "Jump ahead if LIMIT reached"));
   96165       }
   96166       explainSetInteger(iSub2, pParse->iNextSelectId);
   96167       rc = sqlite3Select(pParse, p, &dest);
   96168       testcase( rc!=SQLITE_OK );
   96169       pDelete = p->pPrior;
   96170       p->pPrior = pPrior;
   96171       p->nSelectRow += pPrior->nSelectRow;
   96172       if( pPrior->pLimit
   96173        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
   96174        && p->nSelectRow > (double)nLimit
   96175       ){
   96176         p->nSelectRow = (double)nLimit;
   96177       }
   96178       if( addr ){
   96179         sqlite3VdbeJumpHere(v, addr);
   96180       }
   96181       break;
   96182     }
   96183     case TK_EXCEPT:
   96184     case TK_UNION: {
   96185       int unionTab;    /* Cursor number of the temporary table holding result */
   96186       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   96187       int priorOp;     /* The SRT_ operation to apply to prior selects */
   96188       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   96189       int addr;
   96190       SelectDest uniondest;
   96191 
   96192       testcase( p->op==TK_EXCEPT );
   96193       testcase( p->op==TK_UNION );
   96194       priorOp = SRT_Union;
   96195       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
   96196         /* We can reuse a temporary table generated by a SELECT to our
   96197         ** right.
   96198         */
   96199         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
   96200                                      ** of a 3-way or more compound */
   96201         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   96202         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   96203         unionTab = dest.iParm;
   96204       }else{
   96205         /* We will need to create our own temporary table to hold the
   96206         ** intermediate results.
   96207         */
   96208         unionTab = pParse->nTab++;
   96209         assert( p->pOrderBy==0 );
   96210         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   96211         assert( p->addrOpenEphm[0] == -1 );
   96212         p->addrOpenEphm[0] = addr;
   96213         p->pRightmost->selFlags |= SF_UsesEphemeral;
   96214         assert( p->pEList );
   96215       }
   96216 
   96217       /* Code the SELECT statements to our left
   96218       */
   96219       assert( !pPrior->pOrderBy );
   96220       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   96221       explainSetInteger(iSub1, pParse->iNextSelectId);
   96222       rc = sqlite3Select(pParse, pPrior, &uniondest);
   96223       if( rc ){
   96224         goto multi_select_end;
   96225       }
   96226 
   96227       /* Code the current SELECT statement
   96228       */
   96229       if( p->op==TK_EXCEPT ){
   96230         op = SRT_Except;
   96231       }else{
   96232         assert( p->op==TK_UNION );
   96233         op = SRT_Union;
   96234       }
   96235       p->pPrior = 0;
   96236       pLimit = p->pLimit;
   96237       p->pLimit = 0;
   96238       pOffset = p->pOffset;
   96239       p->pOffset = 0;
   96240       uniondest.eDest = op;
   96241       explainSetInteger(iSub2, pParse->iNextSelectId);
   96242       rc = sqlite3Select(pParse, p, &uniondest);
   96243       testcase( rc!=SQLITE_OK );
   96244       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   96245       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   96246       sqlite3ExprListDelete(db, p->pOrderBy);
   96247       pDelete = p->pPrior;
   96248       p->pPrior = pPrior;
   96249       p->pOrderBy = 0;
   96250       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
   96251       sqlite3ExprDelete(db, p->pLimit);
   96252       p->pLimit = pLimit;
   96253       p->pOffset = pOffset;
   96254       p->iLimit = 0;
   96255       p->iOffset = 0;
   96256 
   96257       /* Convert the data in the temporary table into whatever form
   96258       ** it is that we currently need.
   96259       */
   96260       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
   96261       if( dest.eDest!=priorOp ){
   96262         int iCont, iBreak, iStart;
   96263         assert( p->pEList );
   96264         if( dest.eDest==SRT_Output ){
   96265           Select *pFirst = p;
   96266           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   96267           generateColumnNames(pParse, 0, pFirst->pEList);
   96268         }
   96269         iBreak = sqlite3VdbeMakeLabel(v);
   96270         iCont = sqlite3VdbeMakeLabel(v);
   96271         computeLimitRegisters(pParse, p, iBreak);
   96272         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
   96273         iStart = sqlite3VdbeCurrentAddr(v);
   96274         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
   96275                         0, -1, &dest, iCont, iBreak);
   96276         sqlite3VdbeResolveLabel(v, iCont);
   96277         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
   96278         sqlite3VdbeResolveLabel(v, iBreak);
   96279         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   96280       }
   96281       break;
   96282     }
   96283     default: assert( p->op==TK_INTERSECT ); {
   96284       int tab1, tab2;
   96285       int iCont, iBreak, iStart;
   96286       Expr *pLimit, *pOffset;
   96287       int addr;
   96288       SelectDest intersectdest;
   96289       int r1;
   96290 
   96291       /* INTERSECT is different from the others since it requires
   96292       ** two temporary tables.  Hence it has its own case.  Begin
   96293       ** by allocating the tables we will need.
   96294       */
   96295       tab1 = pParse->nTab++;
   96296       tab2 = pParse->nTab++;
   96297       assert( p->pOrderBy==0 );
   96298 
   96299       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   96300       assert( p->addrOpenEphm[0] == -1 );
   96301       p->addrOpenEphm[0] = addr;
   96302       p->pRightmost->selFlags |= SF_UsesEphemeral;
   96303       assert( p->pEList );
   96304 
   96305       /* Code the SELECTs to our left into temporary table "tab1".
   96306       */
   96307       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   96308       explainSetInteger(iSub1, pParse->iNextSelectId);
   96309       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   96310       if( rc ){
   96311         goto multi_select_end;
   96312       }
   96313 
   96314       /* Code the current SELECT into temporary table "tab2"
   96315       */
   96316       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   96317       assert( p->addrOpenEphm[1] == -1 );
   96318       p->addrOpenEphm[1] = addr;
   96319       p->pPrior = 0;
   96320       pLimit = p->pLimit;
   96321       p->pLimit = 0;
   96322       pOffset = p->pOffset;
   96323       p->pOffset = 0;
   96324       intersectdest.iParm = tab2;
   96325       explainSetInteger(iSub2, pParse->iNextSelectId);
   96326       rc = sqlite3Select(pParse, p, &intersectdest);
   96327       testcase( rc!=SQLITE_OK );
   96328       pDelete = p->pPrior;
   96329       p->pPrior = pPrior;
   96330       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   96331       sqlite3ExprDelete(db, p->pLimit);
   96332       p->pLimit = pLimit;
   96333       p->pOffset = pOffset;
   96334 
   96335       /* Generate code to take the intersection of the two temporary
   96336       ** tables.
   96337       */
   96338       assert( p->pEList );
   96339       if( dest.eDest==SRT_Output ){
   96340         Select *pFirst = p;
   96341         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   96342         generateColumnNames(pParse, 0, pFirst->pEList);
   96343       }
   96344       iBreak = sqlite3VdbeMakeLabel(v);
   96345       iCont = sqlite3VdbeMakeLabel(v);
   96346       computeLimitRegisters(pParse, p, iBreak);
   96347       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
   96348       r1 = sqlite3GetTempReg(pParse);
   96349       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   96350       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
   96351       sqlite3ReleaseTempReg(pParse, r1);
   96352       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
   96353                       0, -1, &dest, iCont, iBreak);
   96354       sqlite3VdbeResolveLabel(v, iCont);
   96355       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
   96356       sqlite3VdbeResolveLabel(v, iBreak);
   96357       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   96358       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   96359       break;
   96360     }
   96361   }
   96362 
   96363   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   96364 
   96365   /* Compute collating sequences used by
   96366   ** temporary tables needed to implement the compound select.
   96367   ** Attach the KeyInfo structure to all temporary tables.
   96368   **
   96369   ** This section is run by the right-most SELECT statement only.
   96370   ** SELECT statements to the left always skip this part.  The right-most
   96371   ** SELECT might also skip this part if it has no ORDER BY clause and
   96372   ** no temp tables are required.
   96373   */
   96374   if( p->selFlags & SF_UsesEphemeral ){
   96375     int i;                        /* Loop counter */
   96376     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   96377     Select *pLoop;                /* For looping through SELECT statements */
   96378     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   96379     int nCol;                     /* Number of columns in result set */
   96380 
   96381     assert( p->pRightmost==p );
   96382     nCol = p->pEList->nExpr;
   96383     pKeyInfo = sqlite3DbMallocZero(db,
   96384                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
   96385     if( !pKeyInfo ){
   96386       rc = SQLITE_NOMEM;
   96387       goto multi_select_end;
   96388     }
   96389 
   96390     pKeyInfo->enc = ENC(db);
   96391     pKeyInfo->nField = (u16)nCol;
   96392 
   96393     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   96394       *apColl = multiSelectCollSeq(pParse, p, i);
   96395       if( 0==*apColl ){
   96396         *apColl = db->pDfltColl;
   96397       }
   96398     }
   96399 
   96400     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   96401       for(i=0; i<2; i++){
   96402         int addr = pLoop->addrOpenEphm[i];
   96403         if( addr<0 ){
   96404           /* If [0] is unused then [1] is also unused.  So we can
   96405           ** always safely abort as soon as the first unused slot is found */
   96406           assert( pLoop->addrOpenEphm[1]<0 );
   96407           break;
   96408         }
   96409         sqlite3VdbeChangeP2(v, addr, nCol);
   96410         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
   96411         pLoop->addrOpenEphm[i] = -1;
   96412       }
   96413     }
   96414     sqlite3DbFree(db, pKeyInfo);
   96415   }
   96416 
   96417 multi_select_end:
   96418   pDest->iMem = dest.iMem;
   96419   pDest->nMem = dest.nMem;
   96420   sqlite3SelectDelete(db, pDelete);
   96421   return rc;
   96422 }
   96423 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   96424 
   96425 /*
   96426 ** Code an output subroutine for a coroutine implementation of a
   96427 ** SELECT statment.
   96428 **
   96429 ** The data to be output is contained in pIn->iMem.  There are
   96430 ** pIn->nMem columns to be output.  pDest is where the output should
   96431 ** be sent.
   96432 **
   96433 ** regReturn is the number of the register holding the subroutine
   96434 ** return address.
   96435 **
   96436 ** If regPrev>0 then it is the first register in a vector that
   96437 ** records the previous output.  mem[regPrev] is a flag that is false
   96438 ** if there has been no previous output.  If regPrev>0 then code is
   96439 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   96440 ** keys.
   96441 **
   96442 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   96443 ** iBreak.
   96444 */
   96445 static int generateOutputSubroutine(
   96446   Parse *pParse,          /* Parsing context */
   96447   Select *p,              /* The SELECT statement */
   96448   SelectDest *pIn,        /* Coroutine supplying data */
   96449   SelectDest *pDest,      /* Where to send the data */
   96450   int regReturn,          /* The return address register */
   96451   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   96452   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   96453   int p4type,             /* The p4 type for pKeyInfo */
   96454   int iBreak              /* Jump here if we hit the LIMIT */
   96455 ){
   96456   Vdbe *v = pParse->pVdbe;
   96457   int iContinue;
   96458   int addr;
   96459 
   96460   addr = sqlite3VdbeCurrentAddr(v);
   96461   iContinue = sqlite3VdbeMakeLabel(v);
   96462 
   96463   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   96464   */
   96465   if( regPrev ){
   96466     int j1, j2;
   96467     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
   96468     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
   96469                               (char*)pKeyInfo, p4type);
   96470     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
   96471     sqlite3VdbeJumpHere(v, j1);
   96472     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
   96473     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   96474   }
   96475   if( pParse->db->mallocFailed ) return 0;
   96476 
   96477   /* Suppress the the first OFFSET entries if there is an OFFSET clause
   96478   */
   96479   codeOffset(v, p, iContinue);
   96480 
   96481   switch( pDest->eDest ){
   96482     /* Store the result as data using a unique key.
   96483     */
   96484     case SRT_Table:
   96485     case SRT_EphemTab: {
   96486       int r1 = sqlite3GetTempReg(pParse);
   96487       int r2 = sqlite3GetTempReg(pParse);
   96488       testcase( pDest->eDest==SRT_Table );
   96489       testcase( pDest->eDest==SRT_EphemTab );
   96490       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
   96491       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
   96492       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
   96493       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   96494       sqlite3ReleaseTempReg(pParse, r2);
   96495       sqlite3ReleaseTempReg(pParse, r1);
   96496       break;
   96497     }
   96498 
   96499 #ifndef SQLITE_OMIT_SUBQUERY
   96500     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   96501     ** then there should be a single item on the stack.  Write this
   96502     ** item into the set table with bogus data.
   96503     */
   96504     case SRT_Set: {
   96505       int r1;
   96506       assert( pIn->nMem==1 );
   96507       p->affinity =
   96508          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
   96509       r1 = sqlite3GetTempReg(pParse);
   96510       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
   96511       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
   96512       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
   96513       sqlite3ReleaseTempReg(pParse, r1);
   96514       break;
   96515     }
   96516 
   96517 #if 0  /* Never occurs on an ORDER BY query */
   96518     /* If any row exist in the result set, record that fact and abort.
   96519     */
   96520     case SRT_Exists: {
   96521       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
   96522       /* The LIMIT clause will terminate the loop for us */
   96523       break;
   96524     }
   96525 #endif
   96526 
   96527     /* If this is a scalar select that is part of an expression, then
   96528     ** store the results in the appropriate memory cell and break out
   96529     ** of the scan loop.
   96530     */
   96531     case SRT_Mem: {
   96532       assert( pIn->nMem==1 );
   96533       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
   96534       /* The LIMIT clause will jump out of the loop for us */
   96535       break;
   96536     }
   96537 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   96538 
   96539     /* The results are stored in a sequence of registers
   96540     ** starting at pDest->iMem.  Then the co-routine yields.
   96541     */
   96542     case SRT_Coroutine: {
   96543       if( pDest->iMem==0 ){
   96544         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
   96545         pDest->nMem = pIn->nMem;
   96546       }
   96547       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
   96548       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   96549       break;
   96550     }
   96551 
   96552     /* If none of the above, then the result destination must be
   96553     ** SRT_Output.  This routine is never called with any other
   96554     ** destination other than the ones handled above or SRT_Output.
   96555     **
   96556     ** For SRT_Output, results are stored in a sequence of registers.
   96557     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   96558     ** return the next row of result.
   96559     */
   96560     default: {
   96561       assert( pDest->eDest==SRT_Output );
   96562       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
   96563       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
   96564       break;
   96565     }
   96566   }
   96567 
   96568   /* Jump to the end of the loop if the LIMIT is reached.
   96569   */
   96570   if( p->iLimit ){
   96571     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   96572   }
   96573 
   96574   /* Generate the subroutine return
   96575   */
   96576   sqlite3VdbeResolveLabel(v, iContinue);
   96577   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   96578 
   96579   return addr;
   96580 }
   96581 
   96582 /*
   96583 ** Alternative compound select code generator for cases when there
   96584 ** is an ORDER BY clause.
   96585 **
   96586 ** We assume a query of the following form:
   96587 **
   96588 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   96589 **
   96590 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   96591 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   96592 ** co-routines.  Then run the co-routines in parallel and merge the results
   96593 ** into the output.  In addition to the two coroutines (called selectA and
   96594 ** selectB) there are 7 subroutines:
   96595 **
   96596 **    outA:    Move the output of the selectA coroutine into the output
   96597 **             of the compound query.
   96598 **
   96599 **    outB:    Move the output of the selectB coroutine into the output
   96600 **             of the compound query.  (Only generated for UNION and
   96601 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   96602 **             appears only in B.)
   96603 **
   96604 **    AltB:    Called when there is data from both coroutines and A<B.
   96605 **
   96606 **    AeqB:    Called when there is data from both coroutines and A==B.
   96607 **
   96608 **    AgtB:    Called when there is data from both coroutines and A>B.
   96609 **
   96610 **    EofA:    Called when data is exhausted from selectA.
   96611 **
   96612 **    EofB:    Called when data is exhausted from selectB.
   96613 **
   96614 ** The implementation of the latter five subroutines depend on which
   96615 ** <operator> is used:
   96616 **
   96617 **
   96618 **             UNION ALL         UNION            EXCEPT          INTERSECT
   96619 **          -------------  -----------------  --------------  -----------------
   96620 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   96621 **
   96622 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   96623 **
   96624 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   96625 **
   96626 **   EofA:   outB, nextB      outB, nextB          halt             halt
   96627 **
   96628 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   96629 **
   96630 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   96631 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   96632 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   96633 ** following nextX causes a jump to the end of the select processing.
   96634 **
   96635 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   96636 ** within the output subroutine.  The regPrev register set holds the previously
   96637 ** output value.  A comparison is made against this value and the output
   96638 ** is skipped if the next results would be the same as the previous.
   96639 **
   96640 ** The implementation plan is to implement the two coroutines and seven
   96641 ** subroutines first, then put the control logic at the bottom.  Like this:
   96642 **
   96643 **          goto Init
   96644 **     coA: coroutine for left query (A)
   96645 **     coB: coroutine for right query (B)
   96646 **    outA: output one row of A
   96647 **    outB: output one row of B (UNION and UNION ALL only)
   96648 **    EofA: ...
   96649 **    EofB: ...
   96650 **    AltB: ...
   96651 **    AeqB: ...
   96652 **    AgtB: ...
   96653 **    Init: initialize coroutine registers
   96654 **          yield coA
   96655 **          if eof(A) goto EofA
   96656 **          yield coB
   96657 **          if eof(B) goto EofB
   96658 **    Cmpr: Compare A, B
   96659 **          Jump AltB, AeqB, AgtB
   96660 **     End: ...
   96661 **
   96662 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   96663 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   96664 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   96665 ** and AgtB jump to either L2 or to one of EofA or EofB.
   96666 */
   96667 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   96668 static int multiSelectOrderBy(
   96669   Parse *pParse,        /* Parsing context */
   96670   Select *p,            /* The right-most of SELECTs to be coded */
   96671   SelectDest *pDest     /* What to do with query results */
   96672 ){
   96673   int i, j;             /* Loop counters */
   96674   Select *pPrior;       /* Another SELECT immediately to our left */
   96675   Vdbe *v;              /* Generate code to this VDBE */
   96676   SelectDest destA;     /* Destination for coroutine A */
   96677   SelectDest destB;     /* Destination for coroutine B */
   96678   int regAddrA;         /* Address register for select-A coroutine */
   96679   int regEofA;          /* Flag to indicate when select-A is complete */
   96680   int regAddrB;         /* Address register for select-B coroutine */
   96681   int regEofB;          /* Flag to indicate when select-B is complete */
   96682   int addrSelectA;      /* Address of the select-A coroutine */
   96683   int addrSelectB;      /* Address of the select-B coroutine */
   96684   int regOutA;          /* Address register for the output-A subroutine */
   96685   int regOutB;          /* Address register for the output-B subroutine */
   96686   int addrOutA;         /* Address of the output-A subroutine */
   96687   int addrOutB = 0;     /* Address of the output-B subroutine */
   96688   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   96689   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   96690   int addrAltB;         /* Address of the A<B subroutine */
   96691   int addrAeqB;         /* Address of the A==B subroutine */
   96692   int addrAgtB;         /* Address of the A>B subroutine */
   96693   int regLimitA;        /* Limit register for select-A */
   96694   int regLimitB;        /* Limit register for select-A */
   96695   int regPrev;          /* A range of registers to hold previous output */
   96696   int savedLimit;       /* Saved value of p->iLimit */
   96697   int savedOffset;      /* Saved value of p->iOffset */
   96698   int labelCmpr;        /* Label for the start of the merge algorithm */
   96699   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   96700   int j1;               /* Jump instructions that get retargetted */
   96701   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   96702   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   96703   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   96704   sqlite3 *db;          /* Database connection */
   96705   ExprList *pOrderBy;   /* The ORDER BY clause */
   96706   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   96707   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   96708 #ifndef SQLITE_OMIT_EXPLAIN
   96709   int iSub1;            /* EQP id of left-hand query */
   96710   int iSub2;            /* EQP id of right-hand query */
   96711 #endif
   96712 
   96713   assert( p->pOrderBy!=0 );
   96714   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   96715   db = pParse->db;
   96716   v = pParse->pVdbe;
   96717   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   96718   labelEnd = sqlite3VdbeMakeLabel(v);
   96719   labelCmpr = sqlite3VdbeMakeLabel(v);
   96720 
   96721 
   96722   /* Patch up the ORDER BY clause
   96723   */
   96724   op = p->op;
   96725   pPrior = p->pPrior;
   96726   assert( pPrior->pOrderBy==0 );
   96727   pOrderBy = p->pOrderBy;
   96728   assert( pOrderBy );
   96729   nOrderBy = pOrderBy->nExpr;
   96730 
   96731   /* For operators other than UNION ALL we have to make sure that
   96732   ** the ORDER BY clause covers every term of the result set.  Add
   96733   ** terms to the ORDER BY clause as necessary.
   96734   */
   96735   if( op!=TK_ALL ){
   96736     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   96737       struct ExprList_item *pItem;
   96738       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   96739         assert( pItem->iOrderByCol>0 );
   96740         if( pItem->iOrderByCol==i ) break;
   96741       }
   96742       if( j==nOrderBy ){
   96743         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   96744         if( pNew==0 ) return SQLITE_NOMEM;
   96745         pNew->flags |= EP_IntValue;
   96746         pNew->u.iValue = i;
   96747         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   96748         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
   96749       }
   96750     }
   96751   }
   96752 
   96753   /* Compute the comparison permutation and keyinfo that is used with
   96754   ** the permutation used to determine if the next
   96755   ** row of results comes from selectA or selectB.  Also add explicit
   96756   ** collations to the ORDER BY clause terms so that when the subqueries
   96757   ** to the right and the left are evaluated, they use the correct
   96758   ** collation.
   96759   */
   96760   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   96761   if( aPermute ){
   96762     struct ExprList_item *pItem;
   96763     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   96764       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
   96765       aPermute[i] = pItem->iOrderByCol - 1;
   96766     }
   96767     pKeyMerge =
   96768       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
   96769     if( pKeyMerge ){
   96770       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
   96771       pKeyMerge->nField = (u16)nOrderBy;
   96772       pKeyMerge->enc = ENC(db);
   96773       for(i=0; i<nOrderBy; i++){
   96774         CollSeq *pColl;
   96775         Expr *pTerm = pOrderBy->a[i].pExpr;
   96776         if( pTerm->flags & EP_ExpCollate ){
   96777           pColl = pTerm->pColl;
   96778         }else{
   96779           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
   96780           pTerm->flags |= EP_ExpCollate;
   96781           pTerm->pColl = pColl;
   96782         }
   96783         pKeyMerge->aColl[i] = pColl;
   96784         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   96785       }
   96786     }
   96787   }else{
   96788     pKeyMerge = 0;
   96789   }
   96790 
   96791   /* Reattach the ORDER BY clause to the query.
   96792   */
   96793   p->pOrderBy = pOrderBy;
   96794   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   96795 
   96796   /* Allocate a range of temporary registers and the KeyInfo needed
   96797   ** for the logic that removes duplicate result rows when the
   96798   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   96799   */
   96800   if( op==TK_ALL ){
   96801     regPrev = 0;
   96802   }else{
   96803     int nExpr = p->pEList->nExpr;
   96804     assert( nOrderBy>=nExpr || db->mallocFailed );
   96805     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
   96806     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   96807     pKeyDup = sqlite3DbMallocZero(db,
   96808                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
   96809     if( pKeyDup ){
   96810       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
   96811       pKeyDup->nField = (u16)nExpr;
   96812       pKeyDup->enc = ENC(db);
   96813       for(i=0; i<nExpr; i++){
   96814         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   96815         pKeyDup->aSortOrder[i] = 0;
   96816       }
   96817     }
   96818   }
   96819 
   96820   /* Separate the left and the right query from one another
   96821   */
   96822   p->pPrior = 0;
   96823   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   96824   if( pPrior->pPrior==0 ){
   96825     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   96826   }
   96827 
   96828   /* Compute the limit registers */
   96829   computeLimitRegisters(pParse, p, labelEnd);
   96830   if( p->iLimit && op==TK_ALL ){
   96831     regLimitA = ++pParse->nMem;
   96832     regLimitB = ++pParse->nMem;
   96833     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   96834                                   regLimitA);
   96835     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   96836   }else{
   96837     regLimitA = regLimitB = 0;
   96838   }
   96839   sqlite3ExprDelete(db, p->pLimit);
   96840   p->pLimit = 0;
   96841   sqlite3ExprDelete(db, p->pOffset);
   96842   p->pOffset = 0;
   96843 
   96844   regAddrA = ++pParse->nMem;
   96845   regEofA = ++pParse->nMem;
   96846   regAddrB = ++pParse->nMem;
   96847   regEofB = ++pParse->nMem;
   96848   regOutA = ++pParse->nMem;
   96849   regOutB = ++pParse->nMem;
   96850   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   96851   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   96852 
   96853   /* Jump past the various subroutines and coroutines to the main
   96854   ** merge loop
   96855   */
   96856   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
   96857   addrSelectA = sqlite3VdbeCurrentAddr(v);
   96858 
   96859 
   96860   /* Generate a coroutine to evaluate the SELECT statement to the
   96861   ** left of the compound operator - the "A" select.
   96862   */
   96863   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
   96864   pPrior->iLimit = regLimitA;
   96865   explainSetInteger(iSub1, pParse->iNextSelectId);
   96866   sqlite3Select(pParse, pPrior, &destA);
   96867   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
   96868   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96869   VdbeNoopComment((v, "End coroutine for left SELECT"));
   96870 
   96871   /* Generate a coroutine to evaluate the SELECT statement on
   96872   ** the right - the "B" select
   96873   */
   96874   addrSelectB = sqlite3VdbeCurrentAddr(v);
   96875   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
   96876   savedLimit = p->iLimit;
   96877   savedOffset = p->iOffset;
   96878   p->iLimit = regLimitB;
   96879   p->iOffset = 0;
   96880   explainSetInteger(iSub2, pParse->iNextSelectId);
   96881   sqlite3Select(pParse, p, &destB);
   96882   p->iLimit = savedLimit;
   96883   p->iOffset = savedOffset;
   96884   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
   96885   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96886   VdbeNoopComment((v, "End coroutine for right SELECT"));
   96887 
   96888   /* Generate a subroutine that outputs the current row of the A
   96889   ** select as the next output row of the compound select.
   96890   */
   96891   VdbeNoopComment((v, "Output routine for A"));
   96892   addrOutA = generateOutputSubroutine(pParse,
   96893                  p, &destA, pDest, regOutA,
   96894                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
   96895 
   96896   /* Generate a subroutine that outputs the current row of the B
   96897   ** select as the next output row of the compound select.
   96898   */
   96899   if( op==TK_ALL || op==TK_UNION ){
   96900     VdbeNoopComment((v, "Output routine for B"));
   96901     addrOutB = generateOutputSubroutine(pParse,
   96902                  p, &destB, pDest, regOutB,
   96903                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
   96904   }
   96905 
   96906   /* Generate a subroutine to run when the results from select A
   96907   ** are exhausted and only data in select B remains.
   96908   */
   96909   VdbeNoopComment((v, "eof-A subroutine"));
   96910   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   96911     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
   96912   }else{
   96913     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
   96914     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   96915     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96916     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   96917     p->nSelectRow += pPrior->nSelectRow;
   96918   }
   96919 
   96920   /* Generate a subroutine to run when the results from select B
   96921   ** are exhausted and only data in select A remains.
   96922   */
   96923   if( op==TK_INTERSECT ){
   96924     addrEofB = addrEofA;
   96925     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   96926   }else{
   96927     VdbeNoopComment((v, "eof-B subroutine"));
   96928     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
   96929     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   96930     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96931     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   96932   }
   96933 
   96934   /* Generate code to handle the case of A<B
   96935   */
   96936   VdbeNoopComment((v, "A-lt-B subroutine"));
   96937   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   96938   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96939   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   96940   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96941 
   96942   /* Generate code to handle the case of A==B
   96943   */
   96944   if( op==TK_ALL ){
   96945     addrAeqB = addrAltB;
   96946   }else if( op==TK_INTERSECT ){
   96947     addrAeqB = addrAltB;
   96948     addrAltB++;
   96949   }else{
   96950     VdbeNoopComment((v, "A-eq-B subroutine"));
   96951     addrAeqB =
   96952     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   96953     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   96954     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96955   }
   96956 
   96957   /* Generate code to handle the case of A>B
   96958   */
   96959   VdbeNoopComment((v, "A-gt-B subroutine"));
   96960   addrAgtB = sqlite3VdbeCurrentAddr(v);
   96961   if( op==TK_ALL || op==TK_UNION ){
   96962     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   96963   }
   96964   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   96965   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   96966   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   96967 
   96968   /* This code runs once to initialize everything.
   96969   */
   96970   sqlite3VdbeJumpHere(v, j1);
   96971   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
   96972   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
   96973   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
   96974   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
   96975   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   96976   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   96977 
   96978   /* Implement the main merge loop
   96979   */
   96980   sqlite3VdbeResolveLabel(v, labelCmpr);
   96981   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   96982   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
   96983                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
   96984   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
   96985 
   96986   /* Release temporary registers
   96987   */
   96988   if( regPrev ){
   96989     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
   96990   }
   96991 
   96992   /* Jump to the this point in order to terminate the query.
   96993   */
   96994   sqlite3VdbeResolveLabel(v, labelEnd);
   96995 
   96996   /* Set the number of output columns
   96997   */
   96998   if( pDest->eDest==SRT_Output ){
   96999     Select *pFirst = pPrior;
   97000     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   97001     generateColumnNames(pParse, 0, pFirst->pEList);
   97002   }
   97003 
   97004   /* Reassembly the compound query so that it will be freed correctly
   97005   ** by the calling function */
   97006   if( p->pPrior ){
   97007     sqlite3SelectDelete(db, p->pPrior);
   97008   }
   97009   p->pPrior = pPrior;
   97010 
   97011   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   97012   **** subqueries ****/
   97013   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   97014   return SQLITE_OK;
   97015 }
   97016 #endif
   97017 
   97018 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   97019 /* Forward Declarations */
   97020 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   97021 static void substSelect(sqlite3*, Select *, int, ExprList *);
   97022 
   97023 /*
   97024 ** Scan through the expression pExpr.  Replace every reference to
   97025 ** a column in table number iTable with a copy of the iColumn-th
   97026 ** entry in pEList.  (But leave references to the ROWID column
   97027 ** unchanged.)
   97028 **
   97029 ** This routine is part of the flattening procedure.  A subquery
   97030 ** whose result set is defined by pEList appears as entry in the
   97031 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   97032 ** FORM clause entry is iTable.  This routine make the necessary
   97033 ** changes to pExpr so that it refers directly to the source table
   97034 ** of the subquery rather the result set of the subquery.
   97035 */
   97036 static Expr *substExpr(
   97037   sqlite3 *db,        /* Report malloc errors to this connection */
   97038   Expr *pExpr,        /* Expr in which substitution occurs */
   97039   int iTable,         /* Table to be substituted */
   97040   ExprList *pEList    /* Substitute expressions */
   97041 ){
   97042   if( pExpr==0 ) return 0;
   97043   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   97044     if( pExpr->iColumn<0 ){
   97045       pExpr->op = TK_NULL;
   97046     }else{
   97047       Expr *pNew;
   97048       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   97049       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   97050       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   97051       if( pNew && pExpr->pColl ){
   97052         pNew->pColl = pExpr->pColl;
   97053       }
   97054       sqlite3ExprDelete(db, pExpr);
   97055       pExpr = pNew;
   97056     }
   97057   }else{
   97058     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   97059     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   97060     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   97061       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   97062     }else{
   97063       substExprList(db, pExpr->x.pList, iTable, pEList);
   97064     }
   97065   }
   97066   return pExpr;
   97067 }
   97068 static void substExprList(
   97069   sqlite3 *db,         /* Report malloc errors here */
   97070   ExprList *pList,     /* List to scan and in which to make substitutes */
   97071   int iTable,          /* Table to be substituted */
   97072   ExprList *pEList     /* Substitute values */
   97073 ){
   97074   int i;
   97075   if( pList==0 ) return;
   97076   for(i=0; i<pList->nExpr; i++){
   97077     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   97078   }
   97079 }
   97080 static void substSelect(
   97081   sqlite3 *db,         /* Report malloc errors here */
   97082   Select *p,           /* SELECT statement in which to make substitutions */
   97083   int iTable,          /* Table to be replaced */
   97084   ExprList *pEList     /* Substitute values */
   97085 ){
   97086   SrcList *pSrc;
   97087   struct SrcList_item *pItem;
   97088   int i;
   97089   if( !p ) return;
   97090   substExprList(db, p->pEList, iTable, pEList);
   97091   substExprList(db, p->pGroupBy, iTable, pEList);
   97092   substExprList(db, p->pOrderBy, iTable, pEList);
   97093   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   97094   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   97095   substSelect(db, p->pPrior, iTable, pEList);
   97096   pSrc = p->pSrc;
   97097   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   97098   if( ALWAYS(pSrc) ){
   97099     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   97100       substSelect(db, pItem->pSelect, iTable, pEList);
   97101     }
   97102   }
   97103 }
   97104 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   97105 
   97106 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   97107 /*
   97108 ** This routine attempts to flatten subqueries as a performance optimization.
   97109 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
   97110 **
   97111 ** To understand the concept of flattening, consider the following
   97112 ** query:
   97113 **
   97114 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   97115 **
   97116 ** The default way of implementing this query is to execute the
   97117 ** subquery first and store the results in a temporary table, then
   97118 ** run the outer query on that temporary table.  This requires two
   97119 ** passes over the data.  Furthermore, because the temporary table
   97120 ** has no indices, the WHERE clause on the outer query cannot be
   97121 ** optimized.
   97122 **
   97123 ** This routine attempts to rewrite queries such as the above into
   97124 ** a single flat select, like this:
   97125 **
   97126 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   97127 **
   97128 ** The code generated for this simpification gives the same result
   97129 ** but only has to scan the data once.  And because indices might
   97130 ** exist on the table t1, a complete scan of the data might be
   97131 ** avoided.
   97132 **
   97133 ** Flattening is only attempted if all of the following are true:
   97134 **
   97135 **   (1)  The subquery and the outer query do not both use aggregates.
   97136 **
   97137 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   97138 **
   97139 **   (3)  The subquery is not the right operand of a left outer join
   97140 **        (Originally ticket #306.  Strengthened by ticket #3300)
   97141 **
   97142 **   (4)  The subquery is not DISTINCT.
   97143 **
   97144 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   97145 **        sub-queries that were excluded from this optimization. Restriction
   97146 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   97147 **
   97148 **   (6)  The subquery does not use aggregates or the outer query is not
   97149 **        DISTINCT.
   97150 **
   97151 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
   97152 **        A FROM clause, consider adding a FROM close with the special
   97153 **        table sqlite_once that consists of a single row containing a
   97154 **        single NULL.
   97155 **
   97156 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   97157 **
   97158 **   (9)  The subquery does not use LIMIT or the outer query does not use
   97159 **        aggregates.
   97160 **
   97161 **  (10)  The subquery does not use aggregates or the outer query does not
   97162 **        use LIMIT.
   97163 **
   97164 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   97165 **
   97166 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   97167 **        a separate restriction deriving from ticket #350.
   97168 **
   97169 **  (13)  The subquery and outer query do not both use LIMIT.
   97170 **
   97171 **  (14)  The subquery does not use OFFSET.
   97172 **
   97173 **  (15)  The outer query is not part of a compound select or the
   97174 **        subquery does not have a LIMIT clause.
   97175 **        (See ticket #2339 and ticket [02a8e81d44]).
   97176 **
   97177 **  (16)  The outer query is not an aggregate or the subquery does
   97178 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   97179 **        until we introduced the group_concat() function.
   97180 **
   97181 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   97182 **        compound clause made up entirely of non-aggregate queries, and
   97183 **        the parent query:
   97184 **
   97185 **          * is not itself part of a compound select,
   97186 **          * is not an aggregate or DISTINCT query, and
   97187 **          * is not a join
   97188 **
   97189 **        The parent and sub-query may contain WHERE clauses. Subject to
   97190 **        rules (11), (13) and (14), they may also contain ORDER BY,
   97191 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
   97192 **        operator other than UNION ALL because all the other compound
   97193 **        operators have an implied DISTINCT which is disallowed by
   97194 **        restriction (4).
   97195 **
   97196 **  (18)  If the sub-query is a compound select, then all terms of the
   97197 **        ORDER by clause of the parent must be simple references to
   97198 **        columns of the sub-query.
   97199 **
   97200 **  (19)  The subquery does not use LIMIT or the outer query does not
   97201 **        have a WHERE clause.
   97202 **
   97203 **  (20)  If the sub-query is a compound select, then it must not use
   97204 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   97205 **        somewhat by saying that the terms of the ORDER BY clause must
   97206 **        appear as unmodified result columns in the outer query.  But we
   97207 **        have other optimizations in mind to deal with that case.
   97208 **
   97209 **  (21)  The subquery does not use LIMIT or the outer query is not
   97210 **        DISTINCT.  (See ticket [752e1646fc]).
   97211 **
   97212 ** In this routine, the "p" parameter is a pointer to the outer query.
   97213 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   97214 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   97215 **
   97216 ** If flattening is not attempted, this routine is a no-op and returns 0.
   97217 ** If flattening is attempted this routine returns 1.
   97218 **
   97219 ** All of the expression analysis must occur on both the outer query and
   97220 ** the subquery before this routine runs.
   97221 */
   97222 static int flattenSubquery(
   97223   Parse *pParse,       /* Parsing context */
   97224   Select *p,           /* The parent or outer SELECT statement */
   97225   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   97226   int isAgg,           /* True if outer SELECT uses aggregate functions */
   97227   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   97228 ){
   97229   const char *zSavedAuthContext = pParse->zAuthContext;
   97230   Select *pParent;
   97231   Select *pSub;       /* The inner query or "subquery" */
   97232   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   97233   SrcList *pSrc;      /* The FROM clause of the outer query */
   97234   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   97235   ExprList *pList;    /* The result set of the outer query */
   97236   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   97237   int i;              /* Loop counter */
   97238   Expr *pWhere;                    /* The WHERE clause */
   97239   struct SrcList_item *pSubitem;   /* The subquery */
   97240   sqlite3 *db = pParse->db;
   97241 
   97242   /* Check to see if flattening is permitted.  Return 0 if not.
   97243   */
   97244   assert( p!=0 );
   97245   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   97246   if( db->flags & SQLITE_QueryFlattener ) return 0;
   97247   pSrc = p->pSrc;
   97248   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   97249   pSubitem = &pSrc->a[iFrom];
   97250   iParent = pSubitem->iCursor;
   97251   pSub = pSubitem->pSelect;
   97252   assert( pSub!=0 );
   97253   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   97254   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   97255   pSubSrc = pSub->pSrc;
   97256   assert( pSubSrc );
   97257   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   97258   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   97259   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   97260   ** became arbitrary expressions, we were forced to add restrictions (13)
   97261   ** and (14). */
   97262   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   97263   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   97264   if( p->pRightmost && pSub->pLimit ){
   97265     return 0;                                            /* Restriction (15) */
   97266   }
   97267   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   97268   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
   97269   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   97270      return 0;         /* Restrictions (8)(9) */
   97271   }
   97272   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   97273      return 0;         /* Restriction (6)  */
   97274   }
   97275   if( p->pOrderBy && pSub->pOrderBy ){
   97276      return 0;                                           /* Restriction (11) */
   97277   }
   97278   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   97279   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   97280   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
   97281      return 0;         /* Restriction (21) */
   97282   }
   97283 
   97284   /* OBSOLETE COMMENT 1:
   97285   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   97286   ** not used as the right operand of an outer join.  Examples of why this
   97287   ** is not allowed:
   97288   **
   97289   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   97290   **
   97291   ** If we flatten the above, we would get
   97292   **
   97293   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   97294   **
   97295   ** which is not at all the same thing.
   97296   **
   97297   ** OBSOLETE COMMENT 2:
   97298   ** Restriction 12:  If the subquery is the right operand of a left outer
   97299   ** join, make sure the subquery has no WHERE clause.
   97300   ** An examples of why this is not allowed:
   97301   **
   97302   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   97303   **
   97304   ** If we flatten the above, we would get
   97305   **
   97306   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   97307   **
   97308   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   97309   ** effectively converts the OUTER JOIN into an INNER JOIN.
   97310   **
   97311   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   97312   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   97313   ** is fraught with danger.  Best to avoid the whole thing.  If the
   97314   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   97315   */
   97316   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   97317     return 0;
   97318   }
   97319 
   97320   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   97321   ** use only the UNION ALL operator. And none of the simple select queries
   97322   ** that make up the compound SELECT are allowed to be aggregate or distinct
   97323   ** queries.
   97324   */
   97325   if( pSub->pPrior ){
   97326     if( pSub->pOrderBy ){
   97327       return 0;  /* Restriction 20 */
   97328     }
   97329     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   97330       return 0;
   97331     }
   97332     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   97333       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   97334       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   97335       assert( pSub->pSrc!=0 );
   97336       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   97337        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   97338        || pSub1->pSrc->nSrc<1
   97339       ){
   97340         return 0;
   97341       }
   97342       testcase( pSub1->pSrc->nSrc>1 );
   97343     }
   97344 
   97345     /* Restriction 18. */
   97346     if( p->pOrderBy ){
   97347       int ii;
   97348       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   97349         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
   97350       }
   97351     }
   97352   }
   97353 
   97354   /***** If we reach this point, flattening is permitted. *****/
   97355 
   97356   /* Authorize the subquery */
   97357   pParse->zAuthContext = pSubitem->zName;
   97358   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   97359   pParse->zAuthContext = zSavedAuthContext;
   97360 
   97361   /* If the sub-query is a compound SELECT statement, then (by restrictions
   97362   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   97363   ** be of the form:
   97364   **
   97365   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   97366   **
   97367   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   97368   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   97369   ** OFFSET clauses and joins them to the left-hand-side of the original
   97370   ** using UNION ALL operators. In this case N is the number of simple
   97371   ** select statements in the compound sub-query.
   97372   **
   97373   ** Example:
   97374   **
   97375   **     SELECT a+1 FROM (
   97376   **        SELECT x FROM tab
   97377   **        UNION ALL
   97378   **        SELECT y FROM tab
   97379   **        UNION ALL
   97380   **        SELECT abs(z*2) FROM tab2
   97381   **     ) WHERE a!=5 ORDER BY 1
   97382   **
   97383   ** Transformed into:
   97384   **
   97385   **     SELECT x+1 FROM tab WHERE x+1!=5
   97386   **     UNION ALL
   97387   **     SELECT y+1 FROM tab WHERE y+1!=5
   97388   **     UNION ALL
   97389   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   97390   **     ORDER BY 1
   97391   **
   97392   ** We call this the "compound-subquery flattening".
   97393   */
   97394   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   97395     Select *pNew;
   97396     ExprList *pOrderBy = p->pOrderBy;
   97397     Expr *pLimit = p->pLimit;
   97398     Select *pPrior = p->pPrior;
   97399     p->pOrderBy = 0;
   97400     p->pSrc = 0;
   97401     p->pPrior = 0;
   97402     p->pLimit = 0;
   97403     pNew = sqlite3SelectDup(db, p, 0);
   97404     p->pLimit = pLimit;
   97405     p->pOrderBy = pOrderBy;
   97406     p->pSrc = pSrc;
   97407     p->op = TK_ALL;
   97408     p->pRightmost = 0;
   97409     if( pNew==0 ){
   97410       pNew = pPrior;
   97411     }else{
   97412       pNew->pPrior = pPrior;
   97413       pNew->pRightmost = 0;
   97414     }
   97415     p->pPrior = pNew;
   97416     if( db->mallocFailed ) return 1;
   97417   }
   97418 
   97419   /* Begin flattening the iFrom-th entry of the FROM clause
   97420   ** in the outer query.
   97421   */
   97422   pSub = pSub1 = pSubitem->pSelect;
   97423 
   97424   /* Delete the transient table structure associated with the
   97425   ** subquery
   97426   */
   97427   sqlite3DbFree(db, pSubitem->zDatabase);
   97428   sqlite3DbFree(db, pSubitem->zName);
   97429   sqlite3DbFree(db, pSubitem->zAlias);
   97430   pSubitem->zDatabase = 0;
   97431   pSubitem->zName = 0;
   97432   pSubitem->zAlias = 0;
   97433   pSubitem->pSelect = 0;
   97434 
   97435   /* Defer deleting the Table object associated with the
   97436   ** subquery until code generation is
   97437   ** complete, since there may still exist Expr.pTab entries that
   97438   ** refer to the subquery even after flattening.  Ticket #3346.
   97439   **
   97440   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   97441   */
   97442   if( ALWAYS(pSubitem->pTab!=0) ){
   97443     Table *pTabToDel = pSubitem->pTab;
   97444     if( pTabToDel->nRef==1 ){
   97445       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   97446       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   97447       pToplevel->pZombieTab = pTabToDel;
   97448     }else{
   97449       pTabToDel->nRef--;
   97450     }
   97451     pSubitem->pTab = 0;
   97452   }
   97453 
   97454   /* The following loop runs once for each term in a compound-subquery
   97455   ** flattening (as described above).  If we are doing a different kind
   97456   ** of flattening - a flattening other than a compound-subquery flattening -
   97457   ** then this loop only runs once.
   97458   **
   97459   ** This loop moves all of the FROM elements of the subquery into the
   97460   ** the FROM clause of the outer query.  Before doing this, remember
   97461   ** the cursor number for the original outer query FROM element in
   97462   ** iParent.  The iParent cursor will never be used.  Subsequent code
   97463   ** will scan expressions looking for iParent references and replace
   97464   ** those references with expressions that resolve to the subquery FROM
   97465   ** elements we are now copying in.
   97466   */
   97467   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   97468     int nSubSrc;
   97469     u8 jointype = 0;
   97470     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   97471     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   97472     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   97473 
   97474     if( pSrc ){
   97475       assert( pParent==p );  /* First time through the loop */
   97476       jointype = pSubitem->jointype;
   97477     }else{
   97478       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   97479       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   97480       if( pSrc==0 ){
   97481         assert( db->mallocFailed );
   97482         break;
   97483       }
   97484     }
   97485 
   97486     /* The subquery uses a single slot of the FROM clause of the outer
   97487     ** query.  If the subquery has more than one element in its FROM clause,
   97488     ** then expand the outer query to make space for it to hold all elements
   97489     ** of the subquery.
   97490     **
   97491     ** Example:
   97492     **
   97493     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   97494     **
   97495     ** The outer query has 3 slots in its FROM clause.  One slot of the
   97496     ** outer query (the middle slot) is used by the subquery.  The next
   97497     ** block of code will expand the out query to 4 slots.  The middle
   97498     ** slot is expanded to two slots in order to make space for the
   97499     ** two elements in the FROM clause of the subquery.
   97500     */
   97501     if( nSubSrc>1 ){
   97502       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   97503       if( db->mallocFailed ){
   97504         break;
   97505       }
   97506     }
   97507 
   97508     /* Transfer the FROM clause terms from the subquery into the
   97509     ** outer query.
   97510     */
   97511     for(i=0; i<nSubSrc; i++){
   97512       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   97513       pSrc->a[i+iFrom] = pSubSrc->a[i];
   97514       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   97515     }
   97516     pSrc->a[iFrom].jointype = jointype;
   97517 
   97518     /* Now begin substituting subquery result set expressions for
   97519     ** references to the iParent in the outer query.
   97520     **
   97521     ** Example:
   97522     **
   97523     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   97524     **   \                     \_____________ subquery __________/          /
   97525     **    \_____________________ outer query ______________________________/
   97526     **
   97527     ** We look at every expression in the outer query and every place we see
   97528     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   97529     */
   97530     pList = pParent->pEList;
   97531     for(i=0; i<pList->nExpr; i++){
   97532       if( pList->a[i].zName==0 ){
   97533         const char *zSpan = pList->a[i].zSpan;
   97534         if( ALWAYS(zSpan) ){
   97535           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
   97536         }
   97537       }
   97538     }
   97539     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   97540     if( isAgg ){
   97541       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   97542       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   97543     }
   97544     if( pSub->pOrderBy ){
   97545       assert( pParent->pOrderBy==0 );
   97546       pParent->pOrderBy = pSub->pOrderBy;
   97547       pSub->pOrderBy = 0;
   97548     }else if( pParent->pOrderBy ){
   97549       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   97550     }
   97551     if( pSub->pWhere ){
   97552       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   97553     }else{
   97554       pWhere = 0;
   97555     }
   97556     if( subqueryIsAgg ){
   97557       assert( pParent->pHaving==0 );
   97558       pParent->pHaving = pParent->pWhere;
   97559       pParent->pWhere = pWhere;
   97560       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   97561       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   97562                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   97563       assert( pParent->pGroupBy==0 );
   97564       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   97565     }else{
   97566       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   97567       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   97568     }
   97569 
   97570     /* The flattened query is distinct if either the inner or the
   97571     ** outer query is distinct.
   97572     */
   97573     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   97574 
   97575     /*
   97576     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   97577     **
   97578     ** One is tempted to try to add a and b to combine the limits.  But this
   97579     ** does not work if either limit is negative.
   97580     */
   97581     if( pSub->pLimit ){
   97582       pParent->pLimit = pSub->pLimit;
   97583       pSub->pLimit = 0;
   97584     }
   97585   }
   97586 
   97587   /* Finially, delete what is left of the subquery and return
   97588   ** success.
   97589   */
   97590   sqlite3SelectDelete(db, pSub1);
   97591 
   97592   return 1;
   97593 }
   97594 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   97595 
   97596 /*
   97597 ** Analyze the SELECT statement passed as an argument to see if it
   97598 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
   97599 ** it is, or 0 otherwise. At present, a query is considered to be
   97600 ** a min()/max() query if:
   97601 **
   97602 **   1. There is a single object in the FROM clause.
   97603 **
   97604 **   2. There is a single expression in the result set, and it is
   97605 **      either min(x) or max(x), where x is a column reference.
   97606 */
   97607 static u8 minMaxQuery(Select *p){
   97608   Expr *pExpr;
   97609   ExprList *pEList = p->pEList;
   97610 
   97611   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
   97612   pExpr = pEList->a[0].pExpr;
   97613   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   97614   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
   97615   pEList = pExpr->x.pList;
   97616   if( pEList==0 || pEList->nExpr!=1 ) return 0;
   97617   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
   97618   assert( !ExprHasProperty(pExpr, EP_IntValue) );
   97619   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
   97620     return WHERE_ORDERBY_MIN;
   97621   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
   97622     return WHERE_ORDERBY_MAX;
   97623   }
   97624   return WHERE_ORDERBY_NORMAL;
   97625 }
   97626 
   97627 /*
   97628 ** The select statement passed as the first argument is an aggregate query.
   97629 ** The second argment is the associated aggregate-info object. This
   97630 ** function tests if the SELECT is of the form:
   97631 **
   97632 **   SELECT count(*) FROM <tbl>
   97633 **
   97634 ** where table is a database table, not a sub-select or view. If the query
   97635 ** does match this pattern, then a pointer to the Table object representing
   97636 ** <tbl> is returned. Otherwise, 0 is returned.
   97637 */
   97638 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   97639   Table *pTab;
   97640   Expr *pExpr;
   97641 
   97642   assert( !p->pGroupBy );
   97643 
   97644   if( p->pWhere || p->pEList->nExpr!=1
   97645    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   97646   ){
   97647     return 0;
   97648   }
   97649   pTab = p->pSrc->a[0].pTab;
   97650   pExpr = p->pEList->a[0].pExpr;
   97651   assert( pTab && !pTab->pSelect && pExpr );
   97652 
   97653   if( IsVirtual(pTab) ) return 0;
   97654   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   97655   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
   97656   if( pExpr->flags&EP_Distinct ) return 0;
   97657 
   97658   return pTab;
   97659 }
   97660 
   97661 /*
   97662 ** If the source-list item passed as an argument was augmented with an
   97663 ** INDEXED BY clause, then try to locate the specified index. If there
   97664 ** was such a clause and the named index cannot be found, return
   97665 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   97666 ** pFrom->pIndex and return SQLITE_OK.
   97667 */
   97668 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   97669   if( pFrom->pTab && pFrom->zIndex ){
   97670     Table *pTab = pFrom->pTab;
   97671     char *zIndex = pFrom->zIndex;
   97672     Index *pIdx;
   97673     for(pIdx=pTab->pIndex;
   97674         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   97675         pIdx=pIdx->pNext
   97676     );
   97677     if( !pIdx ){
   97678       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   97679       pParse->checkSchema = 1;
   97680       return SQLITE_ERROR;
   97681     }
   97682     pFrom->pIndex = pIdx;
   97683   }
   97684   return SQLITE_OK;
   97685 }
   97686 
   97687 /*
   97688 ** This routine is a Walker callback for "expanding" a SELECT statement.
   97689 ** "Expanding" means to do the following:
   97690 **
   97691 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   97692 **         element of the FROM clause.
   97693 **
   97694 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   97695 **         defines FROM clause.  When views appear in the FROM clause,
   97696 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   97697 **         that implements the view.  A copy is made of the view's SELECT
   97698 **         statement so that we can freely modify or delete that statement
   97699 **         without worrying about messing up the presistent representation
   97700 **         of the view.
   97701 **
   97702 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   97703 **         on joins and the ON and USING clause of joins.
   97704 **
   97705 **    (4)  Scan the list of columns in the result set (pEList) looking
   97706 **         for instances of the "*" operator or the TABLE.* operator.
   97707 **         If found, expand each "*" to be every column in every table
   97708 **         and TABLE.* to be every column in TABLE.
   97709 **
   97710 */
   97711 static int selectExpander(Walker *pWalker, Select *p){
   97712   Parse *pParse = pWalker->pParse;
   97713   int i, j, k;
   97714   SrcList *pTabList;
   97715   ExprList *pEList;
   97716   struct SrcList_item *pFrom;
   97717   sqlite3 *db = pParse->db;
   97718 
   97719   if( db->mallocFailed  ){
   97720     return WRC_Abort;
   97721   }
   97722   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
   97723     return WRC_Prune;
   97724   }
   97725   p->selFlags |= SF_Expanded;
   97726   pTabList = p->pSrc;
   97727   pEList = p->pEList;
   97728 
   97729   /* Make sure cursor numbers have been assigned to all entries in
   97730   ** the FROM clause of the SELECT statement.
   97731   */
   97732   sqlite3SrcListAssignCursors(pParse, pTabList);
   97733 
   97734   /* Look up every table named in the FROM clause of the select.  If
   97735   ** an entry of the FROM clause is a subquery instead of a table or view,
   97736   ** then create a transient table structure to describe the subquery.
   97737   */
   97738   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   97739     Table *pTab;
   97740     if( pFrom->pTab!=0 ){
   97741       /* This statement has already been prepared.  There is no need
   97742       ** to go further. */
   97743       assert( i==0 );
   97744       return WRC_Prune;
   97745     }
   97746     if( pFrom->zName==0 ){
   97747 #ifndef SQLITE_OMIT_SUBQUERY
   97748       Select *pSel = pFrom->pSelect;
   97749       /* A sub-query in the FROM clause of a SELECT */
   97750       assert( pSel!=0 );
   97751       assert( pFrom->pTab==0 );
   97752       sqlite3WalkSelect(pWalker, pSel);
   97753       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   97754       if( pTab==0 ) return WRC_Abort;
   97755       pTab->nRef = 1;
   97756       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
   97757       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   97758       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   97759       pTab->iPKey = -1;
   97760       pTab->nRowEst = 1000000;
   97761       pTab->tabFlags |= TF_Ephemeral;
   97762 #endif
   97763     }else{
   97764       /* An ordinary table or view name in the FROM clause */
   97765       assert( pFrom->pTab==0 );
   97766       pFrom->pTab = pTab =
   97767         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
   97768       if( pTab==0 ) return WRC_Abort;
   97769       pTab->nRef++;
   97770 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   97771       if( pTab->pSelect || IsVirtual(pTab) ){
   97772         /* We reach here if the named table is a really a view */
   97773         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   97774         assert( pFrom->pSelect==0 );
   97775         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   97776         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   97777       }
   97778 #endif
   97779     }
   97780 
   97781     /* Locate the index named by the INDEXED BY clause, if any. */
   97782     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   97783       return WRC_Abort;
   97784     }
   97785   }
   97786 
   97787   /* Process NATURAL keywords, and ON and USING clauses of joins.
   97788   */
   97789   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   97790     return WRC_Abort;
   97791   }
   97792 
   97793   /* For every "*" that occurs in the column list, insert the names of
   97794   ** all columns in all tables.  And for every TABLE.* insert the names
   97795   ** of all columns in TABLE.  The parser inserted a special expression
   97796   ** with the TK_ALL operator for each "*" that it found in the column list.
   97797   ** The following code just has to locate the TK_ALL expressions and expand
   97798   ** each one to the list of all columns in all tables.
   97799   **
   97800   ** The first loop just checks to see if there are any "*" operators
   97801   ** that need expanding.
   97802   */
   97803   for(k=0; k<pEList->nExpr; k++){
   97804     Expr *pE = pEList->a[k].pExpr;
   97805     if( pE->op==TK_ALL ) break;
   97806     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   97807     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   97808     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   97809   }
   97810   if( k<pEList->nExpr ){
   97811     /*
   97812     ** If we get here it means the result set contains one or more "*"
   97813     ** operators that need to be expanded.  Loop through each expression
   97814     ** in the result set and expand them one by one.
   97815     */
   97816     struct ExprList_item *a = pEList->a;
   97817     ExprList *pNew = 0;
   97818     int flags = pParse->db->flags;
   97819     int longNames = (flags & SQLITE_FullColNames)!=0
   97820                       && (flags & SQLITE_ShortColNames)==0;
   97821 
   97822     for(k=0; k<pEList->nExpr; k++){
   97823       Expr *pE = a[k].pExpr;
   97824       assert( pE->op!=TK_DOT || pE->pRight!=0 );
   97825       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
   97826         /* This particular expression does not need to be expanded.
   97827         */
   97828         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   97829         if( pNew ){
   97830           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   97831           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   97832           a[k].zName = 0;
   97833           a[k].zSpan = 0;
   97834         }
   97835         a[k].pExpr = 0;
   97836       }else{
   97837         /* This expression is a "*" or a "TABLE.*" and needs to be
   97838         ** expanded. */
   97839         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   97840         char *zTName;            /* text of name of TABLE */
   97841         if( pE->op==TK_DOT ){
   97842           assert( pE->pLeft!=0 );
   97843           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   97844           zTName = pE->pLeft->u.zToken;
   97845         }else{
   97846           zTName = 0;
   97847         }
   97848         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   97849           Table *pTab = pFrom->pTab;
   97850           char *zTabName = pFrom->zAlias;
   97851           if( zTabName==0 ){
   97852             zTabName = pTab->zName;
   97853           }
   97854           if( db->mallocFailed ) break;
   97855           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   97856             continue;
   97857           }
   97858           tableSeen = 1;
   97859           for(j=0; j<pTab->nCol; j++){
   97860             Expr *pExpr, *pRight;
   97861             char *zName = pTab->aCol[j].zName;
   97862             char *zColname;  /* The computed column name */
   97863             char *zToFree;   /* Malloced string that needs to be freed */
   97864             Token sColname;  /* Computed column name as a token */
   97865 
   97866             /* If a column is marked as 'hidden' (currently only possible
   97867             ** for virtual tables), do not include it in the expanded
   97868             ** result-set list.
   97869             */
   97870             if( IsHiddenColumn(&pTab->aCol[j]) ){
   97871               assert(IsVirtual(pTab));
   97872               continue;
   97873             }
   97874 
   97875             if( i>0 && zTName==0 ){
   97876               if( (pFrom->jointype & JT_NATURAL)!=0
   97877                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   97878               ){
   97879                 /* In a NATURAL join, omit the join columns from the
   97880                 ** table to the right of the join */
   97881                 continue;
   97882               }
   97883               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   97884                 /* In a join with a USING clause, omit columns in the
   97885                 ** using clause from the table on the right. */
   97886                 continue;
   97887               }
   97888             }
   97889             pRight = sqlite3Expr(db, TK_ID, zName);
   97890             zColname = zName;
   97891             zToFree = 0;
   97892             if( longNames || pTabList->nSrc>1 ){
   97893               Expr *pLeft;
   97894               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   97895               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   97896               if( longNames ){
   97897                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   97898                 zToFree = zColname;
   97899               }
   97900             }else{
   97901               pExpr = pRight;
   97902             }
   97903             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   97904             sColname.z = zColname;
   97905             sColname.n = sqlite3Strlen30(zColname);
   97906             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   97907             sqlite3DbFree(db, zToFree);
   97908           }
   97909         }
   97910         if( !tableSeen ){
   97911           if( zTName ){
   97912             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   97913           }else{
   97914             sqlite3ErrorMsg(pParse, "no tables specified");
   97915           }
   97916         }
   97917       }
   97918     }
   97919     sqlite3ExprListDelete(db, pEList);
   97920     p->pEList = pNew;
   97921   }
   97922 #if SQLITE_MAX_COLUMN
   97923   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   97924     sqlite3ErrorMsg(pParse, "too many columns in result set");
   97925   }
   97926 #endif
   97927   return WRC_Continue;
   97928 }
   97929 
   97930 /*
   97931 ** No-op routine for the parse-tree walker.
   97932 **
   97933 ** When this routine is the Walker.xExprCallback then expression trees
   97934 ** are walked without any actions being taken at each node.  Presumably,
   97935 ** when this routine is used for Walker.xExprCallback then
   97936 ** Walker.xSelectCallback is set to do something useful for every
   97937 ** subquery in the parser tree.
   97938 */
   97939 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   97940   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   97941   return WRC_Continue;
   97942 }
   97943 
   97944 /*
   97945 ** This routine "expands" a SELECT statement and all of its subqueries.
   97946 ** For additional information on what it means to "expand" a SELECT
   97947 ** statement, see the comment on the selectExpand worker callback above.
   97948 **
   97949 ** Expanding a SELECT statement is the first step in processing a
   97950 ** SELECT statement.  The SELECT statement must be expanded before
   97951 ** name resolution is performed.
   97952 **
   97953 ** If anything goes wrong, an error message is written into pParse.
   97954 ** The calling function can detect the problem by looking at pParse->nErr
   97955 ** and/or pParse->db->mallocFailed.
   97956 */
   97957 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   97958   Walker w;
   97959   w.xSelectCallback = selectExpander;
   97960   w.xExprCallback = exprWalkNoop;
   97961   w.pParse = pParse;
   97962   sqlite3WalkSelect(&w, pSelect);
   97963 }
   97964 
   97965 
   97966 #ifndef SQLITE_OMIT_SUBQUERY
   97967 /*
   97968 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   97969 ** interface.
   97970 **
   97971 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   97972 ** information to the Table structure that represents the result set
   97973 ** of that subquery.
   97974 **
   97975 ** The Table structure that represents the result set was constructed
   97976 ** by selectExpander() but the type and collation information was omitted
   97977 ** at that point because identifiers had not yet been resolved.  This
   97978 ** routine is called after identifier resolution.
   97979 */
   97980 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   97981   Parse *pParse;
   97982   int i;
   97983   SrcList *pTabList;
   97984   struct SrcList_item *pFrom;
   97985 
   97986   assert( p->selFlags & SF_Resolved );
   97987   if( (p->selFlags & SF_HasTypeInfo)==0 ){
   97988     p->selFlags |= SF_HasTypeInfo;
   97989     pParse = pWalker->pParse;
   97990     pTabList = p->pSrc;
   97991     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   97992       Table *pTab = pFrom->pTab;
   97993       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   97994         /* A sub-query in the FROM clause of a SELECT */
   97995         Select *pSel = pFrom->pSelect;
   97996         assert( pSel );
   97997         while( pSel->pPrior ) pSel = pSel->pPrior;
   97998         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
   97999       }
   98000     }
   98001   }
   98002   return WRC_Continue;
   98003 }
   98004 #endif
   98005 
   98006 
   98007 /*
   98008 ** This routine adds datatype and collating sequence information to
   98009 ** the Table structures of all FROM-clause subqueries in a
   98010 ** SELECT statement.
   98011 **
   98012 ** Use this routine after name resolution.
   98013 */
   98014 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   98015 #ifndef SQLITE_OMIT_SUBQUERY
   98016   Walker w;
   98017   w.xSelectCallback = selectAddSubqueryTypeInfo;
   98018   w.xExprCallback = exprWalkNoop;
   98019   w.pParse = pParse;
   98020   sqlite3WalkSelect(&w, pSelect);
   98021 #endif
   98022 }
   98023 
   98024 
   98025 /*
   98026 ** This routine sets of a SELECT statement for processing.  The
   98027 ** following is accomplished:
   98028 **
   98029 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   98030 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   98031 **     *  ON and USING clauses are shifted into WHERE statements
   98032 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   98033 **     *  Identifiers in expression are matched to tables.
   98034 **
   98035 ** This routine acts recursively on all subqueries within the SELECT.
   98036 */
   98037 SQLITE_PRIVATE void sqlite3SelectPrep(
   98038   Parse *pParse,         /* The parser context */
   98039   Select *p,             /* The SELECT statement being coded. */
   98040   NameContext *pOuterNC  /* Name context for container */
   98041 ){
   98042   sqlite3 *db;
   98043   if( NEVER(p==0) ) return;
   98044   db = pParse->db;
   98045   if( p->selFlags & SF_HasTypeInfo ) return;
   98046   sqlite3SelectExpand(pParse, p);
   98047   if( pParse->nErr || db->mallocFailed ) return;
   98048   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   98049   if( pParse->nErr || db->mallocFailed ) return;
   98050   sqlite3SelectAddTypeInfo(pParse, p);
   98051 }
   98052 
   98053 /*
   98054 ** Reset the aggregate accumulator.
   98055 **
   98056 ** The aggregate accumulator is a set of memory cells that hold
   98057 ** intermediate results while calculating an aggregate.  This
   98058 ** routine simply stores NULLs in all of those memory cells.
   98059 */
   98060 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   98061   Vdbe *v = pParse->pVdbe;
   98062   int i;
   98063   struct AggInfo_func *pFunc;
   98064   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
   98065     return;
   98066   }
   98067   for(i=0; i<pAggInfo->nColumn; i++){
   98068     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
   98069   }
   98070   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   98071     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
   98072     if( pFunc->iDistinct>=0 ){
   98073       Expr *pE = pFunc->pExpr;
   98074       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   98075       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   98076         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   98077            "argument");
   98078         pFunc->iDistinct = -1;
   98079       }else{
   98080         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
   98081         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   98082                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98083       }
   98084     }
   98085   }
   98086 }
   98087 
   98088 /*
   98089 ** Invoke the OP_AggFinalize opcode for every aggregate function
   98090 ** in the AggInfo structure.
   98091 */
   98092 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   98093   Vdbe *v = pParse->pVdbe;
   98094   int i;
   98095   struct AggInfo_func *pF;
   98096   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   98097     ExprList *pList = pF->pExpr->x.pList;
   98098     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   98099     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   98100                       (void*)pF->pFunc, P4_FUNCDEF);
   98101   }
   98102 }
   98103 
   98104 /*
   98105 ** Update the accumulator memory cells for an aggregate based on
   98106 ** the current cursor position.
   98107 */
   98108 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   98109   Vdbe *v = pParse->pVdbe;
   98110   int i;
   98111   int regHit = 0;
   98112   int addrHitTest = 0;
   98113   struct AggInfo_func *pF;
   98114   struct AggInfo_col *pC;
   98115 
   98116   pAggInfo->directMode = 1;
   98117   sqlite3ExprCacheClear(pParse);
   98118   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   98119     int nArg;
   98120     int addrNext = 0;
   98121     int regAgg;
   98122     ExprList *pList = pF->pExpr->x.pList;
   98123     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   98124     if( pList ){
   98125       nArg = pList->nExpr;
   98126       regAgg = sqlite3GetTempRange(pParse, nArg);
   98127       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
   98128     }else{
   98129       nArg = 0;
   98130       regAgg = 0;
   98131     }
   98132     if( pF->iDistinct>=0 ){
   98133       addrNext = sqlite3VdbeMakeLabel(v);
   98134       assert( nArg==1 );
   98135       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   98136     }
   98137     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   98138       CollSeq *pColl = 0;
   98139       struct ExprList_item *pItem;
   98140       int j;
   98141       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   98142       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   98143         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   98144       }
   98145       if( !pColl ){
   98146         pColl = pParse->db->pDfltColl;
   98147       }
   98148       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
   98149       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
   98150     }
   98151     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   98152                       (void*)pF->pFunc, P4_FUNCDEF);
   98153     sqlite3VdbeChangeP5(v, (u8)nArg);
   98154     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   98155     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   98156     if( addrNext ){
   98157       sqlite3VdbeResolveLabel(v, addrNext);
   98158       sqlite3ExprCacheClear(pParse);
   98159     }
   98160   }
   98161 
   98162   /* Before populating the accumulator registers, clear the column cache.
   98163   ** Otherwise, if any of the required column values are already present
   98164   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   98165   ** to pC->iMem. But by the time the value is used, the original register
   98166   ** may have been used, invalidating the underlying buffer holding the
   98167   ** text or blob value. See ticket [883034dcb5].
   98168   **
   98169   ** Another solution would be to change the OP_SCopy used to copy cached
   98170   ** values to an OP_Copy.
   98171   */
   98172   if( regHit ){
   98173     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
   98174   }
   98175   sqlite3ExprCacheClear(pParse);
   98176   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   98177     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   98178   }
   98179   pAggInfo->directMode = 0;
   98180   sqlite3ExprCacheClear(pParse);
   98181   if( addrHitTest ){
   98182     sqlite3VdbeJumpHere(v, addrHitTest);
   98183   }
   98184 }
   98185 
   98186 /*
   98187 ** Add a single OP_Explain instruction to the VDBE to explain a simple
   98188 ** count(*) query ("SELECT count(*) FROM pTab").
   98189 */
   98190 #ifndef SQLITE_OMIT_EXPLAIN
   98191 static void explainSimpleCount(
   98192   Parse *pParse,                  /* Parse context */
   98193   Table *pTab,                    /* Table being queried */
   98194   Index *pIdx                     /* Index used to optimize scan, or NULL */
   98195 ){
   98196   if( pParse->explain==2 ){
   98197     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
   98198         pTab->zName,
   98199         pIdx ? "USING COVERING INDEX " : "",
   98200         pIdx ? pIdx->zName : "",
   98201         pTab->nRowEst
   98202     );
   98203     sqlite3VdbeAddOp4(
   98204         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
   98205     );
   98206   }
   98207 }
   98208 #else
   98209 # define explainSimpleCount(a,b,c)
   98210 #endif
   98211 
   98212 /*
   98213 ** Generate code for the SELECT statement given in the p argument.
   98214 **
   98215 ** The results are distributed in various ways depending on the
   98216 ** contents of the SelectDest structure pointed to by argument pDest
   98217 ** as follows:
   98218 **
   98219 **     pDest->eDest    Result
   98220 **     ------------    -------------------------------------------
   98221 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   98222 **                     opcode) for each row in the result set.
   98223 **
   98224 **     SRT_Mem         Only valid if the result is a single column.
   98225 **                     Store the first column of the first result row
   98226 **                     in register pDest->iParm then abandon the rest
   98227 **                     of the query.  This destination implies "LIMIT 1".
   98228 **
   98229 **     SRT_Set         The result must be a single column.  Store each
   98230 **                     row of result as the key in table pDest->iParm.
   98231 **                     Apply the affinity pDest->affinity before storing
   98232 **                     results.  Used to implement "IN (SELECT ...)".
   98233 **
   98234 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
   98235 **
   98236 **     SRT_Except      Remove results from the temporary table pDest->iParm.
   98237 **
   98238 **     SRT_Table       Store results in temporary table pDest->iParm.
   98239 **                     This is like SRT_EphemTab except that the table
   98240 **                     is assumed to already be open.
   98241 **
   98242 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
   98243 **                     the result there. The cursor is left open after
   98244 **                     returning.  This is like SRT_Table except that
   98245 **                     this destination uses OP_OpenEphemeral to create
   98246 **                     the table first.
   98247 **
   98248 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   98249 **                     results each time it is invoked.  The entry point
   98250 **                     of the co-routine is stored in register pDest->iParm.
   98251 **
   98252 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
   98253 **                     set is not empty.
   98254 **
   98255 **     SRT_Discard     Throw the results away.  This is used by SELECT
   98256 **                     statements within triggers whose only purpose is
   98257 **                     the side-effects of functions.
   98258 **
   98259 ** This routine returns the number of errors.  If any errors are
   98260 ** encountered, then an appropriate error message is left in
   98261 ** pParse->zErrMsg.
   98262 **
   98263 ** This routine does NOT free the Select structure passed in.  The
   98264 ** calling function needs to do that.
   98265 */
   98266 SQLITE_PRIVATE int sqlite3Select(
   98267   Parse *pParse,         /* The parser context */
   98268   Select *p,             /* The SELECT statement being coded. */
   98269   SelectDest *pDest      /* What to do with the query results */
   98270 ){
   98271   int i, j;              /* Loop counters */
   98272   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   98273   Vdbe *v;               /* The virtual machine under construction */
   98274   int isAgg;             /* True for select lists like "count(*)" */
   98275   ExprList *pEList;      /* List of columns to extract. */
   98276   SrcList *pTabList;     /* List of tables to select from */
   98277   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   98278   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
   98279   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   98280   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   98281   int isDistinct;        /* True if the DISTINCT keyword is present */
   98282   int distinct;          /* Table to use for the distinct set */
   98283   int rc = 1;            /* Value to return from this function */
   98284   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
   98285   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
   98286   AggInfo sAggInfo;      /* Information used by aggregate queries */
   98287   int iEnd;              /* Address of the end of the query */
   98288   sqlite3 *db;           /* The database connection */
   98289 
   98290 #ifndef SQLITE_OMIT_EXPLAIN
   98291   int iRestoreSelectId = pParse->iSelectId;
   98292   pParse->iSelectId = pParse->iNextSelectId++;
   98293 #endif
   98294 
   98295   db = pParse->db;
   98296   if( p==0 || db->mallocFailed || pParse->nErr ){
   98297     return 1;
   98298   }
   98299   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   98300   memset(&sAggInfo, 0, sizeof(sAggInfo));
   98301 
   98302   if( IgnorableOrderby(pDest) ){
   98303     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   98304            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
   98305     /* If ORDER BY makes no difference in the output then neither does
   98306     ** DISTINCT so it can be removed too. */
   98307     sqlite3ExprListDelete(db, p->pOrderBy);
   98308     p->pOrderBy = 0;
   98309     p->selFlags &= ~SF_Distinct;
   98310   }
   98311   sqlite3SelectPrep(pParse, p, 0);
   98312   pOrderBy = p->pOrderBy;
   98313   pTabList = p->pSrc;
   98314   pEList = p->pEList;
   98315   if( pParse->nErr || db->mallocFailed ){
   98316     goto select_end;
   98317   }
   98318   isAgg = (p->selFlags & SF_Aggregate)!=0;
   98319   assert( pEList!=0 );
   98320 
   98321   /* Begin generating code.
   98322   */
   98323   v = sqlite3GetVdbe(pParse);
   98324   if( v==0 ) goto select_end;
   98325 
   98326   /* If writing to memory or generating a set
   98327   ** only a single column may be output.
   98328   */
   98329 #ifndef SQLITE_OMIT_SUBQUERY
   98330   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   98331     goto select_end;
   98332   }
   98333 #endif
   98334 
   98335   /* Generate code for all sub-queries in the FROM clause
   98336   */
   98337 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   98338   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   98339     struct SrcList_item *pItem = &pTabList->a[i];
   98340     SelectDest dest;
   98341     Select *pSub = pItem->pSelect;
   98342     int isAggSub;
   98343 
   98344     if( pSub==0 ) continue;
   98345     if( pItem->addrFillSub ){
   98346       sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
   98347       continue;
   98348     }
   98349 
   98350     /* Increment Parse.nHeight by the height of the largest expression
   98351     ** tree refered to by this, the parent select. The child select
   98352     ** may contain expression trees of at most
   98353     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   98354     ** more conservative than necessary, but much easier than enforcing
   98355     ** an exact limit.
   98356     */
   98357     pParse->nHeight += sqlite3SelectExprHeight(p);
   98358 
   98359     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   98360     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   98361       /* This subquery can be absorbed into its parent. */
   98362       if( isAggSub ){
   98363         isAgg = 1;
   98364         p->selFlags |= SF_Aggregate;
   98365       }
   98366       i = -1;
   98367     }else{
   98368       /* Generate a subroutine that will fill an ephemeral table with
   98369       ** the content of this subquery.  pItem->addrFillSub will point
   98370       ** to the address of the generated subroutine.  pItem->regReturn
   98371       ** is a register allocated to hold the subroutine return address
   98372       */
   98373       int topAddr;
   98374       int onceAddr = 0;
   98375       int retAddr;
   98376       assert( pItem->addrFillSub==0 );
   98377       pItem->regReturn = ++pParse->nMem;
   98378       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
   98379       pItem->addrFillSub = topAddr+1;
   98380       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
   98381       if( pItem->isCorrelated==0 ){
   98382         /* If the subquery is no correlated and if we are not inside of
   98383         ** a trigger, then we only need to compute the value of the subquery
   98384         ** once. */
   98385         onceAddr = sqlite3CodeOnce(pParse);
   98386       }
   98387       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   98388       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   98389       sqlite3Select(pParse, pSub, &dest);
   98390       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
   98391       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
   98392       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
   98393       VdbeComment((v, "end %s", pItem->pTab->zName));
   98394       sqlite3VdbeChangeP1(v, topAddr, retAddr);
   98395       sqlite3ClearTempRegCache(pParse);
   98396     }
   98397     if( /*pParse->nErr ||*/ db->mallocFailed ){
   98398       goto select_end;
   98399     }
   98400     pParse->nHeight -= sqlite3SelectExprHeight(p);
   98401     pTabList = p->pSrc;
   98402     if( !IgnorableOrderby(pDest) ){
   98403       pOrderBy = p->pOrderBy;
   98404     }
   98405   }
   98406   pEList = p->pEList;
   98407 #endif
   98408   pWhere = p->pWhere;
   98409   pGroupBy = p->pGroupBy;
   98410   pHaving = p->pHaving;
   98411   isDistinct = (p->selFlags & SF_Distinct)!=0;
   98412 
   98413 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   98414   /* If there is are a sequence of queries, do the earlier ones first.
   98415   */
   98416   if( p->pPrior ){
   98417     if( p->pRightmost==0 ){
   98418       Select *pLoop, *pRight = 0;
   98419       int cnt = 0;
   98420       int mxSelect;
   98421       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
   98422         pLoop->pRightmost = p;
   98423         pLoop->pNext = pRight;
   98424         pRight = pLoop;
   98425       }
   98426       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   98427       if( mxSelect && cnt>mxSelect ){
   98428         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   98429         goto select_end;
   98430       }
   98431     }
   98432     rc = multiSelect(pParse, p, pDest);
   98433     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   98434     return rc;
   98435   }
   98436 #endif
   98437 
   98438   /* If there is both a GROUP BY and an ORDER BY clause and they are
   98439   ** identical, then disable the ORDER BY clause since the GROUP BY
   98440   ** will cause elements to come out in the correct order.  This is
   98441   ** an optimization - the correct answer should result regardless.
   98442   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
   98443   ** to disable this optimization for testing purposes.
   98444   */
   98445   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
   98446          && (db->flags & SQLITE_GroupByOrder)==0 ){
   98447     pOrderBy = 0;
   98448   }
   98449 
   98450   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   98451   ** if the select-list is the same as the ORDER BY list, then this query
   98452   ** can be rewritten as a GROUP BY. In other words, this:
   98453   **
   98454   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
   98455   **
   98456   ** is transformed to:
   98457   **
   98458   **     SELECT xyz FROM ... GROUP BY xyz
   98459   **
   98460   ** The second form is preferred as a single index (or temp-table) may be
   98461   ** used for both the ORDER BY and DISTINCT processing. As originally
   98462   ** written the query must use a temp-table for at least one of the ORDER
   98463   ** BY and DISTINCT, and an index or separate temp-table for the other.
   98464   */
   98465   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
   98466    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
   98467   ){
   98468     p->selFlags &= ~SF_Distinct;
   98469     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   98470     pGroupBy = p->pGroupBy;
   98471     pOrderBy = 0;
   98472   }
   98473 
   98474   /* If there is an ORDER BY clause, then this sorting
   98475   ** index might end up being unused if the data can be
   98476   ** extracted in pre-sorted order.  If that is the case, then the
   98477   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   98478   ** we figure out that the sorting index is not needed.  The addrSortIndex
   98479   ** variable is used to facilitate that change.
   98480   */
   98481   if( pOrderBy ){
   98482     KeyInfo *pKeyInfo;
   98483     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
   98484     pOrderBy->iECursor = pParse->nTab++;
   98485     p->addrOpenEphm[2] = addrSortIndex =
   98486       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   98487                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
   98488                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98489   }else{
   98490     addrSortIndex = -1;
   98491   }
   98492 
   98493   /* If the output is destined for a temporary table, open that table.
   98494   */
   98495   if( pDest->eDest==SRT_EphemTab ){
   98496     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
   98497   }
   98498 
   98499   /* Set the limiter.
   98500   */
   98501   iEnd = sqlite3VdbeMakeLabel(v);
   98502   p->nSelectRow = (double)LARGEST_INT64;
   98503   computeLimitRegisters(pParse, p, iEnd);
   98504   if( p->iLimit==0 && addrSortIndex>=0 ){
   98505     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
   98506     p->selFlags |= SF_UseSorter;
   98507   }
   98508 
   98509   /* Open a virtual index to use for the distinct set.
   98510   */
   98511   if( p->selFlags & SF_Distinct ){
   98512     KeyInfo *pKeyInfo;
   98513     distinct = pParse->nTab++;
   98514     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
   98515     addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
   98516         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98517     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   98518   }else{
   98519     distinct = addrDistinctIndex = -1;
   98520   }
   98521 
   98522   /* Aggregate and non-aggregate queries are handled differently */
   98523   if( !isAgg && pGroupBy==0 ){
   98524     ExprList *pDist = (isDistinct ? p->pEList : 0);
   98525 
   98526     /* Begin the database scan. */
   98527     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
   98528     if( pWInfo==0 ) goto select_end;
   98529     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
   98530 
   98531     /* If sorting index that was created by a prior OP_OpenEphemeral
   98532     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   98533     ** into an OP_Noop.
   98534     */
   98535     if( addrSortIndex>=0 && pOrderBy==0 ){
   98536       sqlite3VdbeChangeToNoop(v, addrSortIndex);
   98537       p->addrOpenEphm[2] = -1;
   98538     }
   98539 
   98540     if( pWInfo->eDistinct ){
   98541       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
   98542 
   98543       assert( addrDistinctIndex>=0 );
   98544       pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
   98545 
   98546       assert( isDistinct );
   98547       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
   98548            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
   98549       );
   98550       distinct = -1;
   98551       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
   98552         int iJump;
   98553         int iExpr;
   98554         int iFlag = ++pParse->nMem;
   98555         int iBase = pParse->nMem+1;
   98556         int iBase2 = iBase + pEList->nExpr;
   98557         pParse->nMem += (pEList->nExpr*2);
   98558 
   98559         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
   98560         ** OP_Integer initializes the "first row" flag.  */
   98561         pOp->opcode = OP_Integer;
   98562         pOp->p1 = 1;
   98563         pOp->p2 = iFlag;
   98564 
   98565         sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
   98566         iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
   98567         sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
   98568         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
   98569           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
   98570           sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
   98571           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   98572           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   98573         }
   98574         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
   98575 
   98576         sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
   98577         assert( sqlite3VdbeCurrentAddr(v)==iJump );
   98578         sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
   98579       }else{
   98580         pOp->opcode = OP_Noop;
   98581       }
   98582     }
   98583 
   98584     /* Use the standard inner loop. */
   98585     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
   98586                     pWInfo->iContinue, pWInfo->iBreak);
   98587 
   98588     /* End the database scan loop.
   98589     */
   98590     sqlite3WhereEnd(pWInfo);
   98591   }else{
   98592     /* This is the processing for aggregate queries */
   98593     NameContext sNC;    /* Name context for processing aggregate information */
   98594     int iAMem;          /* First Mem address for storing current GROUP BY */
   98595     int iBMem;          /* First Mem address for previous GROUP BY */
   98596     int iUseFlag;       /* Mem address holding flag indicating that at least
   98597                         ** one row of the input to the aggregator has been
   98598                         ** processed */
   98599     int iAbortFlag;     /* Mem address which causes query abort if positive */
   98600     int groupBySort;    /* Rows come from source in GROUP BY order */
   98601     int addrEnd;        /* End of processing for this SELECT */
   98602     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
   98603     int sortOut = 0;    /* Output register from the sorter */
   98604 
   98605     /* Remove any and all aliases between the result set and the
   98606     ** GROUP BY clause.
   98607     */
   98608     if( pGroupBy ){
   98609       int k;                        /* Loop counter */
   98610       struct ExprList_item *pItem;  /* For looping over expression in a list */
   98611 
   98612       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   98613         pItem->iAlias = 0;
   98614       }
   98615       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   98616         pItem->iAlias = 0;
   98617       }
   98618       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
   98619     }else{
   98620       p->nSelectRow = (double)1;
   98621     }
   98622 
   98623 
   98624     /* Create a label to jump to when we want to abort the query */
   98625     addrEnd = sqlite3VdbeMakeLabel(v);
   98626 
   98627     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   98628     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   98629     ** SELECT statement.
   98630     */
   98631     memset(&sNC, 0, sizeof(sNC));
   98632     sNC.pParse = pParse;
   98633     sNC.pSrcList = pTabList;
   98634     sNC.pAggInfo = &sAggInfo;
   98635     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   98636     sAggInfo.pGroupBy = pGroupBy;
   98637     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   98638     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
   98639     if( pHaving ){
   98640       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   98641     }
   98642     sAggInfo.nAccumulator = sAggInfo.nColumn;
   98643     for(i=0; i<sAggInfo.nFunc; i++){
   98644       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   98645       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   98646     }
   98647     if( db->mallocFailed ) goto select_end;
   98648 
   98649     /* Processing for aggregates with GROUP BY is very different and
   98650     ** much more complex than aggregates without a GROUP BY.
   98651     */
   98652     if( pGroupBy ){
   98653       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   98654       int j1;             /* A-vs-B comparision jump */
   98655       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   98656       int regOutputRow;   /* Return address register for output subroutine */
   98657       int addrSetAbort;   /* Set the abort flag and return */
   98658       int addrTopOfLoop;  /* Top of the input loop */
   98659       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   98660       int addrReset;      /* Subroutine for resetting the accumulator */
   98661       int regReset;       /* Return address register for reset subroutine */
   98662 
   98663       /* If there is a GROUP BY clause we might need a sorting index to
   98664       ** implement it.  Allocate that sorting index now.  If it turns out
   98665       ** that we do not need it after all, the OP_SorterOpen instruction
   98666       ** will be converted into a Noop.
   98667       */
   98668       sAggInfo.sortingIdx = pParse->nTab++;
   98669       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
   98670       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
   98671           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   98672           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   98673 
   98674       /* Initialize memory locations used by GROUP BY aggregate processing
   98675       */
   98676       iUseFlag = ++pParse->nMem;
   98677       iAbortFlag = ++pParse->nMem;
   98678       regOutputRow = ++pParse->nMem;
   98679       addrOutputRow = sqlite3VdbeMakeLabel(v);
   98680       regReset = ++pParse->nMem;
   98681       addrReset = sqlite3VdbeMakeLabel(v);
   98682       iAMem = pParse->nMem + 1;
   98683       pParse->nMem += pGroupBy->nExpr;
   98684       iBMem = pParse->nMem + 1;
   98685       pParse->nMem += pGroupBy->nExpr;
   98686       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   98687       VdbeComment((v, "clear abort flag"));
   98688       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   98689       VdbeComment((v, "indicate accumulator empty"));
   98690       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
   98691 
   98692       /* Begin a loop that will extract all source rows in GROUP BY order.
   98693       ** This might involve two separate loops with an OP_Sort in between, or
   98694       ** it might be a single loop that uses an index to extract information
   98695       ** in the right order to begin with.
   98696       */
   98697       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   98698       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
   98699       if( pWInfo==0 ) goto select_end;
   98700       if( pGroupBy==0 ){
   98701         /* The optimizer is able to deliver rows in group by order so
   98702         ** we do not have to sort.  The OP_OpenEphemeral table will be
   98703         ** cancelled later because we still need to use the pKeyInfo
   98704         */
   98705         pGroupBy = p->pGroupBy;
   98706         groupBySort = 0;
   98707       }else{
   98708         /* Rows are coming out in undetermined order.  We have to push
   98709         ** each row into a sorting index, terminate the first loop,
   98710         ** then loop over the sorting index in order to get the output
   98711         ** in sorted order
   98712         */
   98713         int regBase;
   98714         int regRecord;
   98715         int nCol;
   98716         int nGroupBy;
   98717 
   98718         explainTempTable(pParse,
   98719             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
   98720 
   98721         groupBySort = 1;
   98722         nGroupBy = pGroupBy->nExpr;
   98723         nCol = nGroupBy + 1;
   98724         j = nGroupBy+1;
   98725         for(i=0; i<sAggInfo.nColumn; i++){
   98726           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   98727             nCol++;
   98728             j++;
   98729           }
   98730         }
   98731         regBase = sqlite3GetTempRange(pParse, nCol);
   98732         sqlite3ExprCacheClear(pParse);
   98733         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   98734         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   98735         j = nGroupBy+1;
   98736         for(i=0; i<sAggInfo.nColumn; i++){
   98737           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   98738           if( pCol->iSorterColumn>=j ){
   98739             int r1 = j + regBase;
   98740             int r2;
   98741 
   98742             r2 = sqlite3ExprCodeGetColumn(pParse,
   98743                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
   98744             if( r1!=r2 ){
   98745               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   98746             }
   98747             j++;
   98748           }
   98749         }
   98750         regRecord = sqlite3GetTempReg(pParse);
   98751         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   98752         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
   98753         sqlite3ReleaseTempReg(pParse, regRecord);
   98754         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   98755         sqlite3WhereEnd(pWInfo);
   98756         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
   98757         sortOut = sqlite3GetTempReg(pParse);
   98758         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
   98759         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
   98760         VdbeComment((v, "GROUP BY sort"));
   98761         sAggInfo.useSortingIdx = 1;
   98762         sqlite3ExprCacheClear(pParse);
   98763       }
   98764 
   98765       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   98766       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   98767       ** Then compare the current GROUP BY terms against the GROUP BY terms
   98768       ** from the previous row currently stored in a0, a1, a2...
   98769       */
   98770       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   98771       sqlite3ExprCacheClear(pParse);
   98772       if( groupBySort ){
   98773         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
   98774       }
   98775       for(j=0; j<pGroupBy->nExpr; j++){
   98776         if( groupBySort ){
   98777           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
   98778           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   98779         }else{
   98780           sAggInfo.directMode = 1;
   98781           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   98782         }
   98783       }
   98784       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   98785                           (char*)pKeyInfo, P4_KEYINFO);
   98786       j1 = sqlite3VdbeCurrentAddr(v);
   98787       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
   98788 
   98789       /* Generate code that runs whenever the GROUP BY changes.
   98790       ** Changes in the GROUP BY are detected by the previous code
   98791       ** block.  If there were no changes, this block is skipped.
   98792       **
   98793       ** This code copies current group by terms in b0,b1,b2,...
   98794       ** over to a0,a1,a2.  It then calls the output subroutine
   98795       ** and resets the aggregate accumulator registers in preparation
   98796       ** for the next GROUP BY batch.
   98797       */
   98798       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   98799       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   98800       VdbeComment((v, "output one row"));
   98801       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
   98802       VdbeComment((v, "check abort flag"));
   98803       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   98804       VdbeComment((v, "reset accumulator"));
   98805 
   98806       /* Update the aggregate accumulators based on the content of
   98807       ** the current row
   98808       */
   98809       sqlite3VdbeJumpHere(v, j1);
   98810       updateAccumulator(pParse, &sAggInfo);
   98811       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   98812       VdbeComment((v, "indicate data in accumulator"));
   98813 
   98814       /* End of the loop
   98815       */
   98816       if( groupBySort ){
   98817         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
   98818       }else{
   98819         sqlite3WhereEnd(pWInfo);
   98820         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
   98821       }
   98822 
   98823       /* Output the final row of result
   98824       */
   98825       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   98826       VdbeComment((v, "output final row"));
   98827 
   98828       /* Jump over the subroutines
   98829       */
   98830       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   98831 
   98832       /* Generate a subroutine that outputs a single row of the result
   98833       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   98834       ** is less than or equal to zero, the subroutine is a no-op.  If
   98835       ** the processing calls for the query to abort, this subroutine
   98836       ** increments the iAbortFlag memory location before returning in
   98837       ** order to signal the caller to abort.
   98838       */
   98839       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   98840       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   98841       VdbeComment((v, "set abort flag"));
   98842       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98843       sqlite3VdbeResolveLabel(v, addrOutputRow);
   98844       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   98845       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
   98846       VdbeComment((v, "Groupby result generator entry point"));
   98847       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98848       finalizeAggFunctions(pParse, &sAggInfo);
   98849       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   98850       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
   98851                       distinct, pDest,
   98852                       addrOutputRow+1, addrSetAbort);
   98853       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   98854       VdbeComment((v, "end groupby result generator"));
   98855 
   98856       /* Generate a subroutine that will reset the group-by accumulator
   98857       */
   98858       sqlite3VdbeResolveLabel(v, addrReset);
   98859       resetAccumulator(pParse, &sAggInfo);
   98860       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   98861 
   98862     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   98863     else {
   98864       ExprList *pDel = 0;
   98865 #ifndef SQLITE_OMIT_BTREECOUNT
   98866       Table *pTab;
   98867       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   98868         /* If isSimpleCount() returns a pointer to a Table structure, then
   98869         ** the SQL statement is of the form:
   98870         **
   98871         **   SELECT count(*) FROM <tbl>
   98872         **
   98873         ** where the Table structure returned represents table <tbl>.
   98874         **
   98875         ** This statement is so common that it is optimized specially. The
   98876         ** OP_Count instruction is executed either on the intkey table that
   98877         ** contains the data for table <tbl> or on one of its indexes. It
   98878         ** is better to execute the op on an index, as indexes are almost
   98879         ** always spread across less pages than their corresponding tables.
   98880         */
   98881         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   98882         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   98883         Index *pIdx;                         /* Iterator variable */
   98884         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   98885         Index *pBest = 0;                    /* Best index found so far */
   98886         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   98887 
   98888         sqlite3CodeVerifySchema(pParse, iDb);
   98889         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   98890 
   98891         /* Search for the index that has the least amount of columns. If
   98892         ** there is such an index, and it has less columns than the table
   98893         ** does, then we can assume that it consumes less space on disk and
   98894         ** will therefore be cheaper to scan to determine the query result.
   98895         ** In this case set iRoot to the root page number of the index b-tree
   98896         ** and pKeyInfo to the KeyInfo structure required to navigate the
   98897         ** index.
   98898         **
   98899         ** (2011-04-15) Do not do a full scan of an unordered index.
   98900         **
   98901         ** In practice the KeyInfo structure will not be used. It is only
   98902         ** passed to keep OP_OpenRead happy.
   98903         */
   98904         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   98905           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
   98906             pBest = pIdx;
   98907           }
   98908         }
   98909         if( pBest && pBest->nColumn<pTab->nCol ){
   98910           iRoot = pBest->tnum;
   98911           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
   98912         }
   98913 
   98914         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   98915         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
   98916         if( pKeyInfo ){
   98917           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
   98918         }
   98919         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   98920         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   98921         explainSimpleCount(pParse, pTab, pBest);
   98922       }else
   98923 #endif /* SQLITE_OMIT_BTREECOUNT */
   98924       {
   98925         /* Check if the query is of one of the following forms:
   98926         **
   98927         **   SELECT min(x) FROM ...
   98928         **   SELECT max(x) FROM ...
   98929         **
   98930         ** If it is, then ask the code in where.c to attempt to sort results
   98931         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   98932         ** If where.c is able to produce results sorted in this order, then
   98933         ** add vdbe code to break out of the processing loop after the
   98934         ** first iteration (since the first iteration of the loop is
   98935         ** guaranteed to operate on the row with the minimum or maximum
   98936         ** value of x, the only row required).
   98937         **
   98938         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   98939         ** modify behaviour as follows:
   98940         **
   98941         **   + If the query is a "SELECT min(x)", then the loop coded by
   98942         **     where.c should not iterate over any values with a NULL value
   98943         **     for x.
   98944         **
   98945         **   + The optimizer code in where.c (the thing that decides which
   98946         **     index or indices to use) should place a different priority on
   98947         **     satisfying the 'ORDER BY' clause than it does in other cases.
   98948         **     Refer to code and comments in where.c for details.
   98949         */
   98950         ExprList *pMinMax = 0;
   98951         u8 flag = minMaxQuery(p);
   98952         if( flag ){
   98953           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
   98954           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
   98955           pDel = pMinMax;
   98956           if( pMinMax && !db->mallocFailed ){
   98957             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   98958             pMinMax->a[0].pExpr->op = TK_COLUMN;
   98959           }
   98960         }
   98961 
   98962         /* This case runs if the aggregate has no GROUP BY clause.  The
   98963         ** processing is much simpler since there is only a single row
   98964         ** of output.
   98965         */
   98966         resetAccumulator(pParse, &sAggInfo);
   98967         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
   98968         if( pWInfo==0 ){
   98969           sqlite3ExprListDelete(db, pDel);
   98970           goto select_end;
   98971         }
   98972         updateAccumulator(pParse, &sAggInfo);
   98973         if( !pMinMax && flag ){
   98974           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
   98975           VdbeComment((v, "%s() by index",
   98976                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   98977         }
   98978         sqlite3WhereEnd(pWInfo);
   98979         finalizeAggFunctions(pParse, &sAggInfo);
   98980       }
   98981 
   98982       pOrderBy = 0;
   98983       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   98984       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
   98985                       pDest, addrEnd, addrEnd);
   98986       sqlite3ExprListDelete(db, pDel);
   98987     }
   98988     sqlite3VdbeResolveLabel(v, addrEnd);
   98989 
   98990   } /* endif aggregate query */
   98991 
   98992   if( distinct>=0 ){
   98993     explainTempTable(pParse, "DISTINCT");
   98994   }
   98995 
   98996   /* If there is an ORDER BY clause, then we need to sort the results
   98997   ** and send them to the callback one by one.
   98998   */
   98999   if( pOrderBy ){
   99000     explainTempTable(pParse, "ORDER BY");
   99001     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
   99002   }
   99003 
   99004   /* Jump here to skip this query
   99005   */
   99006   sqlite3VdbeResolveLabel(v, iEnd);
   99007 
   99008   /* The SELECT was successfully coded.   Set the return code to 0
   99009   ** to indicate no errors.
   99010   */
   99011   rc = 0;
   99012 
   99013   /* Control jumps to here if an error is encountered above, or upon
   99014   ** successful coding of the SELECT.
   99015   */
   99016 select_end:
   99017   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   99018 
   99019   /* Identify column names if results of the SELECT are to be output.
   99020   */
   99021   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   99022     generateColumnNames(pParse, pTabList, pEList);
   99023   }
   99024 
   99025   sqlite3DbFree(db, sAggInfo.aCol);
   99026   sqlite3DbFree(db, sAggInfo.aFunc);
   99027   return rc;
   99028 }
   99029 
   99030 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   99031 /*
   99032 ** Generate a human-readable description of a the Select object.
   99033 */
   99034 static void explainOneSelect(Vdbe *pVdbe, Select *p){
   99035   sqlite3ExplainPrintf(pVdbe, "SELECT ");
   99036   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   99037     if( p->selFlags & SF_Distinct ){
   99038       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
   99039     }
   99040     if( p->selFlags & SF_Aggregate ){
   99041       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
   99042     }
   99043     sqlite3ExplainNL(pVdbe);
   99044     sqlite3ExplainPrintf(pVdbe, "   ");
   99045   }
   99046   sqlite3ExplainExprList(pVdbe, p->pEList);
   99047   sqlite3ExplainNL(pVdbe);
   99048   if( p->pSrc && p->pSrc->nSrc ){
   99049     int i;
   99050     sqlite3ExplainPrintf(pVdbe, "FROM ");
   99051     sqlite3ExplainPush(pVdbe);
   99052     for(i=0; i<p->pSrc->nSrc; i++){
   99053       struct SrcList_item *pItem = &p->pSrc->a[i];
   99054       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
   99055       if( pItem->pSelect ){
   99056         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
   99057         if( pItem->pTab ){
   99058           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
   99059         }
   99060       }else if( pItem->zName ){
   99061         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
   99062       }
   99063       if( pItem->zAlias ){
   99064         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
   99065       }
   99066       if( pItem->jointype & JT_LEFT ){
   99067         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
   99068       }
   99069       sqlite3ExplainNL(pVdbe);
   99070     }
   99071     sqlite3ExplainPop(pVdbe);
   99072   }
   99073   if( p->pWhere ){
   99074     sqlite3ExplainPrintf(pVdbe, "WHERE ");
   99075     sqlite3ExplainExpr(pVdbe, p->pWhere);
   99076     sqlite3ExplainNL(pVdbe);
   99077   }
   99078   if( p->pGroupBy ){
   99079     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
   99080     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
   99081     sqlite3ExplainNL(pVdbe);
   99082   }
   99083   if( p->pHaving ){
   99084     sqlite3ExplainPrintf(pVdbe, "HAVING ");
   99085     sqlite3ExplainExpr(pVdbe, p->pHaving);
   99086     sqlite3ExplainNL(pVdbe);
   99087   }
   99088   if( p->pOrderBy ){
   99089     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
   99090     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
   99091     sqlite3ExplainNL(pVdbe);
   99092   }
   99093   if( p->pLimit ){
   99094     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
   99095     sqlite3ExplainExpr(pVdbe, p->pLimit);
   99096     sqlite3ExplainNL(pVdbe);
   99097   }
   99098   if( p->pOffset ){
   99099     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
   99100     sqlite3ExplainExpr(pVdbe, p->pOffset);
   99101     sqlite3ExplainNL(pVdbe);
   99102   }
   99103 }
   99104 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
   99105   if( p==0 ){
   99106     sqlite3ExplainPrintf(pVdbe, "(null-select)");
   99107     return;
   99108   }
   99109   while( p->pPrior ) p = p->pPrior;
   99110   sqlite3ExplainPush(pVdbe);
   99111   while( p ){
   99112     explainOneSelect(pVdbe, p);
   99113     p = p->pNext;
   99114     if( p==0 ) break;
   99115     sqlite3ExplainNL(pVdbe);
   99116     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
   99117   }
   99118   sqlite3ExplainPrintf(pVdbe, "END");
   99119   sqlite3ExplainPop(pVdbe);
   99120 }
   99121 
   99122 /* End of the structure debug printing code
   99123 *****************************************************************************/
   99124 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
   99125 
   99126 /************** End of select.c **********************************************/
   99127 /************** Begin file table.c *******************************************/
   99128 /*
   99129 ** 2001 September 15
   99130 **
   99131 ** The author disclaims copyright to this source code.  In place of
   99132 ** a legal notice, here is a blessing:
   99133 **
   99134 **    May you do good and not evil.
   99135 **    May you find forgiveness for yourself and forgive others.
   99136 **    May you share freely, never taking more than you give.
   99137 **
   99138 *************************************************************************
   99139 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   99140 ** interface routines.  These are just wrappers around the main
   99141 ** interface routine of sqlite3_exec().
   99142 **
   99143 ** These routines are in a separate files so that they will not be linked
   99144 ** if they are not used.
   99145 */
   99146 /* #include <stdlib.h> */
   99147 /* #include <string.h> */
   99148 
   99149 #ifndef SQLITE_OMIT_GET_TABLE
   99150 
   99151 /*
   99152 ** This structure is used to pass data from sqlite3_get_table() through
   99153 ** to the callback function is uses to build the result.
   99154 */
   99155 typedef struct TabResult {
   99156   char **azResult;   /* Accumulated output */
   99157   char *zErrMsg;     /* Error message text, if an error occurs */
   99158   int nAlloc;        /* Slots allocated for azResult[] */
   99159   int nRow;          /* Number of rows in the result */
   99160   int nColumn;       /* Number of columns in the result */
   99161   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   99162   int rc;            /* Return code from sqlite3_exec() */
   99163 } TabResult;
   99164 
   99165 /*
   99166 ** This routine is called once for each row in the result table.  Its job
   99167 ** is to fill in the TabResult structure appropriately, allocating new
   99168 ** memory as necessary.
   99169 */
   99170 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   99171   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   99172   int need;                         /* Slots needed in p->azResult[] */
   99173   int i;                            /* Loop counter */
   99174   char *z;                          /* A single column of result */
   99175 
   99176   /* Make sure there is enough space in p->azResult to hold everything
   99177   ** we need to remember from this invocation of the callback.
   99178   */
   99179   if( p->nRow==0 && argv!=0 ){
   99180     need = nCol*2;
   99181   }else{
   99182     need = nCol;
   99183   }
   99184   if( p->nData + need > p->nAlloc ){
   99185     char **azNew;
   99186     p->nAlloc = p->nAlloc*2 + need;
   99187     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   99188     if( azNew==0 ) goto malloc_failed;
   99189     p->azResult = azNew;
   99190   }
   99191 
   99192   /* If this is the first row, then generate an extra row containing
   99193   ** the names of all columns.
   99194   */
   99195   if( p->nRow==0 ){
   99196     p->nColumn = nCol;
   99197     for(i=0; i<nCol; i++){
   99198       z = sqlite3_mprintf("%s", colv[i]);
   99199       if( z==0 ) goto malloc_failed;
   99200       p->azResult[p->nData++] = z;
   99201     }
   99202   }else if( p->nColumn!=nCol ){
   99203     sqlite3_free(p->zErrMsg);
   99204     p->zErrMsg = sqlite3_mprintf(
   99205        "sqlite3_get_table() called with two or more incompatible queries"
   99206     );
   99207     p->rc = SQLITE_ERROR;
   99208     return 1;
   99209   }
   99210 
   99211   /* Copy over the row data
   99212   */
   99213   if( argv!=0 ){
   99214     for(i=0; i<nCol; i++){
   99215       if( argv[i]==0 ){
   99216         z = 0;
   99217       }else{
   99218         int n = sqlite3Strlen30(argv[i])+1;
   99219         z = sqlite3_malloc( n );
   99220         if( z==0 ) goto malloc_failed;
   99221         memcpy(z, argv[i], n);
   99222       }
   99223       p->azResult[p->nData++] = z;
   99224     }
   99225     p->nRow++;
   99226   }
   99227   return 0;
   99228 
   99229 malloc_failed:
   99230   p->rc = SQLITE_NOMEM;
   99231   return 1;
   99232 }
   99233 
   99234 /*
   99235 ** Query the database.  But instead of invoking a callback for each row,
   99236 ** malloc() for space to hold the result and return the entire results
   99237 ** at the conclusion of the call.
   99238 **
   99239 ** The result that is written to ***pazResult is held in memory obtained
   99240 ** from malloc().  But the caller cannot free this memory directly.
   99241 ** Instead, the entire table should be passed to sqlite3_free_table() when
   99242 ** the calling procedure is finished using it.
   99243 */
   99244 SQLITE_API int sqlite3_get_table(
   99245   sqlite3 *db,                /* The database on which the SQL executes */
   99246   const char *zSql,           /* The SQL to be executed */
   99247   char ***pazResult,          /* Write the result table here */
   99248   int *pnRow,                 /* Write the number of rows in the result here */
   99249   int *pnColumn,              /* Write the number of columns of result here */
   99250   char **pzErrMsg             /* Write error messages here */
   99251 ){
   99252   int rc;
   99253   TabResult res;
   99254 
   99255   *pazResult = 0;
   99256   if( pnColumn ) *pnColumn = 0;
   99257   if( pnRow ) *pnRow = 0;
   99258   if( pzErrMsg ) *pzErrMsg = 0;
   99259   res.zErrMsg = 0;
   99260   res.nRow = 0;
   99261   res.nColumn = 0;
   99262   res.nData = 1;
   99263   res.nAlloc = 20;
   99264   res.rc = SQLITE_OK;
   99265   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   99266   if( res.azResult==0 ){
   99267      db->errCode = SQLITE_NOMEM;
   99268      return SQLITE_NOMEM;
   99269   }
   99270   res.azResult[0] = 0;
   99271   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   99272   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   99273   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   99274   if( (rc&0xff)==SQLITE_ABORT ){
   99275     sqlite3_free_table(&res.azResult[1]);
   99276     if( res.zErrMsg ){
   99277       if( pzErrMsg ){
   99278         sqlite3_free(*pzErrMsg);
   99279         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   99280       }
   99281       sqlite3_free(res.zErrMsg);
   99282     }
   99283     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   99284     return res.rc;
   99285   }
   99286   sqlite3_free(res.zErrMsg);
   99287   if( rc!=SQLITE_OK ){
   99288     sqlite3_free_table(&res.azResult[1]);
   99289     return rc;
   99290   }
   99291   if( res.nAlloc>res.nData ){
   99292     char **azNew;
   99293     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   99294     if( azNew==0 ){
   99295       sqlite3_free_table(&res.azResult[1]);
   99296       db->errCode = SQLITE_NOMEM;
   99297       return SQLITE_NOMEM;
   99298     }
   99299     res.azResult = azNew;
   99300   }
   99301   *pazResult = &res.azResult[1];
   99302   if( pnColumn ) *pnColumn = res.nColumn;
   99303   if( pnRow ) *pnRow = res.nRow;
   99304   return rc;
   99305 }
   99306 
   99307 /*
   99308 ** This routine frees the space the sqlite3_get_table() malloced.
   99309 */
   99310 SQLITE_API void sqlite3_free_table(
   99311   char **azResult            /* Result returned from from sqlite3_get_table() */
   99312 ){
   99313   if( azResult ){
   99314     int i, n;
   99315     azResult--;
   99316     assert( azResult!=0 );
   99317     n = SQLITE_PTR_TO_INT(azResult[0]);
   99318     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   99319     sqlite3_free(azResult);
   99320   }
   99321 }
   99322 
   99323 #endif /* SQLITE_OMIT_GET_TABLE */
   99324 
   99325 /************** End of table.c ***********************************************/
   99326 /************** Begin file trigger.c *****************************************/
   99327 /*
   99328 **
   99329 ** The author disclaims copyright to this source code.  In place of
   99330 ** a legal notice, here is a blessing:
   99331 **
   99332 **    May you do good and not evil.
   99333 **    May you find forgiveness for yourself and forgive others.
   99334 **    May you share freely, never taking more than you give.
   99335 **
   99336 *************************************************************************
   99337 ** This file contains the implementation for TRIGGERs
   99338 */
   99339 
   99340 #ifndef SQLITE_OMIT_TRIGGER
   99341 /*
   99342 ** Delete a linked list of TriggerStep structures.
   99343 */
   99344 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   99345   while( pTriggerStep ){
   99346     TriggerStep * pTmp = pTriggerStep;
   99347     pTriggerStep = pTriggerStep->pNext;
   99348 
   99349     sqlite3ExprDelete(db, pTmp->pWhere);
   99350     sqlite3ExprListDelete(db, pTmp->pExprList);
   99351     sqlite3SelectDelete(db, pTmp->pSelect);
   99352     sqlite3IdListDelete(db, pTmp->pIdList);
   99353 
   99354     sqlite3DbFree(db, pTmp);
   99355   }
   99356 }
   99357 
   99358 /*
   99359 ** Given table pTab, return a list of all the triggers attached to
   99360 ** the table. The list is connected by Trigger.pNext pointers.
   99361 **
   99362 ** All of the triggers on pTab that are in the same database as pTab
   99363 ** are already attached to pTab->pTrigger.  But there might be additional
   99364 ** triggers on pTab in the TEMP schema.  This routine prepends all
   99365 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   99366 ** and returns the combined list.
   99367 **
   99368 ** To state it another way:  This routine returns a list of all triggers
   99369 ** that fire off of pTab.  The list will include any TEMP triggers on
   99370 ** pTab as well as the triggers lised in pTab->pTrigger.
   99371 */
   99372 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   99373   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   99374   Trigger *pList = 0;                  /* List of triggers to return */
   99375 
   99376   if( pParse->disableTriggers ){
   99377     return 0;
   99378   }
   99379 
   99380   if( pTmpSchema!=pTab->pSchema ){
   99381     HashElem *p;
   99382     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
   99383     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   99384       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   99385       if( pTrig->pTabSchema==pTab->pSchema
   99386        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   99387       ){
   99388         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   99389         pList = pTrig;
   99390       }
   99391     }
   99392   }
   99393 
   99394   return (pList ? pList : pTab->pTrigger);
   99395 }
   99396 
   99397 /*
   99398 ** This is called by the parser when it sees a CREATE TRIGGER statement
   99399 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   99400 ** structure is generated based on the information available and stored
   99401 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   99402 ** sqlite3FinishTrigger() function is called to complete the trigger
   99403 ** construction process.
   99404 */
   99405 SQLITE_PRIVATE void sqlite3BeginTrigger(
   99406   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   99407   Token *pName1,      /* The name of the trigger */
   99408   Token *pName2,      /* The name of the trigger */
   99409   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   99410   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   99411   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   99412   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   99413   Expr *pWhen,        /* WHEN clause */
   99414   int isTemp,         /* True if the TEMPORARY keyword is present */
   99415   int noErr           /* Suppress errors if the trigger already exists */
   99416 ){
   99417   Trigger *pTrigger = 0;  /* The new trigger */
   99418   Table *pTab;            /* Table that the trigger fires off of */
   99419   char *zName = 0;        /* Name of the trigger */
   99420   sqlite3 *db = pParse->db;  /* The database connection */
   99421   int iDb;                /* The database to store the trigger in */
   99422   Token *pName;           /* The unqualified db name */
   99423   DbFixer sFix;           /* State vector for the DB fixer */
   99424   int iTabDb;             /* Index of the database holding pTab */
   99425 
   99426   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   99427   assert( pName2!=0 );
   99428   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   99429   assert( op>0 && op<0xff );
   99430   if( isTemp ){
   99431     /* If TEMP was specified, then the trigger name may not be qualified. */
   99432     if( pName2->n>0 ){
   99433       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   99434       goto trigger_cleanup;
   99435     }
   99436     iDb = 1;
   99437     pName = pName1;
   99438   }else{
   99439     /* Figure out the db that the the trigger will be created in */
   99440     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   99441     if( iDb<0 ){
   99442       goto trigger_cleanup;
   99443     }
   99444   }
   99445   if( !pTableName || db->mallocFailed ){
   99446     goto trigger_cleanup;
   99447   }
   99448 
   99449   /* A long-standing parser bug is that this syntax was allowed:
   99450   **
   99451   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
   99452   **                                                 ^^^^^^^^
   99453   **
   99454   ** To maintain backwards compatibility, ignore the database
   99455   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
   99456   */
   99457   if( db->init.busy && iDb!=1 ){
   99458     sqlite3DbFree(db, pTableName->a[0].zDatabase);
   99459     pTableName->a[0].zDatabase = 0;
   99460   }
   99461 
   99462   /* If the trigger name was unqualified, and the table is a temp table,
   99463   ** then set iDb to 1 to create the trigger in the temporary database.
   99464   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   99465   ** exist, the error is caught by the block below.
   99466   */
   99467   pTab = sqlite3SrcListLookup(pParse, pTableName);
   99468   if( db->init.busy==0 && pName2->n==0 && pTab
   99469         && pTab->pSchema==db->aDb[1].pSchema ){
   99470     iDb = 1;
   99471   }
   99472 
   99473   /* Ensure the table name matches database name and that the table exists */
   99474   if( db->mallocFailed ) goto trigger_cleanup;
   99475   assert( pTableName->nSrc==1 );
   99476   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
   99477       sqlite3FixSrcList(&sFix, pTableName) ){
   99478     goto trigger_cleanup;
   99479   }
   99480   pTab = sqlite3SrcListLookup(pParse, pTableName);
   99481   if( !pTab ){
   99482     /* The table does not exist. */
   99483     if( db->init.iDb==1 ){
   99484       /* Ticket #3810.
   99485       ** Normally, whenever a table is dropped, all associated triggers are
   99486       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   99487       ** and the table is dropped by a different database connection, the
   99488       ** trigger is not visible to the database connection that does the
   99489       ** drop so the trigger cannot be dropped.  This results in an
   99490       ** "orphaned trigger" - a trigger whose associated table is missing.
   99491       */
   99492       db->init.orphanTrigger = 1;
   99493     }
   99494     goto trigger_cleanup;
   99495   }
   99496   if( IsVirtual(pTab) ){
   99497     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   99498     goto trigger_cleanup;
   99499   }
   99500 
   99501   /* Check that the trigger name is not reserved and that no trigger of the
   99502   ** specified name exists */
   99503   zName = sqlite3NameFromToken(db, pName);
   99504   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   99505     goto trigger_cleanup;
   99506   }
   99507   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99508   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   99509                       zName, sqlite3Strlen30(zName)) ){
   99510     if( !noErr ){
   99511       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   99512     }else{
   99513       assert( !db->init.busy );
   99514       sqlite3CodeVerifySchema(pParse, iDb);
   99515     }
   99516     goto trigger_cleanup;
   99517   }
   99518 
   99519   /* Do not create a trigger on a system table */
   99520   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   99521     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   99522     pParse->nErr++;
   99523     goto trigger_cleanup;
   99524   }
   99525 
   99526   /* INSTEAD of triggers are only for views and views only support INSTEAD
   99527   ** of triggers.
   99528   */
   99529   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   99530     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   99531         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   99532     goto trigger_cleanup;
   99533   }
   99534   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   99535     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   99536         " trigger on table: %S", pTableName, 0);
   99537     goto trigger_cleanup;
   99538   }
   99539   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   99540 
   99541 #ifndef SQLITE_OMIT_AUTHORIZATION
   99542   {
   99543     int code = SQLITE_CREATE_TRIGGER;
   99544     const char *zDb = db->aDb[iTabDb].zName;
   99545     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   99546     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   99547     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   99548       goto trigger_cleanup;
   99549     }
   99550     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   99551       goto trigger_cleanup;
   99552     }
   99553   }
   99554 #endif
   99555 
   99556   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   99557   ** cannot appear on views.  So we might as well translate every
   99558   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   99559   ** elsewhere.
   99560   */
   99561   if (tr_tm == TK_INSTEAD){
   99562     tr_tm = TK_BEFORE;
   99563   }
   99564 
   99565   /* Build the Trigger object */
   99566   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   99567   if( pTrigger==0 ) goto trigger_cleanup;
   99568   pTrigger->zName = zName;
   99569   zName = 0;
   99570   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   99571   pTrigger->pSchema = db->aDb[iDb].pSchema;
   99572   pTrigger->pTabSchema = pTab->pSchema;
   99573   pTrigger->op = (u8)op;
   99574   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   99575   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   99576   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   99577   assert( pParse->pNewTrigger==0 );
   99578   pParse->pNewTrigger = pTrigger;
   99579 
   99580 trigger_cleanup:
   99581   sqlite3DbFree(db, zName);
   99582   sqlite3SrcListDelete(db, pTableName);
   99583   sqlite3IdListDelete(db, pColumns);
   99584   sqlite3ExprDelete(db, pWhen);
   99585   if( !pParse->pNewTrigger ){
   99586     sqlite3DeleteTrigger(db, pTrigger);
   99587   }else{
   99588     assert( pParse->pNewTrigger==pTrigger );
   99589   }
   99590 }
   99591 
   99592 /*
   99593 ** This routine is called after all of the trigger actions have been parsed
   99594 ** in order to complete the process of building the trigger.
   99595 */
   99596 SQLITE_PRIVATE void sqlite3FinishTrigger(
   99597   Parse *pParse,          /* Parser context */
   99598   TriggerStep *pStepList, /* The triggered program */
   99599   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   99600 ){
   99601   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   99602   char *zName;                            /* Name of trigger */
   99603   sqlite3 *db = pParse->db;               /* The database */
   99604   DbFixer sFix;                           /* Fixer object */
   99605   int iDb;                                /* Database containing the trigger */
   99606   Token nameToken;                        /* Trigger name for error reporting */
   99607 
   99608   pParse->pNewTrigger = 0;
   99609   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   99610   zName = pTrig->zName;
   99611   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   99612   pTrig->step_list = pStepList;
   99613   while( pStepList ){
   99614     pStepList->pTrig = pTrig;
   99615     pStepList = pStepList->pNext;
   99616   }
   99617   nameToken.z = pTrig->zName;
   99618   nameToken.n = sqlite3Strlen30(nameToken.z);
   99619   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
   99620           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
   99621     goto triggerfinish_cleanup;
   99622   }
   99623 
   99624   /* if we are not initializing,
   99625   ** build the sqlite_master entry
   99626   */
   99627   if( !db->init.busy ){
   99628     Vdbe *v;
   99629     char *z;
   99630 
   99631     /* Make an entry in the sqlite_master table */
   99632     v = sqlite3GetVdbe(pParse);
   99633     if( v==0 ) goto triggerfinish_cleanup;
   99634     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99635     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   99636     sqlite3NestedParse(pParse,
   99637        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   99638        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   99639        pTrig->table, z);
   99640     sqlite3DbFree(db, z);
   99641     sqlite3ChangeCookie(pParse, iDb);
   99642     sqlite3VdbeAddParseSchemaOp(v, iDb,
   99643         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
   99644   }
   99645 
   99646   if( db->init.busy ){
   99647     Trigger *pLink = pTrig;
   99648     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   99649     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99650     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   99651     if( pTrig ){
   99652       db->mallocFailed = 1;
   99653     }else if( pLink->pSchema==pLink->pTabSchema ){
   99654       Table *pTab;
   99655       int n = sqlite3Strlen30(pLink->table);
   99656       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   99657       assert( pTab!=0 );
   99658       pLink->pNext = pTab->pTrigger;
   99659       pTab->pTrigger = pLink;
   99660     }
   99661   }
   99662 
   99663 triggerfinish_cleanup:
   99664   sqlite3DeleteTrigger(db, pTrig);
   99665   assert( !pParse->pNewTrigger );
   99666   sqlite3DeleteTriggerStep(db, pStepList);
   99667 }
   99668 
   99669 /*
   99670 ** Turn a SELECT statement (that the pSelect parameter points to) into
   99671 ** a trigger step.  Return a pointer to a TriggerStep structure.
   99672 **
   99673 ** The parser calls this routine when it finds a SELECT statement in
   99674 ** body of a TRIGGER.
   99675 */
   99676 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   99677   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   99678   if( pTriggerStep==0 ) {
   99679     sqlite3SelectDelete(db, pSelect);
   99680     return 0;
   99681   }
   99682   pTriggerStep->op = TK_SELECT;
   99683   pTriggerStep->pSelect = pSelect;
   99684   pTriggerStep->orconf = OE_Default;
   99685   return pTriggerStep;
   99686 }
   99687 
   99688 /*
   99689 ** Allocate space to hold a new trigger step.  The allocated space
   99690 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   99691 **
   99692 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   99693 */
   99694 static TriggerStep *triggerStepAllocate(
   99695   sqlite3 *db,                /* Database connection */
   99696   u8 op,                      /* Trigger opcode */
   99697   Token *pName                /* The target name */
   99698 ){
   99699   TriggerStep *pTriggerStep;
   99700 
   99701   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   99702   if( pTriggerStep ){
   99703     char *z = (char*)&pTriggerStep[1];
   99704     memcpy(z, pName->z, pName->n);
   99705     pTriggerStep->target.z = z;
   99706     pTriggerStep->target.n = pName->n;
   99707     pTriggerStep->op = op;
   99708   }
   99709   return pTriggerStep;
   99710 }
   99711 
   99712 /*
   99713 ** Build a trigger step out of an INSERT statement.  Return a pointer
   99714 ** to the new trigger step.
   99715 **
   99716 ** The parser calls this routine when it sees an INSERT inside the
   99717 ** body of a trigger.
   99718 */
   99719 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   99720   sqlite3 *db,        /* The database connection */
   99721   Token *pTableName,  /* Name of the table into which we insert */
   99722   IdList *pColumn,    /* List of columns in pTableName to insert into */
   99723   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
   99724   Select *pSelect,    /* A SELECT statement that supplies values */
   99725   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   99726 ){
   99727   TriggerStep *pTriggerStep;
   99728 
   99729   assert(pEList == 0 || pSelect == 0);
   99730   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
   99731 
   99732   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   99733   if( pTriggerStep ){
   99734     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   99735     pTriggerStep->pIdList = pColumn;
   99736     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   99737     pTriggerStep->orconf = orconf;
   99738   }else{
   99739     sqlite3IdListDelete(db, pColumn);
   99740   }
   99741   sqlite3ExprListDelete(db, pEList);
   99742   sqlite3SelectDelete(db, pSelect);
   99743 
   99744   return pTriggerStep;
   99745 }
   99746 
   99747 /*
   99748 ** Construct a trigger step that implements an UPDATE statement and return
   99749 ** a pointer to that trigger step.  The parser calls this routine when it
   99750 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   99751 */
   99752 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   99753   sqlite3 *db,         /* The database connection */
   99754   Token *pTableName,   /* Name of the table to be updated */
   99755   ExprList *pEList,    /* The SET clause: list of column and new values */
   99756   Expr *pWhere,        /* The WHERE clause */
   99757   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   99758 ){
   99759   TriggerStep *pTriggerStep;
   99760 
   99761   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   99762   if( pTriggerStep ){
   99763     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   99764     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   99765     pTriggerStep->orconf = orconf;
   99766   }
   99767   sqlite3ExprListDelete(db, pEList);
   99768   sqlite3ExprDelete(db, pWhere);
   99769   return pTriggerStep;
   99770 }
   99771 
   99772 /*
   99773 ** Construct a trigger step that implements a DELETE statement and return
   99774 ** a pointer to that trigger step.  The parser calls this routine when it
   99775 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   99776 */
   99777 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   99778   sqlite3 *db,            /* Database connection */
   99779   Token *pTableName,      /* The table from which rows are deleted */
   99780   Expr *pWhere            /* The WHERE clause */
   99781 ){
   99782   TriggerStep *pTriggerStep;
   99783 
   99784   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   99785   if( pTriggerStep ){
   99786     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   99787     pTriggerStep->orconf = OE_Default;
   99788   }
   99789   sqlite3ExprDelete(db, pWhere);
   99790   return pTriggerStep;
   99791 }
   99792 
   99793 /*
   99794 ** Recursively delete a Trigger structure
   99795 */
   99796 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   99797   if( pTrigger==0 ) return;
   99798   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   99799   sqlite3DbFree(db, pTrigger->zName);
   99800   sqlite3DbFree(db, pTrigger->table);
   99801   sqlite3ExprDelete(db, pTrigger->pWhen);
   99802   sqlite3IdListDelete(db, pTrigger->pColumns);
   99803   sqlite3DbFree(db, pTrigger);
   99804 }
   99805 
   99806 /*
   99807 ** This function is called to drop a trigger from the database schema.
   99808 **
   99809 ** This may be called directly from the parser and therefore identifies
   99810 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   99811 ** same job as this routine except it takes a pointer to the trigger
   99812 ** instead of the trigger name.
   99813 **/
   99814 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   99815   Trigger *pTrigger = 0;
   99816   int i;
   99817   const char *zDb;
   99818   const char *zName;
   99819   int nName;
   99820   sqlite3 *db = pParse->db;
   99821 
   99822   if( db->mallocFailed ) goto drop_trigger_cleanup;
   99823   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   99824     goto drop_trigger_cleanup;
   99825   }
   99826 
   99827   assert( pName->nSrc==1 );
   99828   zDb = pName->a[0].zDatabase;
   99829   zName = pName->a[0].zName;
   99830   nName = sqlite3Strlen30(zName);
   99831   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   99832   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   99833     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   99834     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   99835     assert( sqlite3SchemaMutexHeld(db, j, 0) );
   99836     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   99837     if( pTrigger ) break;
   99838   }
   99839   if( !pTrigger ){
   99840     if( !noErr ){
   99841       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   99842     }else{
   99843       sqlite3CodeVerifyNamedSchema(pParse, zDb);
   99844     }
   99845     pParse->checkSchema = 1;
   99846     goto drop_trigger_cleanup;
   99847   }
   99848   sqlite3DropTriggerPtr(pParse, pTrigger);
   99849 
   99850 drop_trigger_cleanup:
   99851   sqlite3SrcListDelete(db, pName);
   99852 }
   99853 
   99854 /*
   99855 ** Return a pointer to the Table structure for the table that a trigger
   99856 ** is set on.
   99857 */
   99858 static Table *tableOfTrigger(Trigger *pTrigger){
   99859   int n = sqlite3Strlen30(pTrigger->table);
   99860   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   99861 }
   99862 
   99863 
   99864 /*
   99865 ** Drop a trigger given a pointer to that trigger.
   99866 */
   99867 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   99868   Table   *pTable;
   99869   Vdbe *v;
   99870   sqlite3 *db = pParse->db;
   99871   int iDb;
   99872 
   99873   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   99874   assert( iDb>=0 && iDb<db->nDb );
   99875   pTable = tableOfTrigger(pTrigger);
   99876   assert( pTable );
   99877   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   99878 #ifndef SQLITE_OMIT_AUTHORIZATION
   99879   {
   99880     int code = SQLITE_DROP_TRIGGER;
   99881     const char *zDb = db->aDb[iDb].zName;
   99882     const char *zTab = SCHEMA_TABLE(iDb);
   99883     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   99884     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   99885       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   99886       return;
   99887     }
   99888   }
   99889 #endif
   99890 
   99891   /* Generate code to destroy the database record of the trigger.
   99892   */
   99893   assert( pTable!=0 );
   99894   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   99895     int base;
   99896     static const VdbeOpList dropTrigger[] = {
   99897       { OP_Rewind,     0, ADDR(9),  0},
   99898       { OP_String8,    0, 1,        0}, /* 1 */
   99899       { OP_Column,     0, 1,        2},
   99900       { OP_Ne,         2, ADDR(8),  1},
   99901       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   99902       { OP_Column,     0, 0,        2},
   99903       { OP_Ne,         2, ADDR(8),  1},
   99904       { OP_Delete,     0, 0,        0},
   99905       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   99906     };
   99907 
   99908     sqlite3BeginWriteOperation(pParse, 0, iDb);
   99909     sqlite3OpenMasterTable(pParse, iDb);
   99910     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
   99911     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
   99912     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   99913     sqlite3ChangeCookie(pParse, iDb);
   99914     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   99915     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   99916     if( pParse->nMem<3 ){
   99917       pParse->nMem = 3;
   99918     }
   99919   }
   99920 }
   99921 
   99922 /*
   99923 ** Remove a trigger from the hash tables of the sqlite* pointer.
   99924 */
   99925 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   99926   Trigger *pTrigger;
   99927   Hash *pHash;
   99928 
   99929   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   99930   pHash = &(db->aDb[iDb].pSchema->trigHash);
   99931   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   99932   if( ALWAYS(pTrigger) ){
   99933     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   99934       Table *pTab = tableOfTrigger(pTrigger);
   99935       Trigger **pp;
   99936       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   99937       *pp = (*pp)->pNext;
   99938     }
   99939     sqlite3DeleteTrigger(db, pTrigger);
   99940     db->flags |= SQLITE_InternChanges;
   99941   }
   99942 }
   99943 
   99944 /*
   99945 ** pEList is the SET clause of an UPDATE statement.  Each entry
   99946 ** in pEList is of the format <id>=<expr>.  If any of the entries
   99947 ** in pEList have an <id> which matches an identifier in pIdList,
   99948 ** then return TRUE.  If pIdList==NULL, then it is considered a
   99949 ** wildcard that matches anything.  Likewise if pEList==NULL then
   99950 ** it matches anything so always return true.  Return false only
   99951 ** if there is no match.
   99952 */
   99953 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   99954   int e;
   99955   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   99956   for(e=0; e<pEList->nExpr; e++){
   99957     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   99958   }
   99959   return 0;
   99960 }
   99961 
   99962 /*
   99963 ** Return a list of all triggers on table pTab if there exists at least
   99964 ** one trigger that must be fired when an operation of type 'op' is
   99965 ** performed on the table, and, if that operation is an UPDATE, if at
   99966 ** least one of the columns in pChanges is being modified.
   99967 */
   99968 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   99969   Parse *pParse,          /* Parse context */
   99970   Table *pTab,            /* The table the contains the triggers */
   99971   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   99972   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   99973   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   99974 ){
   99975   int mask = 0;
   99976   Trigger *pList = 0;
   99977   Trigger *p;
   99978 
   99979   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
   99980     pList = sqlite3TriggerList(pParse, pTab);
   99981   }
   99982   assert( pList==0 || IsVirtual(pTab)==0 );
   99983   for(p=pList; p; p=p->pNext){
   99984     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   99985       mask |= p->tr_tm;
   99986     }
   99987   }
   99988   if( pMask ){
   99989     *pMask = mask;
   99990   }
   99991   return (mask ? pList : 0);
   99992 }
   99993 
   99994 /*
   99995 ** Convert the pStep->target token into a SrcList and return a pointer
   99996 ** to that SrcList.
   99997 **
   99998 ** This routine adds a specific database name, if needed, to the target when
   99999 ** forming the SrcList.  This prevents a trigger in one database from
   100000 ** referring to a target in another database.  An exception is when the
   100001 ** trigger is in TEMP in which case it can refer to any other database it
   100002 ** wants.
   100003 */
   100004 static SrcList *targetSrcList(
   100005   Parse *pParse,       /* The parsing context */
   100006   TriggerStep *pStep   /* The trigger containing the target token */
   100007 ){
   100008   int iDb;             /* Index of the database to use */
   100009   SrcList *pSrc;       /* SrcList to be returned */
   100010 
   100011   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   100012   if( pSrc ){
   100013     assert( pSrc->nSrc>0 );
   100014     assert( pSrc->a!=0 );
   100015     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   100016     if( iDb==0 || iDb>=2 ){
   100017       sqlite3 *db = pParse->db;
   100018       assert( iDb<pParse->db->nDb );
   100019       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   100020     }
   100021   }
   100022   return pSrc;
   100023 }
   100024 
   100025 /*
   100026 ** Generate VDBE code for the statements inside the body of a single
   100027 ** trigger.
   100028 */
   100029 static int codeTriggerProgram(
   100030   Parse *pParse,            /* The parser context */
   100031   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   100032   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   100033 ){
   100034   TriggerStep *pStep;
   100035   Vdbe *v = pParse->pVdbe;
   100036   sqlite3 *db = pParse->db;
   100037 
   100038   assert( pParse->pTriggerTab && pParse->pToplevel );
   100039   assert( pStepList );
   100040   assert( v!=0 );
   100041   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   100042     /* Figure out the ON CONFLICT policy that will be used for this step
   100043     ** of the trigger program. If the statement that caused this trigger
   100044     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   100045     ** the ON CONFLICT policy that was specified as part of the trigger
   100046     ** step statement. Example:
   100047     **
   100048     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   100049     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   100050     **   END;
   100051     **
   100052     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   100053     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   100054     */
   100055     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   100056 
   100057     switch( pStep->op ){
   100058       case TK_UPDATE: {
   100059         sqlite3Update(pParse,
   100060           targetSrcList(pParse, pStep),
   100061           sqlite3ExprListDup(db, pStep->pExprList, 0),
   100062           sqlite3ExprDup(db, pStep->pWhere, 0),
   100063           pParse->eOrconf
   100064         );
   100065         break;
   100066       }
   100067       case TK_INSERT: {
   100068         sqlite3Insert(pParse,
   100069           targetSrcList(pParse, pStep),
   100070           sqlite3ExprListDup(db, pStep->pExprList, 0),
   100071           sqlite3SelectDup(db, pStep->pSelect, 0),
   100072           sqlite3IdListDup(db, pStep->pIdList),
   100073           pParse->eOrconf
   100074         );
   100075         break;
   100076       }
   100077       case TK_DELETE: {
   100078         sqlite3DeleteFrom(pParse,
   100079           targetSrcList(pParse, pStep),
   100080           sqlite3ExprDup(db, pStep->pWhere, 0)
   100081         );
   100082         break;
   100083       }
   100084       default: assert( pStep->op==TK_SELECT ); {
   100085         SelectDest sDest;
   100086         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   100087         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   100088         sqlite3Select(pParse, pSelect, &sDest);
   100089         sqlite3SelectDelete(db, pSelect);
   100090         break;
   100091       }
   100092     }
   100093     if( pStep->op!=TK_SELECT ){
   100094       sqlite3VdbeAddOp0(v, OP_ResetCount);
   100095     }
   100096   }
   100097 
   100098   return 0;
   100099 }
   100100 
   100101 #ifdef SQLITE_DEBUG
   100102 /*
   100103 ** This function is used to add VdbeComment() annotations to a VDBE
   100104 ** program. It is not used in production code, only for debugging.
   100105 */
   100106 static const char *onErrorText(int onError){
   100107   switch( onError ){
   100108     case OE_Abort:    return "abort";
   100109     case OE_Rollback: return "rollback";
   100110     case OE_Fail:     return "fail";
   100111     case OE_Replace:  return "replace";
   100112     case OE_Ignore:   return "ignore";
   100113     case OE_Default:  return "default";
   100114   }
   100115   return "n/a";
   100116 }
   100117 #endif
   100118 
   100119 /*
   100120 ** Parse context structure pFrom has just been used to create a sub-vdbe
   100121 ** (trigger program). If an error has occurred, transfer error information
   100122 ** from pFrom to pTo.
   100123 */
   100124 static void transferParseError(Parse *pTo, Parse *pFrom){
   100125   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   100126   assert( pTo->zErrMsg==0 || pTo->nErr );
   100127   if( pTo->nErr==0 ){
   100128     pTo->zErrMsg = pFrom->zErrMsg;
   100129     pTo->nErr = pFrom->nErr;
   100130   }else{
   100131     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   100132   }
   100133 }
   100134 
   100135 /*
   100136 ** Create and populate a new TriggerPrg object with a sub-program
   100137 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   100138 */
   100139 static TriggerPrg *codeRowTrigger(
   100140   Parse *pParse,       /* Current parse context */
   100141   Trigger *pTrigger,   /* Trigger to code */
   100142   Table *pTab,         /* The table pTrigger is attached to */
   100143   int orconf           /* ON CONFLICT policy to code trigger program with */
   100144 ){
   100145   Parse *pTop = sqlite3ParseToplevel(pParse);
   100146   sqlite3 *db = pParse->db;   /* Database handle */
   100147   TriggerPrg *pPrg;           /* Value to return */
   100148   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   100149   Vdbe *v;                    /* Temporary VM */
   100150   NameContext sNC;            /* Name context for sub-vdbe */
   100151   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   100152   Parse *pSubParse;           /* Parse context for sub-vdbe */
   100153   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   100154 
   100155   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   100156   assert( pTop->pVdbe );
   100157 
   100158   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   100159   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   100160   ** list of the top-level Parse object sooner rather than later.  */
   100161   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   100162   if( !pPrg ) return 0;
   100163   pPrg->pNext = pTop->pTriggerPrg;
   100164   pTop->pTriggerPrg = pPrg;
   100165   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   100166   if( !pProgram ) return 0;
   100167   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   100168   pPrg->pTrigger = pTrigger;
   100169   pPrg->orconf = orconf;
   100170   pPrg->aColmask[0] = 0xffffffff;
   100171   pPrg->aColmask[1] = 0xffffffff;
   100172 
   100173   /* Allocate and populate a new Parse context to use for coding the
   100174   ** trigger sub-program.  */
   100175   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   100176   if( !pSubParse ) return 0;
   100177   memset(&sNC, 0, sizeof(sNC));
   100178   sNC.pParse = pSubParse;
   100179   pSubParse->db = db;
   100180   pSubParse->pTriggerTab = pTab;
   100181   pSubParse->pToplevel = pTop;
   100182   pSubParse->zAuthContext = pTrigger->zName;
   100183   pSubParse->eTriggerOp = pTrigger->op;
   100184   pSubParse->nQueryLoop = pParse->nQueryLoop;
   100185 
   100186   v = sqlite3GetVdbe(pSubParse);
   100187   if( v ){
   100188     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   100189       pTrigger->zName, onErrorText(orconf),
   100190       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   100191         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   100192         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   100193         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   100194       pTab->zName
   100195     ));
   100196 #ifndef SQLITE_OMIT_TRACE
   100197     sqlite3VdbeChangeP4(v, -1,
   100198       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   100199     );
   100200 #endif
   100201 
   100202     /* If one was specified, code the WHEN clause. If it evaluates to false
   100203     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   100204     ** OP_Halt inserted at the end of the program.  */
   100205     if( pTrigger->pWhen ){
   100206       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   100207       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   100208        && db->mallocFailed==0
   100209       ){
   100210         iEndTrigger = sqlite3VdbeMakeLabel(v);
   100211         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   100212       }
   100213       sqlite3ExprDelete(db, pWhen);
   100214     }
   100215 
   100216     /* Code the trigger program into the sub-vdbe. */
   100217     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   100218 
   100219     /* Insert an OP_Halt at the end of the sub-program. */
   100220     if( iEndTrigger ){
   100221       sqlite3VdbeResolveLabel(v, iEndTrigger);
   100222     }
   100223     sqlite3VdbeAddOp0(v, OP_Halt);
   100224     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   100225 
   100226     transferParseError(pParse, pSubParse);
   100227     if( db->mallocFailed==0 ){
   100228       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   100229     }
   100230     pProgram->nMem = pSubParse->nMem;
   100231     pProgram->nCsr = pSubParse->nTab;
   100232     pProgram->nOnce = pSubParse->nOnce;
   100233     pProgram->token = (void *)pTrigger;
   100234     pPrg->aColmask[0] = pSubParse->oldmask;
   100235     pPrg->aColmask[1] = pSubParse->newmask;
   100236     sqlite3VdbeDelete(v);
   100237   }
   100238 
   100239   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   100240   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   100241   sqlite3StackFree(db, pSubParse);
   100242 
   100243   return pPrg;
   100244 }
   100245 
   100246 /*
   100247 ** Return a pointer to a TriggerPrg object containing the sub-program for
   100248 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   100249 ** TriggerPrg object exists, a new object is allocated and populated before
   100250 ** being returned.
   100251 */
   100252 static TriggerPrg *getRowTrigger(
   100253   Parse *pParse,       /* Current parse context */
   100254   Trigger *pTrigger,   /* Trigger to code */
   100255   Table *pTab,         /* The table trigger pTrigger is attached to */
   100256   int orconf           /* ON CONFLICT algorithm. */
   100257 ){
   100258   Parse *pRoot = sqlite3ParseToplevel(pParse);
   100259   TriggerPrg *pPrg;
   100260 
   100261   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   100262 
   100263   /* It may be that this trigger has already been coded (or is in the
   100264   ** process of being coded). If this is the case, then an entry with
   100265   ** a matching TriggerPrg.pTrigger field will be present somewhere
   100266   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   100267   for(pPrg=pRoot->pTriggerPrg;
   100268       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   100269       pPrg=pPrg->pNext
   100270   );
   100271 
   100272   /* If an existing TriggerPrg could not be located, create a new one. */
   100273   if( !pPrg ){
   100274     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   100275   }
   100276 
   100277   return pPrg;
   100278 }
   100279 
   100280 /*
   100281 ** Generate code for the trigger program associated with trigger p on
   100282 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   100283 ** function are the same as those described in the header function for
   100284 ** sqlite3CodeRowTrigger()
   100285 */
   100286 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   100287   Parse *pParse,       /* Parse context */
   100288   Trigger *p,          /* Trigger to code */
   100289   Table *pTab,         /* The table to code triggers from */
   100290   int reg,             /* Reg array containing OLD.* and NEW.* values */
   100291   int orconf,          /* ON CONFLICT policy */
   100292   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   100293 ){
   100294   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   100295   TriggerPrg *pPrg;
   100296   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   100297   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   100298 
   100299   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   100300   ** is a pointer to the sub-vdbe containing the trigger program.  */
   100301   if( pPrg ){
   100302     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   100303 
   100304     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   100305     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   100306     VdbeComment(
   100307         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   100308 
   100309     /* Set the P5 operand of the OP_Program instruction to non-zero if
   100310     ** recursive invocation of this trigger program is disallowed. Recursive
   100311     ** invocation is disallowed if (a) the sub-program is really a trigger,
   100312     ** not a foreign key action, and (b) the flag to enable recursive triggers
   100313     ** is clear.  */
   100314     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   100315   }
   100316 }
   100317 
   100318 /*
   100319 ** This is called to code the required FOR EACH ROW triggers for an operation
   100320 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   100321 ** is given by the op paramater. The tr_tm parameter determines whether the
   100322 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   100323 ** parameter pChanges is passed the list of columns being modified.
   100324 **
   100325 ** If there are no triggers that fire at the specified time for the specified
   100326 ** operation on pTab, this function is a no-op.
   100327 **
   100328 ** The reg argument is the address of the first in an array of registers
   100329 ** that contain the values substituted for the new.* and old.* references
   100330 ** in the trigger program. If N is the number of columns in table pTab
   100331 ** (a copy of pTab->nCol), then registers are populated as follows:
   100332 **
   100333 **   Register       Contains
   100334 **   ------------------------------------------------------
   100335 **   reg+0          OLD.rowid
   100336 **   reg+1          OLD.* value of left-most column of pTab
   100337 **   ...            ...
   100338 **   reg+N          OLD.* value of right-most column of pTab
   100339 **   reg+N+1        NEW.rowid
   100340 **   reg+N+2        OLD.* value of left-most column of pTab
   100341 **   ...            ...
   100342 **   reg+N+N+1      NEW.* value of right-most column of pTab
   100343 **
   100344 ** For ON DELETE triggers, the registers containing the NEW.* values will
   100345 ** never be accessed by the trigger program, so they are not allocated or
   100346 ** populated by the caller (there is no data to populate them with anyway).
   100347 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   100348 ** are never accessed, and so are not allocated by the caller. So, for an
   100349 ** ON INSERT trigger, the value passed to this function as parameter reg
   100350 ** is not a readable register, although registers (reg+N) through
   100351 ** (reg+N+N+1) are.
   100352 **
   100353 ** Parameter orconf is the default conflict resolution algorithm for the
   100354 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   100355 ** is the instruction that control should jump to if a trigger program
   100356 ** raises an IGNORE exception.
   100357 */
   100358 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   100359   Parse *pParse,       /* Parse context */
   100360   Trigger *pTrigger,   /* List of triggers on table pTab */
   100361   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   100362   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   100363   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   100364   Table *pTab,         /* The table to code triggers from */
   100365   int reg,             /* The first in an array of registers (see above) */
   100366   int orconf,          /* ON CONFLICT policy */
   100367   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   100368 ){
   100369   Trigger *p;          /* Used to iterate through pTrigger list */
   100370 
   100371   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   100372   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   100373   assert( (op==TK_UPDATE)==(pChanges!=0) );
   100374 
   100375   for(p=pTrigger; p; p=p->pNext){
   100376 
   100377     /* Sanity checking:  The schema for the trigger and for the table are
   100378     ** always defined.  The trigger must be in the same schema as the table
   100379     ** or else it must be a TEMP trigger. */
   100380     assert( p->pSchema!=0 );
   100381     assert( p->pTabSchema!=0 );
   100382     assert( p->pSchema==p->pTabSchema
   100383          || p->pSchema==pParse->db->aDb[1].pSchema );
   100384 
   100385     /* Determine whether we should code this trigger */
   100386     if( p->op==op
   100387      && p->tr_tm==tr_tm
   100388      && checkColumnOverlap(p->pColumns, pChanges)
   100389     ){
   100390       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   100391     }
   100392   }
   100393 }
   100394 
   100395 /*
   100396 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   100397 ** This function returns a 32-bit bitmask indicating which columns of the
   100398 ** old.* or new.* tables actually are used by triggers. This information
   100399 ** may be used by the caller, for example, to avoid having to load the entire
   100400 ** old.* record into memory when executing an UPDATE or DELETE command.
   100401 **
   100402 ** Bit 0 of the returned mask is set if the left-most column of the
   100403 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   100404 ** the second leftmost column value is required, and so on. If there
   100405 ** are more than 32 columns in the table, and at least one of the columns
   100406 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   100407 **
   100408 ** It is not possible to determine if the old.rowid or new.rowid column is
   100409 ** accessed by triggers. The caller must always assume that it is.
   100410 **
   100411 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   100412 ** applies to the old.* table. If 1, the new.* table.
   100413 **
   100414 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   100415 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   100416 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   100417 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   100418 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   100419 */
   100420 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   100421   Parse *pParse,       /* Parse context */
   100422   Trigger *pTrigger,   /* List of triggers on table pTab */
   100423   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   100424   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   100425   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   100426   Table *pTab,         /* The table to code triggers from */
   100427   int orconf           /* Default ON CONFLICT policy for trigger steps */
   100428 ){
   100429   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   100430   u32 mask = 0;
   100431   Trigger *p;
   100432 
   100433   assert( isNew==1 || isNew==0 );
   100434   for(p=pTrigger; p; p=p->pNext){
   100435     if( p->op==op && (tr_tm&p->tr_tm)
   100436      && checkColumnOverlap(p->pColumns,pChanges)
   100437     ){
   100438       TriggerPrg *pPrg;
   100439       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   100440       if( pPrg ){
   100441         mask |= pPrg->aColmask[isNew];
   100442       }
   100443     }
   100444   }
   100445 
   100446   return mask;
   100447 }
   100448 
   100449 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   100450 
   100451 /************** End of trigger.c *********************************************/
   100452 /************** Begin file update.c ******************************************/
   100453 /*
   100454 ** 2001 September 15
   100455 **
   100456 ** The author disclaims copyright to this source code.  In place of
   100457 ** a legal notice, here is a blessing:
   100458 **
   100459 **    May you do good and not evil.
   100460 **    May you find forgiveness for yourself and forgive others.
   100461 **    May you share freely, never taking more than you give.
   100462 **
   100463 *************************************************************************
   100464 ** This file contains C code routines that are called by the parser
   100465 ** to handle UPDATE statements.
   100466 */
   100467 
   100468 #ifndef SQLITE_OMIT_VIRTUALTABLE
   100469 /* Forward declaration */
   100470 static void updateVirtualTable(
   100471   Parse *pParse,       /* The parsing context */
   100472   SrcList *pSrc,       /* The virtual table to be modified */
   100473   Table *pTab,         /* The virtual table */
   100474   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   100475   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   100476   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   100477   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   100478   int onError          /* ON CONFLICT strategy */
   100479 );
   100480 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   100481 
   100482 /*
   100483 ** The most recently coded instruction was an OP_Column to retrieve the
   100484 ** i-th column of table pTab. This routine sets the P4 parameter of the
   100485 ** OP_Column to the default value, if any.
   100486 **
   100487 ** The default value of a column is specified by a DEFAULT clause in the
   100488 ** column definition. This was either supplied by the user when the table
   100489 ** was created, or added later to the table definition by an ALTER TABLE
   100490 ** command. If the latter, then the row-records in the table btree on disk
   100491 ** may not contain a value for the column and the default value, taken
   100492 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   100493 ** If the former, then all row-records are guaranteed to include a value
   100494 ** for the column and the P4 value is not required.
   100495 **
   100496 ** Column definitions created by an ALTER TABLE command may only have
   100497 ** literal default values specified: a number, null or a string. (If a more
   100498 ** complicated default expression value was provided, it is evaluated
   100499 ** when the ALTER TABLE is executed and one of the literal values written
   100500 ** into the sqlite_master table.)
   100501 **
   100502 ** Therefore, the P4 parameter is only required if the default value for
   100503 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   100504 ** function is capable of transforming these types of expressions into
   100505 ** sqlite3_value objects.
   100506 **
   100507 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   100508 ** on register iReg. This is used when an equivalent integer value is
   100509 ** stored in place of an 8-byte floating point value in order to save
   100510 ** space.
   100511 */
   100512 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   100513   assert( pTab!=0 );
   100514   if( !pTab->pSelect ){
   100515     sqlite3_value *pValue;
   100516     u8 enc = ENC(sqlite3VdbeDb(v));
   100517     Column *pCol = &pTab->aCol[i];
   100518     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   100519     assert( i<pTab->nCol );
   100520     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   100521                          pCol->affinity, &pValue);
   100522     if( pValue ){
   100523       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   100524     }
   100525 #ifndef SQLITE_OMIT_FLOATING_POINT
   100526     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   100527       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   100528     }
   100529 #endif
   100530   }
   100531 }
   100532 
   100533 /*
   100534 ** Process an UPDATE statement.
   100535 **
   100536 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   100537 **          \_______/ \________/     \______/       \________________/
   100538 *            onError   pTabList      pChanges             pWhere
   100539 */
   100540 SQLITE_PRIVATE void sqlite3Update(
   100541   Parse *pParse,         /* The parser context */
   100542   SrcList *pTabList,     /* The table in which we should change things */
   100543   ExprList *pChanges,    /* Things to be changed */
   100544   Expr *pWhere,          /* The WHERE clause.  May be null */
   100545   int onError            /* How to handle constraint errors */
   100546 ){
   100547   int i, j;              /* Loop counters */
   100548   Table *pTab;           /* The table to be updated */
   100549   int addr = 0;          /* VDBE instruction address of the start of the loop */
   100550   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   100551   Vdbe *v;               /* The virtual database engine */
   100552   Index *pIdx;           /* For looping over indices */
   100553   int nIdx;              /* Number of indices that need updating */
   100554   int iCur;              /* VDBE Cursor number of pTab */
   100555   sqlite3 *db;           /* The database structure */
   100556   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   100557   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   100558                          ** an expression for the i-th column of the table.
   100559                          ** aXRef[i]==-1 if the i-th column is not changed. */
   100560   int chngRowid;         /* True if the record number is being changed */
   100561   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   100562   int openAll = 0;       /* True if all indices need to be opened */
   100563   AuthContext sContext;  /* The authorization context */
   100564   NameContext sNC;       /* The name-context to resolve expressions in */
   100565   int iDb;               /* Database containing the table being updated */
   100566   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   100567   int hasFK;             /* True if foreign key processing is required */
   100568 
   100569 #ifndef SQLITE_OMIT_TRIGGER
   100570   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   100571   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   100572   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   100573 #endif
   100574   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   100575 
   100576   /* Register Allocations */
   100577   int regRowCount = 0;   /* A count of rows changed */
   100578   int regOldRowid;       /* The old rowid */
   100579   int regNewRowid;       /* The new rowid */
   100580   int regNew;            /* Content of the NEW.* table in triggers */
   100581   int regOld = 0;        /* Content of OLD.* table in triggers */
   100582   int regRowSet = 0;     /* Rowset of rows to be updated */
   100583 
   100584   memset(&sContext, 0, sizeof(sContext));
   100585   db = pParse->db;
   100586   if( pParse->nErr || db->mallocFailed ){
   100587     goto update_cleanup;
   100588   }
   100589   assert( pTabList->nSrc==1 );
   100590 
   100591   /* Locate the table which we want to update.
   100592   */
   100593   pTab = sqlite3SrcListLookup(pParse, pTabList);
   100594   if( pTab==0 ) goto update_cleanup;
   100595   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   100596 
   100597   /* Figure out if we have any triggers and if the table being
   100598   ** updated is a view.
   100599   */
   100600 #ifndef SQLITE_OMIT_TRIGGER
   100601   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   100602   isView = pTab->pSelect!=0;
   100603   assert( pTrigger || tmask==0 );
   100604 #else
   100605 # define pTrigger 0
   100606 # define isView 0
   100607 # define tmask 0
   100608 #endif
   100609 #ifdef SQLITE_OMIT_VIEW
   100610 # undef isView
   100611 # define isView 0
   100612 #endif
   100613 
   100614   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   100615     goto update_cleanup;
   100616   }
   100617   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   100618     goto update_cleanup;
   100619   }
   100620   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
   100621   if( aXRef==0 ) goto update_cleanup;
   100622   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   100623 
   100624   /* Allocate a cursors for the main database table and for all indices.
   100625   ** The index cursors might not be used, but if they are used they
   100626   ** need to occur right after the database cursor.  So go ahead and
   100627   ** allocate enough space, just in case.
   100628   */
   100629   pTabList->a[0].iCursor = iCur = pParse->nTab++;
   100630   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100631     pParse->nTab++;
   100632   }
   100633 
   100634   /* Initialize the name-context */
   100635   memset(&sNC, 0, sizeof(sNC));
   100636   sNC.pParse = pParse;
   100637   sNC.pSrcList = pTabList;
   100638 
   100639   /* Resolve the column names in all the expressions of the
   100640   ** of the UPDATE statement.  Also find the column index
   100641   ** for each column to be updated in the pChanges array.  For each
   100642   ** column to be updated, make sure we have authorization to change
   100643   ** that column.
   100644   */
   100645   chngRowid = 0;
   100646   for(i=0; i<pChanges->nExpr; i++){
   100647     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   100648       goto update_cleanup;
   100649     }
   100650     for(j=0; j<pTab->nCol; j++){
   100651       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   100652         if( j==pTab->iPKey ){
   100653           chngRowid = 1;
   100654           pRowidExpr = pChanges->a[i].pExpr;
   100655         }
   100656         aXRef[j] = i;
   100657         break;
   100658       }
   100659     }
   100660     if( j>=pTab->nCol ){
   100661       if( sqlite3IsRowid(pChanges->a[i].zName) ){
   100662         chngRowid = 1;
   100663         pRowidExpr = pChanges->a[i].pExpr;
   100664       }else{
   100665         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   100666         pParse->checkSchema = 1;
   100667         goto update_cleanup;
   100668       }
   100669     }
   100670 #ifndef SQLITE_OMIT_AUTHORIZATION
   100671     {
   100672       int rc;
   100673       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   100674                            pTab->aCol[j].zName, db->aDb[iDb].zName);
   100675       if( rc==SQLITE_DENY ){
   100676         goto update_cleanup;
   100677       }else if( rc==SQLITE_IGNORE ){
   100678         aXRef[j] = -1;
   100679       }
   100680     }
   100681 #endif
   100682   }
   100683 
   100684   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
   100685 
   100686   /* Allocate memory for the array aRegIdx[].  There is one entry in the
   100687   ** array for each index associated with table being updated.  Fill in
   100688   ** the value with a register number for indices that are to be used
   100689   ** and with zero for unused indices.
   100690   */
   100691   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   100692   if( nIdx>0 ){
   100693     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   100694     if( aRegIdx==0 ) goto update_cleanup;
   100695   }
   100696   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   100697     int reg;
   100698     if( hasFK || chngRowid ){
   100699       reg = ++pParse->nMem;
   100700     }else{
   100701       reg = 0;
   100702       for(i=0; i<pIdx->nColumn; i++){
   100703         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   100704           reg = ++pParse->nMem;
   100705           break;
   100706         }
   100707       }
   100708     }
   100709     aRegIdx[j] = reg;
   100710   }
   100711 
   100712   /* Begin generating code. */
   100713   v = sqlite3GetVdbe(pParse);
   100714   if( v==0 ) goto update_cleanup;
   100715   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   100716   sqlite3BeginWriteOperation(pParse, 1, iDb);
   100717 
   100718 #ifndef SQLITE_OMIT_VIRTUALTABLE
   100719   /* Virtual tables must be handled separately */
   100720   if( IsVirtual(pTab) ){
   100721     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   100722                        pWhere, onError);
   100723     pWhere = 0;
   100724     pTabList = 0;
   100725     goto update_cleanup;
   100726   }
   100727 #endif
   100728 
   100729   /* Allocate required registers. */
   100730   regRowSet = ++pParse->nMem;
   100731   regOldRowid = regNewRowid = ++pParse->nMem;
   100732   if( pTrigger || hasFK ){
   100733     regOld = pParse->nMem + 1;
   100734     pParse->nMem += pTab->nCol;
   100735   }
   100736   if( chngRowid || pTrigger || hasFK ){
   100737     regNewRowid = ++pParse->nMem;
   100738   }
   100739   regNew = pParse->nMem + 1;
   100740   pParse->nMem += pTab->nCol;
   100741 
   100742   /* Start the view context. */
   100743   if( isView ){
   100744     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   100745   }
   100746 
   100747   /* If we are trying to update a view, realize that view into
   100748   ** a ephemeral table.
   100749   */
   100750 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   100751   if( isView ){
   100752     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   100753   }
   100754 #endif
   100755 
   100756   /* Resolve the column names in all the expressions in the
   100757   ** WHERE clause.
   100758   */
   100759   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   100760     goto update_cleanup;
   100761   }
   100762 
   100763   /* Begin the database scan
   100764   */
   100765   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
   100766   pWInfo = sqlite3WhereBegin(
   100767       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
   100768   );
   100769   if( pWInfo==0 ) goto update_cleanup;
   100770   okOnePass = pWInfo->okOnePass;
   100771 
   100772   /* Remember the rowid of every item to be updated.
   100773   */
   100774   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
   100775   if( !okOnePass ){
   100776     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   100777   }
   100778 
   100779   /* End the database scan loop.
   100780   */
   100781   sqlite3WhereEnd(pWInfo);
   100782 
   100783   /* Initialize the count of updated rows
   100784   */
   100785   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   100786     regRowCount = ++pParse->nMem;
   100787     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   100788   }
   100789 
   100790   if( !isView ){
   100791     /*
   100792     ** Open every index that needs updating.  Note that if any
   100793     ** index could potentially invoke a REPLACE conflict resolution
   100794     ** action, then we need to open all indices because we might need
   100795     ** to be deleting some records.
   100796     */
   100797     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
   100798     if( onError==OE_Replace ){
   100799       openAll = 1;
   100800     }else{
   100801       openAll = 0;
   100802       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   100803         if( pIdx->onError==OE_Replace ){
   100804           openAll = 1;
   100805           break;
   100806         }
   100807       }
   100808     }
   100809     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   100810       assert( aRegIdx );
   100811       if( openAll || aRegIdx[i]>0 ){
   100812         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   100813         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
   100814                        (char*)pKey, P4_KEYINFO_HANDOFF);
   100815         assert( pParse->nTab>iCur+i+1 );
   100816       }
   100817     }
   100818   }
   100819 
   100820   /* Top of the update loop */
   100821   if( okOnePass ){
   100822     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   100823     addr = sqlite3VdbeAddOp0(v, OP_Goto);
   100824     sqlite3VdbeJumpHere(v, a1);
   100825   }else{
   100826     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
   100827   }
   100828 
   100829   /* Make cursor iCur point to the record that is being updated. If
   100830   ** this record does not exist for some reason (deleted by a trigger,
   100831   ** for example, then jump to the next iteration of the RowSet loop.  */
   100832   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   100833 
   100834   /* If the record number will change, set register regNewRowid to
   100835   ** contain the new value. If the record number is not being modified,
   100836   ** then regNewRowid is the same register as regOldRowid, which is
   100837   ** already populated.  */
   100838   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
   100839   if( chngRowid ){
   100840     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   100841     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   100842   }
   100843 
   100844   /* If there are triggers on this table, populate an array of registers
   100845   ** with the required old.* column data.  */
   100846   if( hasFK || pTrigger ){
   100847     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   100848     oldmask |= sqlite3TriggerColmask(pParse,
   100849         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   100850     );
   100851     for(i=0; i<pTab->nCol; i++){
   100852       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
   100853         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
   100854       }else{
   100855         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   100856       }
   100857     }
   100858     if( chngRowid==0 ){
   100859       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   100860     }
   100861   }
   100862 
   100863   /* Populate the array of registers beginning at regNew with the new
   100864   ** row data. This array is used to check constaints, create the new
   100865   ** table and index records, and as the values for any new.* references
   100866   ** made by triggers.
   100867   **
   100868   ** If there are one or more BEFORE triggers, then do not populate the
   100869   ** registers associated with columns that are (a) not modified by
   100870   ** this UPDATE statement and (b) not accessed by new.* references. The
   100871   ** values for registers not modified by the UPDATE must be reloaded from
   100872   ** the database after the BEFORE triggers are fired anyway (as the trigger
   100873   ** may have modified them). So not loading those that are not going to
   100874   ** be used eliminates some redundant opcodes.
   100875   */
   100876   newmask = sqlite3TriggerColmask(
   100877       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   100878   );
   100879   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
   100880   for(i=0; i<pTab->nCol; i++){
   100881     if( i==pTab->iPKey ){
   100882       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
   100883     }else{
   100884       j = aXRef[i];
   100885       if( j>=0 ){
   100886         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   100887       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
   100888         /* This branch loads the value of a column that will not be changed
   100889         ** into a register. This is done if there are no BEFORE triggers, or
   100890         ** if there are one or more BEFORE triggers that use this value via
   100891         ** a new.* reference in a trigger program.
   100892         */
   100893         testcase( i==31 );
   100894         testcase( i==32 );
   100895         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   100896         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   100897       }
   100898     }
   100899   }
   100900 
   100901   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   100902   ** verified. One could argue that this is wrong.
   100903   */
   100904   if( tmask&TRIGGER_BEFORE ){
   100905     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
   100906     sqlite3TableAffinityStr(v, pTab);
   100907     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   100908         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
   100909 
   100910     /* The row-trigger may have deleted the row being updated. In this
   100911     ** case, jump to the next row. No updates or AFTER triggers are
   100912     ** required. This behaviour - what happens when the row being updated
   100913     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   100914     ** documentation.
   100915     */
   100916     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   100917 
   100918     /* If it did not delete it, the row-trigger may still have modified
   100919     ** some of the columns of the row being updated. Load the values for
   100920     ** all columns not modified by the update statement into their
   100921     ** registers in case this has happened.
   100922     */
   100923     for(i=0; i<pTab->nCol; i++){
   100924       if( aXRef[i]<0 && i!=pTab->iPKey ){
   100925         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   100926         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   100927       }
   100928     }
   100929   }
   100930 
   100931   if( !isView ){
   100932     int j1;                       /* Address of jump instruction */
   100933 
   100934     /* Do constraint checks. */
   100935     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
   100936         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
   100937 
   100938     /* Do FK constraint checks. */
   100939     if( hasFK ){
   100940       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
   100941     }
   100942 
   100943     /* Delete the index entries associated with the current record.  */
   100944     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   100945     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
   100946 
   100947     /* If changing the record number, delete the old record.  */
   100948     if( hasFK || chngRowid ){
   100949       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
   100950     }
   100951     sqlite3VdbeJumpHere(v, j1);
   100952 
   100953     if( hasFK ){
   100954       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
   100955     }
   100956 
   100957     /* Insert the new index entries and the new record. */
   100958     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
   100959 
   100960     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   100961     ** handle rows (possibly in other tables) that refer via a foreign key
   100962     ** to the row just updated. */
   100963     if( hasFK ){
   100964       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
   100965     }
   100966   }
   100967 
   100968   /* Increment the row counter
   100969   */
   100970   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   100971     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   100972   }
   100973 
   100974   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   100975       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
   100976 
   100977   /* Repeat the above with the next record to be updated, until
   100978   ** all record selected by the WHERE clause have been updated.
   100979   */
   100980   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   100981   sqlite3VdbeJumpHere(v, addr);
   100982 
   100983   /* Close all tables */
   100984   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   100985     assert( aRegIdx );
   100986     if( openAll || aRegIdx[i]>0 ){
   100987       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
   100988     }
   100989   }
   100990   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
   100991 
   100992   /* Update the sqlite_sequence table by storing the content of the
   100993   ** maximum rowid counter values recorded while inserting into
   100994   ** autoincrement tables.
   100995   */
   100996   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   100997     sqlite3AutoincrementEnd(pParse);
   100998   }
   100999 
   101000   /*
   101001   ** Return the number of rows that were changed. If this routine is
   101002   ** generating code because of a call to sqlite3NestedParse(), do not
   101003   ** invoke the callback function.
   101004   */
   101005   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   101006     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   101007     sqlite3VdbeSetNumCols(v, 1);
   101008     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   101009   }
   101010 
   101011 update_cleanup:
   101012   sqlite3AuthContextPop(&sContext);
   101013   sqlite3DbFree(db, aRegIdx);
   101014   sqlite3DbFree(db, aXRef);
   101015   sqlite3SrcListDelete(db, pTabList);
   101016   sqlite3ExprListDelete(db, pChanges);
   101017   sqlite3ExprDelete(db, pWhere);
   101018   return;
   101019 }
   101020 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   101021 ** thely may interfere with compilation of other functions in this file
   101022 ** (or in another file, if this file becomes part of the amalgamation).  */
   101023 #ifdef isView
   101024  #undef isView
   101025 #endif
   101026 #ifdef pTrigger
   101027  #undef pTrigger
   101028 #endif
   101029 
   101030 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101031 /*
   101032 ** Generate code for an UPDATE of a virtual table.
   101033 **
   101034 ** The strategy is that we create an ephemerial table that contains
   101035 ** for each row to be changed:
   101036 **
   101037 **   (A)  The original rowid of that row.
   101038 **   (B)  The revised rowid for the row. (note1)
   101039 **   (C)  The content of every column in the row.
   101040 **
   101041 ** Then we loop over this ephemeral table and for each row in
   101042 ** the ephermeral table call VUpdate.
   101043 **
   101044 ** When finished, drop the ephemeral table.
   101045 **
   101046 ** (note1) Actually, if we know in advance that (A) is always the same
   101047 ** as (B) we only store (A), then duplicate (A) when pulling
   101048 ** it out of the ephemeral table before calling VUpdate.
   101049 */
   101050 static void updateVirtualTable(
   101051   Parse *pParse,       /* The parsing context */
   101052   SrcList *pSrc,       /* The virtual table to be modified */
   101053   Table *pTab,         /* The virtual table */
   101054   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   101055   Expr *pRowid,        /* Expression used to recompute the rowid */
   101056   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   101057   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
   101058   int onError          /* ON CONFLICT strategy */
   101059 ){
   101060   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   101061   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   101062   Select *pSelect = 0;      /* The SELECT statement */
   101063   Expr *pExpr;              /* Temporary expression */
   101064   int ephemTab;             /* Table holding the result of the SELECT */
   101065   int i;                    /* Loop counter */
   101066   int addr;                 /* Address of top of loop */
   101067   int iReg;                 /* First register in set passed to OP_VUpdate */
   101068   sqlite3 *db = pParse->db; /* Database connection */
   101069   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   101070   SelectDest dest;
   101071 
   101072   /* Construct the SELECT statement that will find the new values for
   101073   ** all updated rows.
   101074   */
   101075   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   101076   if( pRowid ){
   101077     pEList = sqlite3ExprListAppend(pParse, pEList,
   101078                                    sqlite3ExprDup(db, pRowid, 0));
   101079   }
   101080   assert( pTab->iPKey<0 );
   101081   for(i=0; i<pTab->nCol; i++){
   101082     if( aXRef[i]>=0 ){
   101083       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   101084     }else{
   101085       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   101086     }
   101087     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   101088   }
   101089   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   101090 
   101091   /* Create the ephemeral table into which the update results will
   101092   ** be stored.
   101093   */
   101094   assert( v );
   101095   ephemTab = pParse->nTab++;
   101096   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   101097   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   101098 
   101099   /* fill the ephemeral table
   101100   */
   101101   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   101102   sqlite3Select(pParse, pSelect, &dest);
   101103 
   101104   /* Generate code to scan the ephemeral table and call VUpdate. */
   101105   iReg = ++pParse->nMem;
   101106   pParse->nMem += pTab->nCol+1;
   101107   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
   101108   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   101109   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   101110   for(i=0; i<pTab->nCol; i++){
   101111     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   101112   }
   101113   sqlite3VtabMakeWritable(pParse, pTab);
   101114   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   101115   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   101116   sqlite3MayAbort(pParse);
   101117   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
   101118   sqlite3VdbeJumpHere(v, addr);
   101119   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   101120 
   101121   /* Cleanup */
   101122   sqlite3SelectDelete(db, pSelect);
   101123 }
   101124 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   101125 
   101126 /************** End of update.c **********************************************/
   101127 /************** Begin file vacuum.c ******************************************/
   101128 /*
   101129 ** 2003 April 6
   101130 **
   101131 ** The author disclaims copyright to this source code.  In place of
   101132 ** a legal notice, here is a blessing:
   101133 **
   101134 **    May you do good and not evil.
   101135 **    May you find forgiveness for yourself and forgive others.
   101136 **    May you share freely, never taking more than you give.
   101137 **
   101138 *************************************************************************
   101139 ** This file contains code used to implement the VACUUM command.
   101140 **
   101141 ** Most of the code in this file may be omitted by defining the
   101142 ** SQLITE_OMIT_VACUUM macro.
   101143 */
   101144 
   101145 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   101146 /*
   101147 ** Finalize a prepared statement.  If there was an error, store the
   101148 ** text of the error message in *pzErrMsg.  Return the result code.
   101149 */
   101150 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   101151   int rc;
   101152   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   101153   if( rc ){
   101154     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   101155   }
   101156   return rc;
   101157 }
   101158 
   101159 /*
   101160 ** Execute zSql on database db. Return an error code.
   101161 */
   101162 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   101163   sqlite3_stmt *pStmt;
   101164   VVA_ONLY( int rc; )
   101165   if( !zSql ){
   101166     return SQLITE_NOMEM;
   101167   }
   101168   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   101169     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   101170     return sqlite3_errcode(db);
   101171   }
   101172   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   101173   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
   101174   return vacuumFinalize(db, pStmt, pzErrMsg);
   101175 }
   101176 
   101177 /*
   101178 ** Execute zSql on database db. The statement returns exactly
   101179 ** one column. Execute this as SQL on the same database.
   101180 */
   101181 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   101182   sqlite3_stmt *pStmt;
   101183   int rc;
   101184 
   101185   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   101186   if( rc!=SQLITE_OK ) return rc;
   101187 
   101188   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   101189     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   101190     if( rc!=SQLITE_OK ){
   101191       vacuumFinalize(db, pStmt, pzErrMsg);
   101192       return rc;
   101193     }
   101194   }
   101195 
   101196   return vacuumFinalize(db, pStmt, pzErrMsg);
   101197 }
   101198 
   101199 /*
   101200 ** The non-standard VACUUM command is used to clean up the database,
   101201 ** collapse free space, etc.  It is modelled after the VACUUM command
   101202 ** in PostgreSQL.
   101203 **
   101204 ** In version 1.0.x of SQLite, the VACUUM command would call
   101205 ** gdbm_reorganize() on all the database tables.  But beginning
   101206 ** with 2.0.0, SQLite no longer uses GDBM so this command has
   101207 ** become a no-op.
   101208 */
   101209 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   101210   Vdbe *v = sqlite3GetVdbe(pParse);
   101211   if( v ){
   101212     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   101213   }
   101214   return;
   101215 }
   101216 
   101217 /*
   101218 ** This routine implements the OP_Vacuum opcode of the VDBE.
   101219 */
   101220 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   101221   int rc = SQLITE_OK;     /* Return code from service routines */
   101222   Btree *pMain;           /* The database being vacuumed */
   101223   Btree *pTemp;           /* The temporary database we vacuum into */
   101224   char *zSql = 0;         /* SQL statements */
   101225   int saved_flags;        /* Saved value of the db->flags */
   101226   int saved_nChange;      /* Saved value of db->nChange */
   101227   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   101228   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   101229   Db *pDb = 0;            /* Database to detach at end of vacuum */
   101230   int isMemDb;            /* True if vacuuming a :memory: database */
   101231   int nRes;               /* Bytes of reserved space at the end of each page */
   101232   int nDb;                /* Number of attached databases */
   101233 
   101234   if( !db->autoCommit ){
   101235     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   101236     return SQLITE_ERROR;
   101237   }
   101238   if( db->activeVdbeCnt>1 ){
   101239     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   101240     return SQLITE_ERROR;
   101241   }
   101242 
   101243   /* Save the current value of the database flags so that it can be
   101244   ** restored before returning. Then set the writable-schema flag, and
   101245   ** disable CHECK and foreign key constraints.  */
   101246   saved_flags = db->flags;
   101247   saved_nChange = db->nChange;
   101248   saved_nTotalChange = db->nTotalChange;
   101249   saved_xTrace = db->xTrace;
   101250   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   101251   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
   101252   db->xTrace = 0;
   101253 
   101254   pMain = db->aDb[0].pBt;
   101255   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   101256 
   101257   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   101258   ** can be set to 'off' for this file, as it is not recovered if a crash
   101259   ** occurs anyway. The integrity of the database is maintained by a
   101260   ** (possibly synchronous) transaction opened on the main database before
   101261   ** sqlite3BtreeCopyFile() is called.
   101262   **
   101263   ** An optimisation would be to use a non-journaled pager.
   101264   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   101265   ** that actually made the VACUUM run slower.  Very little journalling
   101266   ** actually occurs when doing a vacuum since the vacuum_db is initially
   101267   ** empty.  Only the journal header is written.  Apparently it takes more
   101268   ** time to parse and run the PRAGMA to turn journalling off than it does
   101269   ** to write the journal header file.
   101270   */
   101271   nDb = db->nDb;
   101272   if( sqlite3TempInMemory(db) ){
   101273     zSql = "ATTACH ':memory:' AS vacuum_db;";
   101274   }else{
   101275     zSql = "ATTACH '' AS vacuum_db;";
   101276   }
   101277   rc = execSql(db, pzErrMsg, zSql);
   101278   if( db->nDb>nDb ){
   101279     pDb = &db->aDb[db->nDb-1];
   101280     assert( strcmp(pDb->zName,"vacuum_db")==0 );
   101281   }
   101282   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101283   pTemp = db->aDb[db->nDb-1].pBt;
   101284 
   101285   /* The call to execSql() to attach the temp database has left the file
   101286   ** locked (as there was more than one active statement when the transaction
   101287   ** to read the schema was concluded. Unlock it here so that this doesn't
   101288   ** cause problems for the call to BtreeSetPageSize() below.  */
   101289   sqlite3BtreeCommit(pTemp);
   101290 
   101291   nRes = sqlite3BtreeGetReserve(pMain);
   101292 
   101293   /* A VACUUM cannot change the pagesize of an encrypted database. */
   101294 #ifdef SQLITE_HAS_CODEC
   101295   if( db->nextPagesize ){
   101296     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   101297     int nKey;
   101298     char *zKey;
   101299     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   101300     if( nKey ) db->nextPagesize = 0;
   101301   }
   101302 #endif
   101303 
   101304   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   101305   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101306 
   101307   /* Begin a transaction and take an exclusive lock on the main database
   101308   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
   101309   ** to ensure that we do not try to change the page-size on a WAL database.
   101310   */
   101311   rc = execSql(db, pzErrMsg, "BEGIN;");
   101312   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101313   rc = sqlite3BtreeBeginTrans(pMain, 2);
   101314   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101315 
   101316   /* Do not attempt to change the page size for a WAL database */
   101317   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   101318                                                ==PAGER_JOURNALMODE_WAL ){
   101319     db->nextPagesize = 0;
   101320   }
   101321 
   101322   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   101323    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   101324    || NEVER(db->mallocFailed)
   101325   ){
   101326     rc = SQLITE_NOMEM;
   101327     goto end_of_vacuum;
   101328   }
   101329 
   101330 #ifndef SQLITE_OMIT_AUTOVACUUM
   101331   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   101332                                            sqlite3BtreeGetAutoVacuum(pMain));
   101333 #endif
   101334 
   101335   /* Query the schema of the main database. Create a mirror schema
   101336   ** in the temporary database.
   101337   */
   101338   rc = execExecSql(db, pzErrMsg,
   101339       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   101340       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   101341       "   AND rootpage>0"
   101342   );
   101343   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101344   rc = execExecSql(db, pzErrMsg,
   101345       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   101346       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   101347   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101348   rc = execExecSql(db, pzErrMsg,
   101349       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   101350       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   101351   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101352 
   101353   /* Loop through the tables in the main database. For each, do
   101354   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   101355   ** the contents to the temporary database.
   101356   */
   101357   rc = execExecSql(db, pzErrMsg,
   101358       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   101359       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   101360       "FROM main.sqlite_master "
   101361       "WHERE type = 'table' AND name!='sqlite_sequence' "
   101362       "  AND rootpage>0"
   101363   );
   101364   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101365 
   101366   /* Copy over the sequence table
   101367   */
   101368   rc = execExecSql(db, pzErrMsg,
   101369       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   101370       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   101371   );
   101372   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101373   rc = execExecSql(db, pzErrMsg,
   101374       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   101375       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   101376       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   101377   );
   101378   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101379 
   101380 
   101381   /* Copy the triggers, views, and virtual tables from the main database
   101382   ** over to the temporary database.  None of these objects has any
   101383   ** associated storage, so all we have to do is copy their entries
   101384   ** from the SQLITE_MASTER table.
   101385   */
   101386   rc = execSql(db, pzErrMsg,
   101387       "INSERT INTO vacuum_db.sqlite_master "
   101388       "  SELECT type, name, tbl_name, rootpage, sql"
   101389       "    FROM main.sqlite_master"
   101390       "   WHERE type='view' OR type='trigger'"
   101391       "      OR (type='table' AND rootpage=0)"
   101392   );
   101393   if( rc ) goto end_of_vacuum;
   101394 
   101395   /* At this point, there is a write transaction open on both the
   101396   ** vacuum database and the main database. Assuming no error occurs,
   101397   ** both transactions are closed by this block - the main database
   101398   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
   101399   ** call to sqlite3BtreeCommit().
   101400   */
   101401   {
   101402     u32 meta;
   101403     int i;
   101404 
   101405     /* This array determines which meta meta values are preserved in the
   101406     ** vacuum.  Even entries are the meta value number and odd entries
   101407     ** are an increment to apply to the meta value after the vacuum.
   101408     ** The increment is used to increase the schema cookie so that other
   101409     ** connections to the same database will know to reread the schema.
   101410     */
   101411     static const unsigned char aCopy[] = {
   101412        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   101413        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   101414        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   101415        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   101416     };
   101417 
   101418     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   101419     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   101420 
   101421     /* Copy Btree meta values */
   101422     for(i=0; i<ArraySize(aCopy); i+=2){
   101423       /* GetMeta() and UpdateMeta() cannot fail in this context because
   101424       ** we already have page 1 loaded into cache and marked dirty. */
   101425       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   101426       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   101427       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   101428     }
   101429 
   101430     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   101431     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101432     rc = sqlite3BtreeCommit(pTemp);
   101433     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   101434 #ifndef SQLITE_OMIT_AUTOVACUUM
   101435     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   101436 #endif
   101437   }
   101438 
   101439   assert( rc==SQLITE_OK );
   101440   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   101441 
   101442 end_of_vacuum:
   101443   /* Restore the original value of db->flags */
   101444   db->flags = saved_flags;
   101445   db->nChange = saved_nChange;
   101446   db->nTotalChange = saved_nTotalChange;
   101447   db->xTrace = saved_xTrace;
   101448   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   101449 
   101450   /* Currently there is an SQL level transaction open on the vacuum
   101451   ** database. No locks are held on any other files (since the main file
   101452   ** was committed at the btree level). So it safe to end the transaction
   101453   ** by manually setting the autoCommit flag to true and detaching the
   101454   ** vacuum database. The vacuum_db journal file is deleted when the pager
   101455   ** is closed by the DETACH.
   101456   */
   101457   db->autoCommit = 1;
   101458 
   101459   if( pDb ){
   101460     sqlite3BtreeClose(pDb->pBt);
   101461     pDb->pBt = 0;
   101462     pDb->pSchema = 0;
   101463   }
   101464 
   101465   /* This both clears the schemas and reduces the size of the db->aDb[]
   101466   ** array. */
   101467   sqlite3ResetInternalSchema(db, -1);
   101468 
   101469   return rc;
   101470 }
   101471 
   101472 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   101473 
   101474 /************** End of vacuum.c **********************************************/
   101475 /************** Begin file vtab.c ********************************************/
   101476 /*
   101477 ** 2006 June 10
   101478 **
   101479 ** The author disclaims copyright to this source code.  In place of
   101480 ** a legal notice, here is a blessing:
   101481 **
   101482 **    May you do good and not evil.
   101483 **    May you find forgiveness for yourself and forgive others.
   101484 **    May you share freely, never taking more than you give.
   101485 **
   101486 *************************************************************************
   101487 ** This file contains code used to help implement virtual tables.
   101488 */
   101489 #ifndef SQLITE_OMIT_VIRTUALTABLE
   101490 
   101491 /*
   101492 ** Before a virtual table xCreate() or xConnect() method is invoked, the
   101493 ** sqlite3.pVtabCtx member variable is set to point to an instance of
   101494 ** this struct allocated on the stack. It is used by the implementation of
   101495 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
   101496 ** are invoked only from within xCreate and xConnect methods.
   101497 */
   101498 struct VtabCtx {
   101499   Table *pTab;
   101500   VTable *pVTable;
   101501 };
   101502 
   101503 /*
   101504 ** The actual function that does the work of creating a new module.
   101505 ** This function implements the sqlite3_create_module() and
   101506 ** sqlite3_create_module_v2() interfaces.
   101507 */
   101508 static int createModule(
   101509   sqlite3 *db,                    /* Database in which module is registered */
   101510   const char *zName,              /* Name assigned to this module */
   101511   const sqlite3_module *pModule,  /* The definition of the module */
   101512   void *pAux,                     /* Context pointer for xCreate/xConnect */
   101513   void (*xDestroy)(void *)        /* Module destructor function */
   101514 ){
   101515   int rc, nName;
   101516   Module *pMod;
   101517 
   101518   sqlite3_mutex_enter(db->mutex);
   101519   nName = sqlite3Strlen30(zName);
   101520   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   101521   if( pMod ){
   101522     Module *pDel;
   101523     char *zCopy = (char *)(&pMod[1]);
   101524     memcpy(zCopy, zName, nName+1);
   101525     pMod->zName = zCopy;
   101526     pMod->pModule = pModule;
   101527     pMod->pAux = pAux;
   101528     pMod->xDestroy = xDestroy;
   101529     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
   101530     if( pDel && pDel->xDestroy ){
   101531       sqlite3ResetInternalSchema(db, -1);
   101532       pDel->xDestroy(pDel->pAux);
   101533     }
   101534     sqlite3DbFree(db, pDel);
   101535     if( pDel==pMod ){
   101536       db->mallocFailed = 1;
   101537     }
   101538   }else if( xDestroy ){
   101539     xDestroy(pAux);
   101540   }
   101541   rc = sqlite3ApiExit(db, SQLITE_OK);
   101542   sqlite3_mutex_leave(db->mutex);
   101543   return rc;
   101544 }
   101545 
   101546 
   101547 /*
   101548 ** External API function used to create a new virtual-table module.
   101549 */
   101550 SQLITE_API int sqlite3_create_module(
   101551   sqlite3 *db,                    /* Database in which module is registered */
   101552   const char *zName,              /* Name assigned to this module */
   101553   const sqlite3_module *pModule,  /* The definition of the module */
   101554   void *pAux                      /* Context pointer for xCreate/xConnect */
   101555 ){
   101556   return createModule(db, zName, pModule, pAux, 0);
   101557 }
   101558 
   101559 /*
   101560 ** External API function used to create a new virtual-table module.
   101561 */
   101562 SQLITE_API int sqlite3_create_module_v2(
   101563   sqlite3 *db,                    /* Database in which module is registered */
   101564   const char *zName,              /* Name assigned to this module */
   101565   const sqlite3_module *pModule,  /* The definition of the module */
   101566   void *pAux,                     /* Context pointer for xCreate/xConnect */
   101567   void (*xDestroy)(void *)        /* Module destructor function */
   101568 ){
   101569   return createModule(db, zName, pModule, pAux, xDestroy);
   101570 }
   101571 
   101572 /*
   101573 ** Lock the virtual table so that it cannot be disconnected.
   101574 ** Locks nest.  Every lock should have a corresponding unlock.
   101575 ** If an unlock is omitted, resources leaks will occur.
   101576 **
   101577 ** If a disconnect is attempted while a virtual table is locked,
   101578 ** the disconnect is deferred until all locks have been removed.
   101579 */
   101580 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   101581   pVTab->nRef++;
   101582 }
   101583 
   101584 
   101585 /*
   101586 ** pTab is a pointer to a Table structure representing a virtual-table.
   101587 ** Return a pointer to the VTable object used by connection db to access
   101588 ** this virtual-table, if one has been created, or NULL otherwise.
   101589 */
   101590 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   101591   VTable *pVtab;
   101592   assert( IsVirtual(pTab) );
   101593   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   101594   return pVtab;
   101595 }
   101596 
   101597 /*
   101598 ** Decrement the ref-count on a virtual table object. When the ref-count
   101599 ** reaches zero, call the xDisconnect() method to delete the object.
   101600 */
   101601 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   101602   sqlite3 *db = pVTab->db;
   101603 
   101604   assert( db );
   101605   assert( pVTab->nRef>0 );
   101606   assert( sqlite3SafetyCheckOk(db) );
   101607 
   101608   pVTab->nRef--;
   101609   if( pVTab->nRef==0 ){
   101610     sqlite3_vtab *p = pVTab->pVtab;
   101611     if( p ){
   101612       p->pModule->xDisconnect(p);
   101613     }
   101614     sqlite3DbFree(db, pVTab);
   101615   }
   101616 }
   101617 
   101618 /*
   101619 ** Table p is a virtual table. This function moves all elements in the
   101620 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   101621 ** database connections to be disconnected at the next opportunity.
   101622 ** Except, if argument db is not NULL, then the entry associated with
   101623 ** connection db is left in the p->pVTable list.
   101624 */
   101625 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   101626   VTable *pRet = 0;
   101627   VTable *pVTable = p->pVTable;
   101628   p->pVTable = 0;
   101629 
   101630   /* Assert that the mutex (if any) associated with the BtShared database
   101631   ** that contains table p is held by the caller. See header comments
   101632   ** above function sqlite3VtabUnlockList() for an explanation of why
   101633   ** this makes it safe to access the sqlite3.pDisconnect list of any
   101634   ** database connection that may have an entry in the p->pVTable list.
   101635   */
   101636   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
   101637 
   101638   while( pVTable ){
   101639     sqlite3 *db2 = pVTable->db;
   101640     VTable *pNext = pVTable->pNext;
   101641     assert( db2 );
   101642     if( db2==db ){
   101643       pRet = pVTable;
   101644       p->pVTable = pRet;
   101645       pRet->pNext = 0;
   101646     }else{
   101647       pVTable->pNext = db2->pDisconnect;
   101648       db2->pDisconnect = pVTable;
   101649     }
   101650     pVTable = pNext;
   101651   }
   101652 
   101653   assert( !db || pRet );
   101654   return pRet;
   101655 }
   101656 
   101657 
   101658 /*
   101659 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   101660 **
   101661 ** This function may only be called when the mutexes associated with all
   101662 ** shared b-tree databases opened using connection db are held by the
   101663 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   101664 ** sqlite3.pDisconnect list is accessed only as follows:
   101665 **
   101666 **   1) By this function. In this case, all BtShared mutexes and the mutex
   101667 **      associated with the database handle itself must be held.
   101668 **
   101669 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   101670 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   101671 **      associated with the database the virtual table is stored in is held
   101672 **      or, if the virtual table is stored in a non-sharable database, then
   101673 **      the database handle mutex is held.
   101674 **
   101675 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   101676 ** by multiple threads. It is thread-safe.
   101677 */
   101678 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   101679   VTable *p = db->pDisconnect;
   101680   db->pDisconnect = 0;
   101681 
   101682   assert( sqlite3BtreeHoldsAllMutexes(db) );
   101683   assert( sqlite3_mutex_held(db->mutex) );
   101684 
   101685   if( p ){
   101686     sqlite3ExpirePreparedStatements(db);
   101687     do {
   101688       VTable *pNext = p->pNext;
   101689       sqlite3VtabUnlock(p);
   101690       p = pNext;
   101691     }while( p );
   101692   }
   101693 }
   101694 
   101695 /*
   101696 ** Clear any and all virtual-table information from the Table record.
   101697 ** This routine is called, for example, just before deleting the Table
   101698 ** record.
   101699 **
   101700 ** Since it is a virtual-table, the Table structure contains a pointer
   101701 ** to the head of a linked list of VTable structures. Each VTable
   101702 ** structure is associated with a single sqlite3* user of the schema.
   101703 ** The reference count of the VTable structure associated with database
   101704 ** connection db is decremented immediately (which may lead to the
   101705 ** structure being xDisconnected and free). Any other VTable structures
   101706 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   101707 ** database connection.
   101708 */
   101709 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   101710   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   101711   if( p->azModuleArg ){
   101712     int i;
   101713     for(i=0; i<p->nModuleArg; i++){
   101714       sqlite3DbFree(db, p->azModuleArg[i]);
   101715     }
   101716     sqlite3DbFree(db, p->azModuleArg);
   101717   }
   101718 }
   101719 
   101720 /*
   101721 ** Add a new module argument to pTable->azModuleArg[].
   101722 ** The string is not copied - the pointer is stored.  The
   101723 ** string will be freed automatically when the table is
   101724 ** deleted.
   101725 */
   101726 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   101727   int i = pTable->nModuleArg++;
   101728   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   101729   char **azModuleArg;
   101730   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   101731   if( azModuleArg==0 ){
   101732     int j;
   101733     for(j=0; j<i; j++){
   101734       sqlite3DbFree(db, pTable->azModuleArg[j]);
   101735     }
   101736     sqlite3DbFree(db, zArg);
   101737     sqlite3DbFree(db, pTable->azModuleArg);
   101738     pTable->nModuleArg = 0;
   101739   }else{
   101740     azModuleArg[i] = zArg;
   101741     azModuleArg[i+1] = 0;
   101742   }
   101743   pTable->azModuleArg = azModuleArg;
   101744 }
   101745 
   101746 /*
   101747 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   101748 ** statement.  The module name has been parsed, but the optional list
   101749 ** of parameters that follow the module name are still pending.
   101750 */
   101751 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   101752   Parse *pParse,        /* Parsing context */
   101753   Token *pName1,        /* Name of new table, or database name */
   101754   Token *pName2,        /* Name of new table or NULL */
   101755   Token *pModuleName,   /* Name of the module for the virtual table */
   101756   int ifNotExists       /* No error if the table already exists */
   101757 ){
   101758   int iDb;              /* The database the table is being created in */
   101759   Table *pTable;        /* The new virtual table */
   101760   sqlite3 *db;          /* Database connection */
   101761 
   101762   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
   101763   pTable = pParse->pNewTable;
   101764   if( pTable==0 ) return;
   101765   assert( 0==pTable->pIndex );
   101766 
   101767   db = pParse->db;
   101768   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   101769   assert( iDb>=0 );
   101770 
   101771   pTable->tabFlags |= TF_Virtual;
   101772   pTable->nModuleArg = 0;
   101773   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   101774   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
   101775   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   101776   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   101777 
   101778 #ifndef SQLITE_OMIT_AUTHORIZATION
   101779   /* Creating a virtual table invokes the authorization callback twice.
   101780   ** The first invocation, to obtain permission to INSERT a row into the
   101781   ** sqlite_master table, has already been made by sqlite3StartTable().
   101782   ** The second call, to obtain permission to create the table, is made now.
   101783   */
   101784   if( pTable->azModuleArg ){
   101785     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   101786             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   101787   }
   101788 #endif
   101789 }
   101790 
   101791 /*
   101792 ** This routine takes the module argument that has been accumulating
   101793 ** in pParse->zArg[] and appends it to the list of arguments on the
   101794 ** virtual table currently under construction in pParse->pTable.
   101795 */
   101796 static void addArgumentToVtab(Parse *pParse){
   101797   if( pParse->sArg.z && pParse->pNewTable ){
   101798     const char *z = (const char*)pParse->sArg.z;
   101799     int n = pParse->sArg.n;
   101800     sqlite3 *db = pParse->db;
   101801     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   101802   }
   101803 }
   101804 
   101805 /*
   101806 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   101807 ** has been completely parsed.
   101808 */
   101809 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   101810   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   101811   sqlite3 *db = pParse->db;         /* The database connection */
   101812 
   101813   if( pTab==0 ) return;
   101814   addArgumentToVtab(pParse);
   101815   pParse->sArg.z = 0;
   101816   if( pTab->nModuleArg<1 ) return;
   101817 
   101818   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   101819   ** first time (in other words if the virtual table is actually being
   101820   ** created now instead of just being read out of sqlite_master) then
   101821   ** do additional initialization work and store the statement text
   101822   ** in the sqlite_master table.
   101823   */
   101824   if( !db->init.busy ){
   101825     char *zStmt;
   101826     char *zWhere;
   101827     int iDb;
   101828     Vdbe *v;
   101829 
   101830     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   101831     if( pEnd ){
   101832       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   101833     }
   101834     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   101835 
   101836     /* A slot for the record has already been allocated in the
   101837     ** SQLITE_MASTER table.  We just need to update that slot with all
   101838     ** the information we've collected.
   101839     **
   101840     ** The VM register number pParse->regRowid holds the rowid of an
   101841     ** entry in the sqlite_master table tht was created for this vtab
   101842     ** by sqlite3StartTable().
   101843     */
   101844     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   101845     sqlite3NestedParse(pParse,
   101846       "UPDATE %Q.%s "
   101847          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   101848        "WHERE rowid=#%d",
   101849       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   101850       pTab->zName,
   101851       pTab->zName,
   101852       zStmt,
   101853       pParse->regRowid
   101854     );
   101855     sqlite3DbFree(db, zStmt);
   101856     v = sqlite3GetVdbe(pParse);
   101857     sqlite3ChangeCookie(pParse, iDb);
   101858 
   101859     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   101860     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   101861     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
   101862     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   101863                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   101864   }
   101865 
   101866   /* If we are rereading the sqlite_master table create the in-memory
   101867   ** record of the table. The xConnect() method is not called until
   101868   ** the first time the virtual table is used in an SQL statement. This
   101869   ** allows a schema that contains virtual tables to be loaded before
   101870   ** the required virtual table implementations are registered.  */
   101871   else {
   101872     Table *pOld;
   101873     Schema *pSchema = pTab->pSchema;
   101874     const char *zName = pTab->zName;
   101875     int nName = sqlite3Strlen30(zName);
   101876     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   101877     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   101878     if( pOld ){
   101879       db->mallocFailed = 1;
   101880       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   101881       return;
   101882     }
   101883     pParse->pNewTable = 0;
   101884   }
   101885 }
   101886 
   101887 /*
   101888 ** The parser calls this routine when it sees the first token
   101889 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   101890 */
   101891 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   101892   addArgumentToVtab(pParse);
   101893   pParse->sArg.z = 0;
   101894   pParse->sArg.n = 0;
   101895 }
   101896 
   101897 /*
   101898 ** The parser calls this routine for each token after the first token
   101899 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   101900 */
   101901 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   101902   Token *pArg = &pParse->sArg;
   101903   if( pArg->z==0 ){
   101904     pArg->z = p->z;
   101905     pArg->n = p->n;
   101906   }else{
   101907     assert(pArg->z < p->z);
   101908     pArg->n = (int)(&p->z[p->n] - pArg->z);
   101909   }
   101910 }
   101911 
   101912 /*
   101913 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   101914 ** pointer to the function to invoke is passed as the fourth parameter
   101915 ** to this procedure.
   101916 */
   101917 static int vtabCallConstructor(
   101918   sqlite3 *db,
   101919   Table *pTab,
   101920   Module *pMod,
   101921   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   101922   char **pzErr
   101923 ){
   101924   VtabCtx sCtx;
   101925   VTable *pVTable;
   101926   int rc;
   101927   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   101928   int nArg = pTab->nModuleArg;
   101929   char *zErr = 0;
   101930   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   101931 
   101932   if( !zModuleName ){
   101933     return SQLITE_NOMEM;
   101934   }
   101935 
   101936   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   101937   if( !pVTable ){
   101938     sqlite3DbFree(db, zModuleName);
   101939     return SQLITE_NOMEM;
   101940   }
   101941   pVTable->db = db;
   101942   pVTable->pMod = pMod;
   101943 
   101944   /* Invoke the virtual table constructor */
   101945   assert( &db->pVtabCtx );
   101946   assert( xConstruct );
   101947   sCtx.pTab = pTab;
   101948   sCtx.pVTable = pVTable;
   101949   db->pVtabCtx = &sCtx;
   101950   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   101951   db->pVtabCtx = 0;
   101952   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   101953 
   101954   if( SQLITE_OK!=rc ){
   101955     if( zErr==0 ){
   101956       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   101957     }else {
   101958       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   101959       sqlite3_free(zErr);
   101960     }
   101961     sqlite3DbFree(db, pVTable);
   101962   }else if( ALWAYS(pVTable->pVtab) ){
   101963     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   101964     ** the sqlite3_vtab object if successful.  */
   101965     pVTable->pVtab->pModule = pMod->pModule;
   101966     pVTable->nRef = 1;
   101967     if( sCtx.pTab ){
   101968       const char *zFormat = "vtable constructor did not declare schema: %s";
   101969       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   101970       sqlite3VtabUnlock(pVTable);
   101971       rc = SQLITE_ERROR;
   101972     }else{
   101973       int iCol;
   101974       /* If everything went according to plan, link the new VTable structure
   101975       ** into the linked list headed by pTab->pVTable. Then loop through the
   101976       ** columns of the table to see if any of them contain the token "hidden".
   101977       ** If so, set the Column.isHidden flag and remove the token from
   101978       ** the type string.  */
   101979       pVTable->pNext = pTab->pVTable;
   101980       pTab->pVTable = pVTable;
   101981 
   101982       for(iCol=0; iCol<pTab->nCol; iCol++){
   101983         char *zType = pTab->aCol[iCol].zType;
   101984         int nType;
   101985         int i = 0;
   101986         if( !zType ) continue;
   101987         nType = sqlite3Strlen30(zType);
   101988         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   101989           for(i=0; i<nType; i++){
   101990             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   101991              && (zType[i+7]=='\0' || zType[i+7]==' ')
   101992             ){
   101993               i++;
   101994               break;
   101995             }
   101996           }
   101997         }
   101998         if( i<nType ){
   101999           int j;
   102000           int nDel = 6 + (zType[i+6] ? 1 : 0);
   102001           for(j=i; (j+nDel)<=nType; j++){
   102002             zType[j] = zType[j+nDel];
   102003           }
   102004           if( zType[i]=='\0' && i>0 ){
   102005             assert(zType[i-1]==' ');
   102006             zType[i-1] = '\0';
   102007           }
   102008           pTab->aCol[iCol].isHidden = 1;
   102009         }
   102010       }
   102011     }
   102012   }
   102013 
   102014   sqlite3DbFree(db, zModuleName);
   102015   return rc;
   102016 }
   102017 
   102018 /*
   102019 ** This function is invoked by the parser to call the xConnect() method
   102020 ** of the virtual table pTab. If an error occurs, an error code is returned
   102021 ** and an error left in pParse.
   102022 **
   102023 ** This call is a no-op if table pTab is not a virtual table.
   102024 */
   102025 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   102026   sqlite3 *db = pParse->db;
   102027   const char *zMod;
   102028   Module *pMod;
   102029   int rc;
   102030 
   102031   assert( pTab );
   102032   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   102033     return SQLITE_OK;
   102034   }
   102035 
   102036   /* Locate the required virtual table module */
   102037   zMod = pTab->azModuleArg[0];
   102038   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   102039 
   102040   if( !pMod ){
   102041     const char *zModule = pTab->azModuleArg[0];
   102042     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   102043     rc = SQLITE_ERROR;
   102044   }else{
   102045     char *zErr = 0;
   102046     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   102047     if( rc!=SQLITE_OK ){
   102048       sqlite3ErrorMsg(pParse, "%s", zErr);
   102049     }
   102050     sqlite3DbFree(db, zErr);
   102051   }
   102052 
   102053   return rc;
   102054 }
   102055 /*
   102056 ** Grow the db->aVTrans[] array so that there is room for at least one
   102057 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
   102058 */
   102059 static int growVTrans(sqlite3 *db){
   102060   const int ARRAY_INCR = 5;
   102061 
   102062   /* Grow the sqlite3.aVTrans array if required */
   102063   if( (db->nVTrans%ARRAY_INCR)==0 ){
   102064     VTable **aVTrans;
   102065     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   102066     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   102067     if( !aVTrans ){
   102068       return SQLITE_NOMEM;
   102069     }
   102070     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   102071     db->aVTrans = aVTrans;
   102072   }
   102073 
   102074   return SQLITE_OK;
   102075 }
   102076 
   102077 /*
   102078 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
   102079 ** have already been reserved using growVTrans().
   102080 */
   102081 static void addToVTrans(sqlite3 *db, VTable *pVTab){
   102082   /* Add pVtab to the end of sqlite3.aVTrans */
   102083   db->aVTrans[db->nVTrans++] = pVTab;
   102084   sqlite3VtabLock(pVTab);
   102085 }
   102086 
   102087 /*
   102088 ** This function is invoked by the vdbe to call the xCreate method
   102089 ** of the virtual table named zTab in database iDb.
   102090 **
   102091 ** If an error occurs, *pzErr is set to point an an English language
   102092 ** description of the error and an SQLITE_XXX error code is returned.
   102093 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   102094 */
   102095 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   102096   int rc = SQLITE_OK;
   102097   Table *pTab;
   102098   Module *pMod;
   102099   const char *zMod;
   102100 
   102101   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   102102   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   102103 
   102104   /* Locate the required virtual table module */
   102105   zMod = pTab->azModuleArg[0];
   102106   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   102107 
   102108   /* If the module has been registered and includes a Create method,
   102109   ** invoke it now. If the module has not been registered, return an
   102110   ** error. Otherwise, do nothing.
   102111   */
   102112   if( !pMod ){
   102113     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   102114     rc = SQLITE_ERROR;
   102115   }else{
   102116     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   102117   }
   102118 
   102119   /* Justification of ALWAYS():  The xConstructor method is required to
   102120   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   102121   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   102122     rc = growVTrans(db);
   102123     if( rc==SQLITE_OK ){
   102124       addToVTrans(db, sqlite3GetVTable(db, pTab));
   102125     }
   102126   }
   102127 
   102128   return rc;
   102129 }
   102130 
   102131 /*
   102132 ** This function is used to set the schema of a virtual table.  It is only
   102133 ** valid to call this function from within the xCreate() or xConnect() of a
   102134 ** virtual table module.
   102135 */
   102136 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   102137   Parse *pParse;
   102138 
   102139   int rc = SQLITE_OK;
   102140   Table *pTab;
   102141   char *zErr = 0;
   102142 
   102143   sqlite3_mutex_enter(db->mutex);
   102144   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
   102145     sqlite3Error(db, SQLITE_MISUSE, 0);
   102146     sqlite3_mutex_leave(db->mutex);
   102147     return SQLITE_MISUSE_BKPT;
   102148   }
   102149   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   102150 
   102151   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   102152   if( pParse==0 ){
   102153     rc = SQLITE_NOMEM;
   102154   }else{
   102155     pParse->declareVtab = 1;
   102156     pParse->db = db;
   102157     pParse->nQueryLoop = 1;
   102158 
   102159     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   102160      && pParse->pNewTable
   102161      && !db->mallocFailed
   102162      && !pParse->pNewTable->pSelect
   102163      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   102164     ){
   102165       if( !pTab->aCol ){
   102166         pTab->aCol = pParse->pNewTable->aCol;
   102167         pTab->nCol = pParse->pNewTable->nCol;
   102168         pParse->pNewTable->nCol = 0;
   102169         pParse->pNewTable->aCol = 0;
   102170       }
   102171       db->pVtabCtx->pTab = 0;
   102172     }else{
   102173       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   102174       sqlite3DbFree(db, zErr);
   102175       rc = SQLITE_ERROR;
   102176     }
   102177     pParse->declareVtab = 0;
   102178 
   102179     if( pParse->pVdbe ){
   102180       sqlite3VdbeFinalize(pParse->pVdbe);
   102181     }
   102182     sqlite3DeleteTable(db, pParse->pNewTable);
   102183     sqlite3StackFree(db, pParse);
   102184   }
   102185 
   102186   assert( (rc&0xff)==rc );
   102187   rc = sqlite3ApiExit(db, rc);
   102188   sqlite3_mutex_leave(db->mutex);
   102189   return rc;
   102190 }
   102191 
   102192 /*
   102193 ** This function is invoked by the vdbe to call the xDestroy method
   102194 ** of the virtual table named zTab in database iDb. This occurs
   102195 ** when a DROP TABLE is mentioned.
   102196 **
   102197 ** This call is a no-op if zTab is not a virtual table.
   102198 */
   102199 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   102200   int rc = SQLITE_OK;
   102201   Table *pTab;
   102202 
   102203   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   102204   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   102205     VTable *p = vtabDisconnectAll(db, pTab);
   102206 
   102207     assert( rc==SQLITE_OK );
   102208     rc = p->pMod->pModule->xDestroy(p->pVtab);
   102209 
   102210     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   102211     if( rc==SQLITE_OK ){
   102212       assert( pTab->pVTable==p && p->pNext==0 );
   102213       p->pVtab = 0;
   102214       pTab->pVTable = 0;
   102215       sqlite3VtabUnlock(p);
   102216     }
   102217   }
   102218 
   102219   return rc;
   102220 }
   102221 
   102222 /*
   102223 ** This function invokes either the xRollback or xCommit method
   102224 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   102225 ** called is identified by the second argument, "offset", which is
   102226 ** the offset of the method to call in the sqlite3_module structure.
   102227 **
   102228 ** The array is cleared after invoking the callbacks.
   102229 */
   102230 static void callFinaliser(sqlite3 *db, int offset){
   102231   int i;
   102232   if( db->aVTrans ){
   102233     for(i=0; i<db->nVTrans; i++){
   102234       VTable *pVTab = db->aVTrans[i];
   102235       sqlite3_vtab *p = pVTab->pVtab;
   102236       if( p ){
   102237         int (*x)(sqlite3_vtab *);
   102238         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   102239         if( x ) x(p);
   102240       }
   102241       pVTab->iSavepoint = 0;
   102242       sqlite3VtabUnlock(pVTab);
   102243     }
   102244     sqlite3DbFree(db, db->aVTrans);
   102245     db->nVTrans = 0;
   102246     db->aVTrans = 0;
   102247   }
   102248 }
   102249 
   102250 /*
   102251 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   102252 ** array. Return the error code for the first error that occurs, or
   102253 ** SQLITE_OK if all xSync operations are successful.
   102254 **
   102255 ** Set *pzErrmsg to point to a buffer that should be released using
   102256 ** sqlite3DbFree() containing an error message, if one is available.
   102257 */
   102258 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
   102259   int i;
   102260   int rc = SQLITE_OK;
   102261   VTable **aVTrans = db->aVTrans;
   102262 
   102263   db->aVTrans = 0;
   102264   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   102265     int (*x)(sqlite3_vtab *);
   102266     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   102267     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   102268       rc = x(pVtab);
   102269       sqlite3DbFree(db, *pzErrmsg);
   102270       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   102271       sqlite3_free(pVtab->zErrMsg);
   102272     }
   102273   }
   102274   db->aVTrans = aVTrans;
   102275   return rc;
   102276 }
   102277 
   102278 /*
   102279 ** Invoke the xRollback method of all virtual tables in the
   102280 ** sqlite3.aVTrans array. Then clear the array itself.
   102281 */
   102282 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   102283   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   102284   return SQLITE_OK;
   102285 }
   102286 
   102287 /*
   102288 ** Invoke the xCommit method of all virtual tables in the
   102289 ** sqlite3.aVTrans array. Then clear the array itself.
   102290 */
   102291 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   102292   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   102293   return SQLITE_OK;
   102294 }
   102295 
   102296 /*
   102297 ** If the virtual table pVtab supports the transaction interface
   102298 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   102299 ** not currently open, invoke the xBegin method now.
   102300 **
   102301 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   102302 ** in the sqlite3.aVTrans array.
   102303 */
   102304 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   102305   int rc = SQLITE_OK;
   102306   const sqlite3_module *pModule;
   102307 
   102308   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   102309   ** than zero, then this function is being called from within a
   102310   ** virtual module xSync() callback. It is illegal to write to
   102311   ** virtual module tables in this case, so return SQLITE_LOCKED.
   102312   */
   102313   if( sqlite3VtabInSync(db) ){
   102314     return SQLITE_LOCKED;
   102315   }
   102316   if( !pVTab ){
   102317     return SQLITE_OK;
   102318   }
   102319   pModule = pVTab->pVtab->pModule;
   102320 
   102321   if( pModule->xBegin ){
   102322     int i;
   102323 
   102324     /* If pVtab is already in the aVTrans array, return early */
   102325     for(i=0; i<db->nVTrans; i++){
   102326       if( db->aVTrans[i]==pVTab ){
   102327         return SQLITE_OK;
   102328       }
   102329     }
   102330 
   102331     /* Invoke the xBegin method. If successful, add the vtab to the
   102332     ** sqlite3.aVTrans[] array. */
   102333     rc = growVTrans(db);
   102334     if( rc==SQLITE_OK ){
   102335       rc = pModule->xBegin(pVTab->pVtab);
   102336       if( rc==SQLITE_OK ){
   102337         addToVTrans(db, pVTab);
   102338       }
   102339     }
   102340   }
   102341   return rc;
   102342 }
   102343 
   102344 /*
   102345 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
   102346 ** virtual tables that currently have an open transaction. Pass iSavepoint
   102347 ** as the second argument to the virtual table method invoked.
   102348 **
   102349 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
   102350 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
   102351 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
   102352 ** an open transaction is invoked.
   102353 **
   102354 ** If any virtual table method returns an error code other than SQLITE_OK,
   102355 ** processing is abandoned and the error returned to the caller of this
   102356 ** function immediately. If all calls to virtual table methods are successful,
   102357 ** SQLITE_OK is returned.
   102358 */
   102359 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
   102360   int rc = SQLITE_OK;
   102361 
   102362   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
   102363   assert( iSavepoint>=0 );
   102364   if( db->aVTrans ){
   102365     int i;
   102366     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   102367       VTable *pVTab = db->aVTrans[i];
   102368       const sqlite3_module *pMod = pVTab->pMod->pModule;
   102369       if( pVTab->pVtab && pMod->iVersion>=2 ){
   102370         int (*xMethod)(sqlite3_vtab *, int);
   102371         switch( op ){
   102372           case SAVEPOINT_BEGIN:
   102373             xMethod = pMod->xSavepoint;
   102374             pVTab->iSavepoint = iSavepoint+1;
   102375             break;
   102376           case SAVEPOINT_ROLLBACK:
   102377             xMethod = pMod->xRollbackTo;
   102378             break;
   102379           default:
   102380             xMethod = pMod->xRelease;
   102381             break;
   102382         }
   102383         if( xMethod && pVTab->iSavepoint>iSavepoint ){
   102384           rc = xMethod(pVTab->pVtab, iSavepoint);
   102385         }
   102386       }
   102387     }
   102388   }
   102389   return rc;
   102390 }
   102391 
   102392 /*
   102393 ** The first parameter (pDef) is a function implementation.  The
   102394 ** second parameter (pExpr) is the first argument to this function.
   102395 ** If pExpr is a column in a virtual table, then let the virtual
   102396 ** table implementation have an opportunity to overload the function.
   102397 **
   102398 ** This routine is used to allow virtual table implementations to
   102399 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   102400 **
   102401 ** Return either the pDef argument (indicating no change) or a
   102402 ** new FuncDef structure that is marked as ephemeral using the
   102403 ** SQLITE_FUNC_EPHEM flag.
   102404 */
   102405 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   102406   sqlite3 *db,    /* Database connection for reporting malloc problems */
   102407   FuncDef *pDef,  /* Function to possibly overload */
   102408   int nArg,       /* Number of arguments to the function */
   102409   Expr *pExpr     /* First argument to the function */
   102410 ){
   102411   Table *pTab;
   102412   sqlite3_vtab *pVtab;
   102413   sqlite3_module *pMod;
   102414   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   102415   void *pArg = 0;
   102416   FuncDef *pNew;
   102417   int rc = 0;
   102418   char *zLowerName;
   102419   unsigned char *z;
   102420 
   102421 
   102422   /* Check to see the left operand is a column in a virtual table */
   102423   if( NEVER(pExpr==0) ) return pDef;
   102424   if( pExpr->op!=TK_COLUMN ) return pDef;
   102425   pTab = pExpr->pTab;
   102426   if( NEVER(pTab==0) ) return pDef;
   102427   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   102428   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   102429   assert( pVtab!=0 );
   102430   assert( pVtab->pModule!=0 );
   102431   pMod = (sqlite3_module *)pVtab->pModule;
   102432   if( pMod->xFindFunction==0 ) return pDef;
   102433 
   102434   /* Call the xFindFunction method on the virtual table implementation
   102435   ** to see if the implementation wants to overload this function
   102436   */
   102437   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   102438   if( zLowerName ){
   102439     for(z=(unsigned char*)zLowerName; *z; z++){
   102440       *z = sqlite3UpperToLower[*z];
   102441     }
   102442     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   102443     sqlite3DbFree(db, zLowerName);
   102444   }
   102445   if( rc==0 ){
   102446     return pDef;
   102447   }
   102448 
   102449   /* Create a new ephemeral function definition for the overloaded
   102450   ** function */
   102451   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   102452                              + sqlite3Strlen30(pDef->zName) + 1);
   102453   if( pNew==0 ){
   102454     return pDef;
   102455   }
   102456   *pNew = *pDef;
   102457   pNew->zName = (char *)&pNew[1];
   102458   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   102459   pNew->xFunc = xFunc;
   102460   pNew->pUserData = pArg;
   102461   pNew->flags |= SQLITE_FUNC_EPHEM;
   102462   return pNew;
   102463 }
   102464 
   102465 /*
   102466 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   102467 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   102468 ** array if it is missing.  If pTab is already in the array, this routine
   102469 ** is a no-op.
   102470 */
   102471 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   102472   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   102473   int i, n;
   102474   Table **apVtabLock;
   102475 
   102476   assert( IsVirtual(pTab) );
   102477   for(i=0; i<pToplevel->nVtabLock; i++){
   102478     if( pTab==pToplevel->apVtabLock[i] ) return;
   102479   }
   102480   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   102481   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   102482   if( apVtabLock ){
   102483     pToplevel->apVtabLock = apVtabLock;
   102484     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   102485   }else{
   102486     pToplevel->db->mallocFailed = 1;
   102487   }
   102488 }
   102489 
   102490 /*
   102491 ** Return the ON CONFLICT resolution mode in effect for the virtual
   102492 ** table update operation currently in progress.
   102493 **
   102494 ** The results of this routine are undefined unless it is called from
   102495 ** within an xUpdate method.
   102496 */
   102497 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
   102498   static const unsigned char aMap[] = {
   102499     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   102500   };
   102501   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
   102502   assert( OE_Ignore==4 && OE_Replace==5 );
   102503   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
   102504   return (int)aMap[db->vtabOnConflict-1];
   102505 }
   102506 
   102507 /*
   102508 ** Call from within the xCreate() or xConnect() methods to provide
   102509 ** the SQLite core with additional information about the behavior
   102510 ** of the virtual table being implemented.
   102511 */
   102512 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   102513   va_list ap;
   102514   int rc = SQLITE_OK;
   102515 
   102516   sqlite3_mutex_enter(db->mutex);
   102517 
   102518   va_start(ap, op);
   102519   switch( op ){
   102520     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
   102521       VtabCtx *p = db->pVtabCtx;
   102522       if( !p ){
   102523         rc = SQLITE_MISUSE_BKPT;
   102524       }else{
   102525         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
   102526         p->pVTable->bConstraint = (u8)va_arg(ap, int);
   102527       }
   102528       break;
   102529     }
   102530     default:
   102531       rc = SQLITE_MISUSE_BKPT;
   102532       break;
   102533   }
   102534   va_end(ap);
   102535 
   102536   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
   102537   sqlite3_mutex_leave(db->mutex);
   102538   return rc;
   102539 }
   102540 
   102541 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   102542 
   102543 /************** End of vtab.c ************************************************/
   102544 /************** Begin file where.c *******************************************/
   102545 /*
   102546 ** 2001 September 15
   102547 **
   102548 ** The author disclaims copyright to this source code.  In place of
   102549 ** a legal notice, here is a blessing:
   102550 **
   102551 **    May you do good and not evil.
   102552 **    May you find forgiveness for yourself and forgive others.
   102553 **    May you share freely, never taking more than you give.
   102554 **
   102555 *************************************************************************
   102556 ** This module contains C code that generates VDBE code used to process
   102557 ** the WHERE clause of SQL statements.  This module is responsible for
   102558 ** generating the code that loops through a table looking for applicable
   102559 ** rows.  Indices are selected and used to speed the search when doing
   102560 ** so is applicable.  Because this module is responsible for selecting
   102561 ** indices, you might also think of this module as the "query optimizer".
   102562 */
   102563 
   102564 
   102565 /*
   102566 ** Trace output macros
   102567 */
   102568 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   102569 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
   102570 #endif
   102571 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   102572 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
   102573 #else
   102574 # define WHERETRACE(X)
   102575 #endif
   102576 
   102577 /* Forward reference
   102578 */
   102579 typedef struct WhereClause WhereClause;
   102580 typedef struct WhereMaskSet WhereMaskSet;
   102581 typedef struct WhereOrInfo WhereOrInfo;
   102582 typedef struct WhereAndInfo WhereAndInfo;
   102583 typedef struct WhereCost WhereCost;
   102584 
   102585 /*
   102586 ** The query generator uses an array of instances of this structure to
   102587 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   102588 ** clause subexpression is separated from the others by AND operators,
   102589 ** usually, or sometimes subexpressions separated by OR.
   102590 **
   102591 ** All WhereTerms are collected into a single WhereClause structure.
   102592 ** The following identity holds:
   102593 **
   102594 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   102595 **
   102596 ** When a term is of the form:
   102597 **
   102598 **              X <op> <expr>
   102599 **
   102600 ** where X is a column name and <op> is one of certain operators,
   102601 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   102602 ** cursor number and column number for X.  WhereTerm.eOperator records
   102603 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   102604 ** use of a bitmask encoding for the operator allows us to search
   102605 ** quickly for terms that match any of several different operators.
   102606 **
   102607 ** A WhereTerm might also be two or more subterms connected by OR:
   102608 **
   102609 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   102610 **
   102611 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
   102612 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   102613 ** is collected about the
   102614 **
   102615 ** If a term in the WHERE clause does not match either of the two previous
   102616 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   102617 ** to the original subexpression content and wtFlags is set up appropriately
   102618 ** but no other fields in the WhereTerm object are meaningful.
   102619 **
   102620 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   102621 ** but they do so indirectly.  A single WhereMaskSet structure translates
   102622 ** cursor number into bits and the translated bit is stored in the prereq
   102623 ** fields.  The translation is used in order to maximize the number of
   102624 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   102625 ** spread out over the non-negative integers.  For example, the cursor
   102626 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   102627 ** translates these sparse cursor numbers into consecutive integers
   102628 ** beginning with 0 in order to make the best possible use of the available
   102629 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   102630 ** would be mapped into integers 0 through 7.
   102631 **
   102632 ** The number of terms in a join is limited by the number of bits
   102633 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   102634 ** is only able to process joins with 64 or fewer tables.
   102635 */
   102636 typedef struct WhereTerm WhereTerm;
   102637 struct WhereTerm {
   102638   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   102639   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   102640   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   102641   union {
   102642     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   102643     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
   102644     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
   102645   } u;
   102646   u16 eOperator;          /* A WO_xx value describing <op> */
   102647   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   102648   u8 nChild;              /* Number of children that must disable us */
   102649   WhereClause *pWC;       /* The clause this term is part of */
   102650   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   102651   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   102652 };
   102653 
   102654 /*
   102655 ** Allowed values of WhereTerm.wtFlags
   102656 */
   102657 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   102658 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   102659 #define TERM_CODED      0x04   /* This term is already coded */
   102660 #define TERM_COPIED     0x08   /* Has a child */
   102661 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   102662 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   102663 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   102664 #ifdef SQLITE_ENABLE_STAT3
   102665 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
   102666 #else
   102667 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
   102668 #endif
   102669 
   102670 /*
   102671 ** An instance of the following structure holds all information about a
   102672 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   102673 **
   102674 ** Explanation of pOuter:  For a WHERE clause of the form
   102675 **
   102676 **           a AND ((b AND c) OR (d AND e)) AND f
   102677 **
   102678 ** There are separate WhereClause objects for the whole clause and for
   102679 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
   102680 ** subclauses points to the WhereClause object for the whole clause.
   102681 */
   102682 struct WhereClause {
   102683   Parse *pParse;           /* The parser context */
   102684   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
   102685   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
   102686   WhereClause *pOuter;     /* Outer conjunction */
   102687   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   102688   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
   102689   int nTerm;               /* Number of terms */
   102690   int nSlot;               /* Number of entries in a[] */
   102691   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   102692 #if defined(SQLITE_SMALL_STACK)
   102693   WhereTerm aStatic[1];    /* Initial static space for a[] */
   102694 #else
   102695   WhereTerm aStatic[8];    /* Initial static space for a[] */
   102696 #endif
   102697 };
   102698 
   102699 /*
   102700 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   102701 ** a dynamically allocated instance of the following structure.
   102702 */
   102703 struct WhereOrInfo {
   102704   WhereClause wc;          /* Decomposition into subterms */
   102705   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   102706 };
   102707 
   102708 /*
   102709 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   102710 ** a dynamically allocated instance of the following structure.
   102711 */
   102712 struct WhereAndInfo {
   102713   WhereClause wc;          /* The subexpression broken out */
   102714 };
   102715 
   102716 /*
   102717 ** An instance of the following structure keeps track of a mapping
   102718 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   102719 **
   102720 ** The VDBE cursor numbers are small integers contained in
   102721 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   102722 ** clause, the cursor numbers might not begin with 0 and they might
   102723 ** contain gaps in the numbering sequence.  But we want to make maximum
   102724 ** use of the bits in our bitmasks.  This structure provides a mapping
   102725 ** from the sparse cursor numbers into consecutive integers beginning
   102726 ** with 0.
   102727 **
   102728 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   102729 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   102730 **
   102731 ** For example, if the WHERE clause expression used these VDBE
   102732 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   102733 ** would map those cursor numbers into bits 0 through 5.
   102734 **
   102735 ** Note that the mapping is not necessarily ordered.  In the example
   102736 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   102737 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   102738 ** does not really matter.  What is important is that sparse cursor
   102739 ** numbers all get mapped into bit numbers that begin with 0 and contain
   102740 ** no gaps.
   102741 */
   102742 struct WhereMaskSet {
   102743   int n;                        /* Number of assigned cursor values */
   102744   int ix[BMS];                  /* Cursor assigned to each bit */
   102745 };
   102746 
   102747 /*
   102748 ** A WhereCost object records a lookup strategy and the estimated
   102749 ** cost of pursuing that strategy.
   102750 */
   102751 struct WhereCost {
   102752   WherePlan plan;    /* The lookup strategy */
   102753   double rCost;      /* Overall cost of pursuing this search strategy */
   102754   Bitmask used;      /* Bitmask of cursors used by this plan */
   102755 };
   102756 
   102757 /*
   102758 ** Bitmasks for the operators that indices are able to exploit.  An
   102759 ** OR-ed combination of these values can be used when searching for
   102760 ** terms in the where clause.
   102761 */
   102762 #define WO_IN     0x001
   102763 #define WO_EQ     0x002
   102764 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   102765 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   102766 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   102767 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   102768 #define WO_MATCH  0x040
   102769 #define WO_ISNULL 0x080
   102770 #define WO_OR     0x100       /* Two or more OR-connected terms */
   102771 #define WO_AND    0x200       /* Two or more AND-connected terms */
   102772 #define WO_NOOP   0x800       /* This term does not restrict search space */
   102773 
   102774 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   102775 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   102776 
   102777 /*
   102778 ** Value for wsFlags returned by bestIndex() and stored in
   102779 ** WhereLevel.wsFlags.  These flags determine which search
   102780 ** strategies are appropriate.
   102781 **
   102782 ** The least significant 12 bits is reserved as a mask for WO_ values above.
   102783 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
   102784 ** But if the table is the right table of a left join, WhereLevel.wsFlags
   102785 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
   102786 ** the "op" parameter to findTerm when we are resolving equality constraints.
   102787 ** ISNULL constraints will then not be used on the right table of a left
   102788 ** join.  Tickets #2177 and #2189.
   102789 */
   102790 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
   102791 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
   102792 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
   102793 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
   102794 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
   102795 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
   102796 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
   102797 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
   102798 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
   102799 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
   102800 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
   102801 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
   102802 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
   102803 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
   102804 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
   102805 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
   102806 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
   102807 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
   102808 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
   102809 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
   102810 
   102811 /*
   102812 ** Initialize a preallocated WhereClause structure.
   102813 */
   102814 static void whereClauseInit(
   102815   WhereClause *pWC,        /* The WhereClause to be initialized */
   102816   Parse *pParse,           /* The parsing context */
   102817   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
   102818   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
   102819 ){
   102820   pWC->pParse = pParse;
   102821   pWC->pMaskSet = pMaskSet;
   102822   pWC->pOuter = 0;
   102823   pWC->nTerm = 0;
   102824   pWC->nSlot = ArraySize(pWC->aStatic);
   102825   pWC->a = pWC->aStatic;
   102826   pWC->vmask = 0;
   102827   pWC->wctrlFlags = wctrlFlags;
   102828 }
   102829 
   102830 /* Forward reference */
   102831 static void whereClauseClear(WhereClause*);
   102832 
   102833 /*
   102834 ** Deallocate all memory associated with a WhereOrInfo object.
   102835 */
   102836 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   102837   whereClauseClear(&p->wc);
   102838   sqlite3DbFree(db, p);
   102839 }
   102840 
   102841 /*
   102842 ** Deallocate all memory associated with a WhereAndInfo object.
   102843 */
   102844 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   102845   whereClauseClear(&p->wc);
   102846   sqlite3DbFree(db, p);
   102847 }
   102848 
   102849 /*
   102850 ** Deallocate a WhereClause structure.  The WhereClause structure
   102851 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   102852 */
   102853 static void whereClauseClear(WhereClause *pWC){
   102854   int i;
   102855   WhereTerm *a;
   102856   sqlite3 *db = pWC->pParse->db;
   102857   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   102858     if( a->wtFlags & TERM_DYNAMIC ){
   102859       sqlite3ExprDelete(db, a->pExpr);
   102860     }
   102861     if( a->wtFlags & TERM_ORINFO ){
   102862       whereOrInfoDelete(db, a->u.pOrInfo);
   102863     }else if( a->wtFlags & TERM_ANDINFO ){
   102864       whereAndInfoDelete(db, a->u.pAndInfo);
   102865     }
   102866   }
   102867   if( pWC->a!=pWC->aStatic ){
   102868     sqlite3DbFree(db, pWC->a);
   102869   }
   102870 }
   102871 
   102872 /*
   102873 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   102874 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   102875 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   102876 ** 0 is returned if the new WhereTerm could not be added due to a memory
   102877 ** allocation error.  The memory allocation failure will be recorded in
   102878 ** the db->mallocFailed flag so that higher-level functions can detect it.
   102879 **
   102880 ** This routine will increase the size of the pWC->a[] array as necessary.
   102881 **
   102882 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   102883 ** for freeing the expression p is assumed by the WhereClause object pWC.
   102884 ** This is true even if this routine fails to allocate a new WhereTerm.
   102885 **
   102886 ** WARNING:  This routine might reallocate the space used to store
   102887 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   102888 ** calling this routine.  Such pointers may be reinitialized by referencing
   102889 ** the pWC->a[] array.
   102890 */
   102891 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   102892   WhereTerm *pTerm;
   102893   int idx;
   102894   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
   102895   if( pWC->nTerm>=pWC->nSlot ){
   102896     WhereTerm *pOld = pWC->a;
   102897     sqlite3 *db = pWC->pParse->db;
   102898     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   102899     if( pWC->a==0 ){
   102900       if( wtFlags & TERM_DYNAMIC ){
   102901         sqlite3ExprDelete(db, p);
   102902       }
   102903       pWC->a = pOld;
   102904       return 0;
   102905     }
   102906     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   102907     if( pOld!=pWC->aStatic ){
   102908       sqlite3DbFree(db, pOld);
   102909     }
   102910     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   102911   }
   102912   pTerm = &pWC->a[idx = pWC->nTerm++];
   102913   pTerm->pExpr = p;
   102914   pTerm->wtFlags = wtFlags;
   102915   pTerm->pWC = pWC;
   102916   pTerm->iParent = -1;
   102917   return idx;
   102918 }
   102919 
   102920 /*
   102921 ** This routine identifies subexpressions in the WHERE clause where
   102922 ** each subexpression is separated by the AND operator or some other
   102923 ** operator specified in the op parameter.  The WhereClause structure
   102924 ** is filled with pointers to subexpressions.  For example:
   102925 **
   102926 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   102927 **           \________/     \_______________/     \________________/
   102928 **            slot[0]            slot[1]               slot[2]
   102929 **
   102930 ** The original WHERE clause in pExpr is unaltered.  All this routine
   102931 ** does is make slot[] entries point to substructure within pExpr.
   102932 **
   102933 ** In the previous sentence and in the diagram, "slot[]" refers to
   102934 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   102935 ** all terms of the WHERE clause.
   102936 */
   102937 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
   102938   pWC->op = (u8)op;
   102939   if( pExpr==0 ) return;
   102940   if( pExpr->op!=op ){
   102941     whereClauseInsert(pWC, pExpr, 0);
   102942   }else{
   102943     whereSplit(pWC, pExpr->pLeft, op);
   102944     whereSplit(pWC, pExpr->pRight, op);
   102945   }
   102946 }
   102947 
   102948 /*
   102949 ** Initialize an expression mask set (a WhereMaskSet object)
   102950 */
   102951 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
   102952 
   102953 /*
   102954 ** Return the bitmask for the given cursor number.  Return 0 if
   102955 ** iCursor is not in the set.
   102956 */
   102957 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   102958   int i;
   102959   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
   102960   for(i=0; i<pMaskSet->n; i++){
   102961     if( pMaskSet->ix[i]==iCursor ){
   102962       return ((Bitmask)1)<<i;
   102963     }
   102964   }
   102965   return 0;
   102966 }
   102967 
   102968 /*
   102969 ** Create a new mask for cursor iCursor.
   102970 **
   102971 ** There is one cursor per table in the FROM clause.  The number of
   102972 ** tables in the FROM clause is limited by a test early in the
   102973 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   102974 ** array will never overflow.
   102975 */
   102976 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   102977   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   102978   pMaskSet->ix[pMaskSet->n++] = iCursor;
   102979 }
   102980 
   102981 /*
   102982 ** This routine walks (recursively) an expression tree and generates
   102983 ** a bitmask indicating which tables are used in that expression
   102984 ** tree.
   102985 **
   102986 ** In order for this routine to work, the calling function must have
   102987 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
   102988 ** the header comment on that routine for additional information.
   102989 ** The sqlite3ResolveExprNames() routines looks for column names and
   102990 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
   102991 ** the VDBE cursor number of the table.  This routine just has to
   102992 ** translate the cursor numbers into bitmask values and OR all
   102993 ** the bitmasks together.
   102994 */
   102995 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   102996 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   102997 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   102998   Bitmask mask = 0;
   102999   if( p==0 ) return 0;
   103000   if( p->op==TK_COLUMN ){
   103001     mask = getMask(pMaskSet, p->iTable);
   103002     return mask;
   103003   }
   103004   mask = exprTableUsage(pMaskSet, p->pRight);
   103005   mask |= exprTableUsage(pMaskSet, p->pLeft);
   103006   if( ExprHasProperty(p, EP_xIsSelect) ){
   103007     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   103008   }else{
   103009     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   103010   }
   103011   return mask;
   103012 }
   103013 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   103014   int i;
   103015   Bitmask mask = 0;
   103016   if( pList ){
   103017     for(i=0; i<pList->nExpr; i++){
   103018       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   103019     }
   103020   }
   103021   return mask;
   103022 }
   103023 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   103024   Bitmask mask = 0;
   103025   while( pS ){
   103026     SrcList *pSrc = pS->pSrc;
   103027     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   103028     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   103029     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   103030     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   103031     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   103032     if( ALWAYS(pSrc!=0) ){
   103033       int i;
   103034       for(i=0; i<pSrc->nSrc; i++){
   103035         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
   103036         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
   103037       }
   103038     }
   103039     pS = pS->pPrior;
   103040   }
   103041   return mask;
   103042 }
   103043 
   103044 /*
   103045 ** Return TRUE if the given operator is one of the operators that is
   103046 ** allowed for an indexable WHERE clause term.  The allowed operators are
   103047 ** "=", "<", ">", "<=", ">=", and "IN".
   103048 **
   103049 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
   103050 ** of one of the following forms: column = expression column > expression
   103051 ** column >= expression column < expression column <= expression
   103052 ** expression = column expression > column expression >= column
   103053 ** expression < column expression <= column column IN
   103054 ** (expression-list) column IN (subquery) column IS NULL
   103055 */
   103056 static int allowedOp(int op){
   103057   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   103058   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   103059   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   103060   assert( TK_GE==TK_EQ+4 );
   103061   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   103062 }
   103063 
   103064 /*
   103065 ** Swap two objects of type TYPE.
   103066 */
   103067 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   103068 
   103069 /*
   103070 ** Commute a comparison operator.  Expressions of the form "X op Y"
   103071 ** are converted into "Y op X".
   103072 **
   103073 ** If a collation sequence is associated with either the left or right
   103074 ** side of the comparison, it remains associated with the same side after
   103075 ** the commutation. So "Y collate NOCASE op X" becomes
   103076 ** "X collate NOCASE op Y". This is because any collation sequence on
   103077 ** the left hand side of a comparison overrides any collation sequence
   103078 ** attached to the right. For the same reason the EP_ExpCollate flag
   103079 ** is not commuted.
   103080 */
   103081 static void exprCommute(Parse *pParse, Expr *pExpr){
   103082   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
   103083   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
   103084   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   103085   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
   103086   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   103087   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
   103088   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
   103089   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
   103090   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   103091   if( pExpr->op>=TK_GT ){
   103092     assert( TK_LT==TK_GT+2 );
   103093     assert( TK_GE==TK_LE+2 );
   103094     assert( TK_GT>TK_EQ );
   103095     assert( TK_GT<TK_LE );
   103096     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   103097     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   103098   }
   103099 }
   103100 
   103101 /*
   103102 ** Translate from TK_xx operator to WO_xx bitmask.
   103103 */
   103104 static u16 operatorMask(int op){
   103105   u16 c;
   103106   assert( allowedOp(op) );
   103107   if( op==TK_IN ){
   103108     c = WO_IN;
   103109   }else if( op==TK_ISNULL ){
   103110     c = WO_ISNULL;
   103111   }else{
   103112     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   103113     c = (u16)(WO_EQ<<(op-TK_EQ));
   103114   }
   103115   assert( op!=TK_ISNULL || c==WO_ISNULL );
   103116   assert( op!=TK_IN || c==WO_IN );
   103117   assert( op!=TK_EQ || c==WO_EQ );
   103118   assert( op!=TK_LT || c==WO_LT );
   103119   assert( op!=TK_LE || c==WO_LE );
   103120   assert( op!=TK_GT || c==WO_GT );
   103121   assert( op!=TK_GE || c==WO_GE );
   103122   return c;
   103123 }
   103124 
   103125 /*
   103126 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   103127 ** where X is a reference to the iColumn of table iCur and <op> is one of
   103128 ** the WO_xx operator codes specified by the op parameter.
   103129 ** Return a pointer to the term.  Return 0 if not found.
   103130 */
   103131 static WhereTerm *findTerm(
   103132   WhereClause *pWC,     /* The WHERE clause to be searched */
   103133   int iCur,             /* Cursor number of LHS */
   103134   int iColumn,          /* Column number of LHS */
   103135   Bitmask notReady,     /* RHS must not overlap with this mask */
   103136   u32 op,               /* Mask of WO_xx values describing operator */
   103137   Index *pIdx           /* Must be compatible with this index, if not NULL */
   103138 ){
   103139   WhereTerm *pTerm;
   103140   int k;
   103141   assert( iCur>=0 );
   103142   op &= WO_ALL;
   103143   for(; pWC; pWC=pWC->pOuter){
   103144     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
   103145       if( pTerm->leftCursor==iCur
   103146          && (pTerm->prereqRight & notReady)==0
   103147          && pTerm->u.leftColumn==iColumn
   103148          && (pTerm->eOperator & op)!=0
   103149       ){
   103150         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
   103151           Expr *pX = pTerm->pExpr;
   103152           CollSeq *pColl;
   103153           char idxaff;
   103154           int j;
   103155           Parse *pParse = pWC->pParse;
   103156 
   103157           idxaff = pIdx->pTable->aCol[iColumn].affinity;
   103158           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
   103159 
   103160           /* Figure out the collation sequence required from an index for
   103161           ** it to be useful for optimising expression pX. Store this
   103162           ** value in variable pColl.
   103163           */
   103164           assert(pX->pLeft);
   103165           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   103166           assert(pColl || pParse->nErr);
   103167 
   103168           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   103169             if( NEVER(j>=pIdx->nColumn) ) return 0;
   103170           }
   103171           if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
   103172         }
   103173         return pTerm;
   103174       }
   103175     }
   103176   }
   103177   return 0;
   103178 }
   103179 
   103180 /* Forward reference */
   103181 static void exprAnalyze(SrcList*, WhereClause*, int);
   103182 
   103183 /*
   103184 ** Call exprAnalyze on all terms in a WHERE clause.
   103185 **
   103186 **
   103187 */
   103188 static void exprAnalyzeAll(
   103189   SrcList *pTabList,       /* the FROM clause */
   103190   WhereClause *pWC         /* the WHERE clause to be analyzed */
   103191 ){
   103192   int i;
   103193   for(i=pWC->nTerm-1; i>=0; i--){
   103194     exprAnalyze(pTabList, pWC, i);
   103195   }
   103196 }
   103197 
   103198 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   103199 /*
   103200 ** Check to see if the given expression is a LIKE or GLOB operator that
   103201 ** can be optimized using inequality constraints.  Return TRUE if it is
   103202 ** so and false if not.
   103203 **
   103204 ** In order for the operator to be optimizible, the RHS must be a string
   103205 ** literal that does not begin with a wildcard.
   103206 */
   103207 static int isLikeOrGlob(
   103208   Parse *pParse,    /* Parsing and code generating context */
   103209   Expr *pExpr,      /* Test this expression */
   103210   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   103211   int *pisComplete, /* True if the only wildcard is % in the last character */
   103212   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   103213 ){
   103214   const char *z = 0;         /* String on RHS of LIKE operator */
   103215   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   103216   ExprList *pList;           /* List of operands to the LIKE operator */
   103217   int c;                     /* One character in z[] */
   103218   int cnt;                   /* Number of non-wildcard prefix characters */
   103219   char wc[3];                /* Wildcard characters */
   103220   sqlite3 *db = pParse->db;  /* Database connection */
   103221   sqlite3_value *pVal = 0;
   103222   int op;                    /* Opcode of pRight */
   103223 
   103224   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   103225     return 0;
   103226   }
   103227 #ifdef SQLITE_EBCDIC
   103228   if( *pnoCase ) return 0;
   103229 #endif
   103230   pList = pExpr->x.pList;
   103231   pLeft = pList->a[1].pExpr;
   103232   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
   103233     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   103234     ** be the name of an indexed column with TEXT affinity. */
   103235     return 0;
   103236   }
   103237   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   103238 
   103239   pRight = pList->a[0].pExpr;
   103240   op = pRight->op;
   103241   if( op==TK_REGISTER ){
   103242     op = pRight->op2;
   103243   }
   103244   if( op==TK_VARIABLE ){
   103245     Vdbe *pReprepare = pParse->pReprepare;
   103246     int iCol = pRight->iColumn;
   103247     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
   103248     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   103249       z = (char *)sqlite3_value_text(pVal);
   103250     }
   103251     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
   103252     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   103253   }else if( op==TK_STRING ){
   103254     z = pRight->u.zToken;
   103255   }
   103256   if( z ){
   103257     cnt = 0;
   103258     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   103259       cnt++;
   103260     }
   103261     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   103262       Expr *pPrefix;
   103263       *pisComplete = c==wc[0] && z[cnt+1]==0;
   103264       pPrefix = sqlite3Expr(db, TK_STRING, z);
   103265       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   103266       *ppPrefix = pPrefix;
   103267       if( op==TK_VARIABLE ){
   103268         Vdbe *v = pParse->pVdbe;
   103269         sqlite3VdbeSetVarmask(v, pRight->iColumn);
   103270         if( *pisComplete && pRight->u.zToken[1] ){
   103271           /* If the rhs of the LIKE expression is a variable, and the current
   103272           ** value of the variable means there is no need to invoke the LIKE
   103273           ** function, then no OP_Variable will be added to the program.
   103274           ** This causes problems for the sqlite3_bind_parameter_name()
   103275           ** API. To workaround them, add a dummy OP_Variable here.
   103276           */
   103277           int r1 = sqlite3GetTempReg(pParse);
   103278           sqlite3ExprCodeTarget(pParse, pRight, r1);
   103279           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   103280           sqlite3ReleaseTempReg(pParse, r1);
   103281         }
   103282       }
   103283     }else{
   103284       z = 0;
   103285     }
   103286   }
   103287 
   103288   sqlite3ValueFree(pVal);
   103289   return (z!=0);
   103290 }
   103291 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   103292 
   103293 
   103294 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103295 /*
   103296 ** Check to see if the given expression is of the form
   103297 **
   103298 **         column MATCH expr
   103299 **
   103300 ** If it is then return TRUE.  If not, return FALSE.
   103301 */
   103302 static int isMatchOfColumn(
   103303   Expr *pExpr      /* Test this expression */
   103304 ){
   103305   ExprList *pList;
   103306 
   103307   if( pExpr->op!=TK_FUNCTION ){
   103308     return 0;
   103309   }
   103310   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   103311     return 0;
   103312   }
   103313   pList = pExpr->x.pList;
   103314   if( pList->nExpr!=2 ){
   103315     return 0;
   103316   }
   103317   if( pList->a[1].pExpr->op != TK_COLUMN ){
   103318     return 0;
   103319   }
   103320   return 1;
   103321 }
   103322 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   103323 
   103324 /*
   103325 ** If the pBase expression originated in the ON or USING clause of
   103326 ** a join, then transfer the appropriate markings over to derived.
   103327 */
   103328 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   103329   pDerived->flags |= pBase->flags & EP_FromJoin;
   103330   pDerived->iRightJoinTable = pBase->iRightJoinTable;
   103331 }
   103332 
   103333 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   103334 /*
   103335 ** Analyze a term that consists of two or more OR-connected
   103336 ** subterms.  So in:
   103337 **
   103338 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   103339 **                          ^^^^^^^^^^^^^^^^^^^^
   103340 **
   103341 ** This routine analyzes terms such as the middle term in the above example.
   103342 ** A WhereOrTerm object is computed and attached to the term under
   103343 ** analysis, regardless of the outcome of the analysis.  Hence:
   103344 **
   103345 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   103346 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   103347 **
   103348 ** The term being analyzed must have two or more of OR-connected subterms.
   103349 ** A single subterm might be a set of AND-connected sub-subterms.
   103350 ** Examples of terms under analysis:
   103351 **
   103352 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   103353 **     (B)     x=expr1 OR expr2=x OR x=expr3
   103354 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   103355 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   103356 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   103357 **
   103358 ** CASE 1:
   103359 **
   103360 ** If all subterms are of the form T.C=expr for some single column of C
   103361 ** a single table T (as shown in example B above) then create a new virtual
   103362 ** term that is an equivalent IN expression.  In other words, if the term
   103363 ** being analyzed is:
   103364 **
   103365 **      x = expr1  OR  expr2 = x  OR  x = expr3
   103366 **
   103367 ** then create a new virtual term like this:
   103368 **
   103369 **      x IN (expr1,expr2,expr3)
   103370 **
   103371 ** CASE 2:
   103372 **
   103373 ** If all subterms are indexable by a single table T, then set
   103374 **
   103375 **     WhereTerm.eOperator              =  WO_OR
   103376 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   103377 **
   103378 ** A subterm is "indexable" if it is of the form
   103379 ** "T.C <op> <expr>" where C is any column of table T and
   103380 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   103381 ** A subterm is also indexable if it is an AND of two or more
   103382 ** subsubterms at least one of which is indexable.  Indexable AND
   103383 ** subterms have their eOperator set to WO_AND and they have
   103384 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   103385 **
   103386 ** From another point of view, "indexable" means that the subterm could
   103387 ** potentially be used with an index if an appropriate index exists.
   103388 ** This analysis does not consider whether or not the index exists; that
   103389 ** is something the bestIndex() routine will determine.  This analysis
   103390 ** only looks at whether subterms appropriate for indexing exist.
   103391 **
   103392 ** All examples A through E above all satisfy case 2.  But if a term
   103393 ** also statisfies case 1 (such as B) we know that the optimizer will
   103394 ** always prefer case 1, so in that case we pretend that case 2 is not
   103395 ** satisfied.
   103396 **
   103397 ** It might be the case that multiple tables are indexable.  For example,
   103398 ** (E) above is indexable on tables P, Q, and R.
   103399 **
   103400 ** Terms that satisfy case 2 are candidates for lookup by using
   103401 ** separate indices to find rowids for each subterm and composing
   103402 ** the union of all rowids using a RowSet object.  This is similar
   103403 ** to "bitmap indices" in other database engines.
   103404 **
   103405 ** OTHERWISE:
   103406 **
   103407 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   103408 ** zero.  This term is not useful for search.
   103409 */
   103410 static void exprAnalyzeOrTerm(
   103411   SrcList *pSrc,            /* the FROM clause */
   103412   WhereClause *pWC,         /* the complete WHERE clause */
   103413   int idxTerm               /* Index of the OR-term to be analyzed */
   103414 ){
   103415   Parse *pParse = pWC->pParse;            /* Parser context */
   103416   sqlite3 *db = pParse->db;               /* Database connection */
   103417   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   103418   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   103419   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
   103420   int i;                                  /* Loop counters */
   103421   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   103422   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   103423   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   103424   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   103425   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   103426 
   103427   /*
   103428   ** Break the OR clause into its separate subterms.  The subterms are
   103429   ** stored in a WhereClause structure containing within the WhereOrInfo
   103430   ** object that is attached to the original OR clause term.
   103431   */
   103432   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   103433   assert( pExpr->op==TK_OR );
   103434   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   103435   if( pOrInfo==0 ) return;
   103436   pTerm->wtFlags |= TERM_ORINFO;
   103437   pOrWc = &pOrInfo->wc;
   103438   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
   103439   whereSplit(pOrWc, pExpr, TK_OR);
   103440   exprAnalyzeAll(pSrc, pOrWc);
   103441   if( db->mallocFailed ) return;
   103442   assert( pOrWc->nTerm>=2 );
   103443 
   103444   /*
   103445   ** Compute the set of tables that might satisfy cases 1 or 2.
   103446   */
   103447   indexable = ~(Bitmask)0;
   103448   chngToIN = ~(pWC->vmask);
   103449   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   103450     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   103451       WhereAndInfo *pAndInfo;
   103452       assert( pOrTerm->eOperator==0 );
   103453       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   103454       chngToIN = 0;
   103455       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   103456       if( pAndInfo ){
   103457         WhereClause *pAndWC;
   103458         WhereTerm *pAndTerm;
   103459         int j;
   103460         Bitmask b = 0;
   103461         pOrTerm->u.pAndInfo = pAndInfo;
   103462         pOrTerm->wtFlags |= TERM_ANDINFO;
   103463         pOrTerm->eOperator = WO_AND;
   103464         pAndWC = &pAndInfo->wc;
   103465         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
   103466         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   103467         exprAnalyzeAll(pSrc, pAndWC);
   103468         pAndWC->pOuter = pWC;
   103469         testcase( db->mallocFailed );
   103470         if( !db->mallocFailed ){
   103471           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   103472             assert( pAndTerm->pExpr );
   103473             if( allowedOp(pAndTerm->pExpr->op) ){
   103474               b |= getMask(pMaskSet, pAndTerm->leftCursor);
   103475             }
   103476           }
   103477         }
   103478         indexable &= b;
   103479       }
   103480     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   103481       /* Skip this term for now.  We revisit it when we process the
   103482       ** corresponding TERM_VIRTUAL term */
   103483     }else{
   103484       Bitmask b;
   103485       b = getMask(pMaskSet, pOrTerm->leftCursor);
   103486       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   103487         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   103488         b |= getMask(pMaskSet, pOther->leftCursor);
   103489       }
   103490       indexable &= b;
   103491       if( pOrTerm->eOperator!=WO_EQ ){
   103492         chngToIN = 0;
   103493       }else{
   103494         chngToIN &= b;
   103495       }
   103496     }
   103497   }
   103498 
   103499   /*
   103500   ** Record the set of tables that satisfy case 2.  The set might be
   103501   ** empty.
   103502   */
   103503   pOrInfo->indexable = indexable;
   103504   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   103505 
   103506   /*
   103507   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   103508   ** we have to do some additional checking to see if case 1 really
   103509   ** is satisfied.
   103510   **
   103511   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   103512   ** that there is no possibility of transforming the OR clause into an
   103513   ** IN operator because one or more terms in the OR clause contain
   103514   ** something other than == on a column in the single table.  The 1-bit
   103515   ** case means that every term of the OR clause is of the form
   103516   ** "table.column=expr" for some single table.  The one bit that is set
   103517   ** will correspond to the common table.  We still need to check to make
   103518   ** sure the same column is used on all terms.  The 2-bit case is when
   103519   ** the all terms are of the form "table1.column=table2.column".  It
   103520   ** might be possible to form an IN operator with either table1.column
   103521   ** or table2.column as the LHS if either is common to every term of
   103522   ** the OR clause.
   103523   **
   103524   ** Note that terms of the form "table.column1=table.column2" (the
   103525   ** same table on both sizes of the ==) cannot be optimized.
   103526   */
   103527   if( chngToIN ){
   103528     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   103529     int iColumn = -1;         /* Column index on lhs of IN operator */
   103530     int iCursor = -1;         /* Table cursor common to all terms */
   103531     int j = 0;                /* Loop counter */
   103532 
   103533     /* Search for a table and column that appears on one side or the
   103534     ** other of the == operator in every subterm.  That table and column
   103535     ** will be recorded in iCursor and iColumn.  There might not be any
   103536     ** such table and column.  Set okToChngToIN if an appropriate table
   103537     ** and column is found but leave okToChngToIN false if not found.
   103538     */
   103539     for(j=0; j<2 && !okToChngToIN; j++){
   103540       pOrTerm = pOrWc->a;
   103541       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   103542         assert( pOrTerm->eOperator==WO_EQ );
   103543         pOrTerm->wtFlags &= ~TERM_OR_OK;
   103544         if( pOrTerm->leftCursor==iCursor ){
   103545           /* This is the 2-bit case and we are on the second iteration and
   103546           ** current term is from the first iteration.  So skip this term. */
   103547           assert( j==1 );
   103548           continue;
   103549         }
   103550         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
   103551           /* This term must be of the form t1.a==t2.b where t2 is in the
   103552           ** chngToIN set but t1 is not.  This term will be either preceeded
   103553           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   103554           ** and use its inversion. */
   103555           testcase( pOrTerm->wtFlags & TERM_COPIED );
   103556           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   103557           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   103558           continue;
   103559         }
   103560         iColumn = pOrTerm->u.leftColumn;
   103561         iCursor = pOrTerm->leftCursor;
   103562         break;
   103563       }
   103564       if( i<0 ){
   103565         /* No candidate table+column was found.  This can only occur
   103566         ** on the second iteration */
   103567         assert( j==1 );
   103568         assert( (chngToIN&(chngToIN-1))==0 );
   103569         assert( chngToIN==getMask(pMaskSet, iCursor) );
   103570         break;
   103571       }
   103572       testcase( j==1 );
   103573 
   103574       /* We have found a candidate table and column.  Check to see if that
   103575       ** table and column is common to every term in the OR clause */
   103576       okToChngToIN = 1;
   103577       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   103578         assert( pOrTerm->eOperator==WO_EQ );
   103579         if( pOrTerm->leftCursor!=iCursor ){
   103580           pOrTerm->wtFlags &= ~TERM_OR_OK;
   103581         }else if( pOrTerm->u.leftColumn!=iColumn ){
   103582           okToChngToIN = 0;
   103583         }else{
   103584           int affLeft, affRight;
   103585           /* If the right-hand side is also a column, then the affinities
   103586           ** of both right and left sides must be such that no type
   103587           ** conversions are required on the right.  (Ticket #2249)
   103588           */
   103589           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   103590           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   103591           if( affRight!=0 && affRight!=affLeft ){
   103592             okToChngToIN = 0;
   103593           }else{
   103594             pOrTerm->wtFlags |= TERM_OR_OK;
   103595           }
   103596         }
   103597       }
   103598     }
   103599 
   103600     /* At this point, okToChngToIN is true if original pTerm satisfies
   103601     ** case 1.  In that case, construct a new virtual term that is
   103602     ** pTerm converted into an IN operator.
   103603     **
   103604     ** EV: R-00211-15100
   103605     */
   103606     if( okToChngToIN ){
   103607       Expr *pDup;            /* A transient duplicate expression */
   103608       ExprList *pList = 0;   /* The RHS of the IN operator */
   103609       Expr *pLeft = 0;       /* The LHS of the IN operator */
   103610       Expr *pNew;            /* The complete IN operator */
   103611 
   103612       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   103613         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   103614         assert( pOrTerm->eOperator==WO_EQ );
   103615         assert( pOrTerm->leftCursor==iCursor );
   103616         assert( pOrTerm->u.leftColumn==iColumn );
   103617         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   103618         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
   103619         pLeft = pOrTerm->pExpr->pLeft;
   103620       }
   103621       assert( pLeft!=0 );
   103622       pDup = sqlite3ExprDup(db, pLeft, 0);
   103623       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   103624       if( pNew ){
   103625         int idxNew;
   103626         transferJoinMarkings(pNew, pExpr);
   103627         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   103628         pNew->x.pList = pList;
   103629         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   103630         testcase( idxNew==0 );
   103631         exprAnalyze(pSrc, pWC, idxNew);
   103632         pTerm = &pWC->a[idxTerm];
   103633         pWC->a[idxNew].iParent = idxTerm;
   103634         pTerm->nChild = 1;
   103635       }else{
   103636         sqlite3ExprListDelete(db, pList);
   103637       }
   103638       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
   103639     }
   103640   }
   103641 }
   103642 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   103643 
   103644 
   103645 /*
   103646 ** The input to this routine is an WhereTerm structure with only the
   103647 ** "pExpr" field filled in.  The job of this routine is to analyze the
   103648 ** subexpression and populate all the other fields of the WhereTerm
   103649 ** structure.
   103650 **
   103651 ** If the expression is of the form "<expr> <op> X" it gets commuted
   103652 ** to the standard form of "X <op> <expr>".
   103653 **
   103654 ** If the expression is of the form "X <op> Y" where both X and Y are
   103655 ** columns, then the original expression is unchanged and a new virtual
   103656 ** term of the form "Y <op> X" is added to the WHERE clause and
   103657 ** analyzed separately.  The original term is marked with TERM_COPIED
   103658 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   103659 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   103660 ** is a commuted copy of a prior term.)  The original term has nChild=1
   103661 ** and the copy has idxParent set to the index of the original term.
   103662 */
   103663 static void exprAnalyze(
   103664   SrcList *pSrc,            /* the FROM clause */
   103665   WhereClause *pWC,         /* the WHERE clause */
   103666   int idxTerm               /* Index of the term to be analyzed */
   103667 ){
   103668   WhereTerm *pTerm;                /* The term to be analyzed */
   103669   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   103670   Expr *pExpr;                     /* The expression to be analyzed */
   103671   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   103672   Bitmask prereqAll;               /* Prerequesites of pExpr */
   103673   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   103674   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   103675   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   103676   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   103677   int op;                          /* Top-level operator.  pExpr->op */
   103678   Parse *pParse = pWC->pParse;     /* Parsing context */
   103679   sqlite3 *db = pParse->db;        /* Database connection */
   103680 
   103681   if( db->mallocFailed ){
   103682     return;
   103683   }
   103684   pTerm = &pWC->a[idxTerm];
   103685   pMaskSet = pWC->pMaskSet;
   103686   pExpr = pTerm->pExpr;
   103687   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   103688   op = pExpr->op;
   103689   if( op==TK_IN ){
   103690     assert( pExpr->pRight==0 );
   103691     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   103692       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   103693     }else{
   103694       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   103695     }
   103696   }else if( op==TK_ISNULL ){
   103697     pTerm->prereqRight = 0;
   103698   }else{
   103699     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   103700   }
   103701   prereqAll = exprTableUsage(pMaskSet, pExpr);
   103702   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   103703     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   103704     prereqAll |= x;
   103705     extraRight = x-1;  /* ON clause terms may not be used with an index
   103706                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   103707   }
   103708   pTerm->prereqAll = prereqAll;
   103709   pTerm->leftCursor = -1;
   103710   pTerm->iParent = -1;
   103711   pTerm->eOperator = 0;
   103712   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
   103713     Expr *pLeft = pExpr->pLeft;
   103714     Expr *pRight = pExpr->pRight;
   103715     if( pLeft->op==TK_COLUMN ){
   103716       pTerm->leftCursor = pLeft->iTable;
   103717       pTerm->u.leftColumn = pLeft->iColumn;
   103718       pTerm->eOperator = operatorMask(op);
   103719     }
   103720     if( pRight && pRight->op==TK_COLUMN ){
   103721       WhereTerm *pNew;
   103722       Expr *pDup;
   103723       if( pTerm->leftCursor>=0 ){
   103724         int idxNew;
   103725         pDup = sqlite3ExprDup(db, pExpr, 0);
   103726         if( db->mallocFailed ){
   103727           sqlite3ExprDelete(db, pDup);
   103728           return;
   103729         }
   103730         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   103731         if( idxNew==0 ) return;
   103732         pNew = &pWC->a[idxNew];
   103733         pNew->iParent = idxTerm;
   103734         pTerm = &pWC->a[idxTerm];
   103735         pTerm->nChild = 1;
   103736         pTerm->wtFlags |= TERM_COPIED;
   103737       }else{
   103738         pDup = pExpr;
   103739         pNew = pTerm;
   103740       }
   103741       exprCommute(pParse, pDup);
   103742       pLeft = pDup->pLeft;
   103743       pNew->leftCursor = pLeft->iTable;
   103744       pNew->u.leftColumn = pLeft->iColumn;
   103745       testcase( (prereqLeft | extraRight) != prereqLeft );
   103746       pNew->prereqRight = prereqLeft | extraRight;
   103747       pNew->prereqAll = prereqAll;
   103748       pNew->eOperator = operatorMask(pDup->op);
   103749     }
   103750   }
   103751 
   103752 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   103753   /* If a term is the BETWEEN operator, create two new virtual terms
   103754   ** that define the range that the BETWEEN implements.  For example:
   103755   **
   103756   **      a BETWEEN b AND c
   103757   **
   103758   ** is converted into:
   103759   **
   103760   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   103761   **
   103762   ** The two new terms are added onto the end of the WhereClause object.
   103763   ** The new terms are "dynamic" and are children of the original BETWEEN
   103764   ** term.  That means that if the BETWEEN term is coded, the children are
   103765   ** skipped.  Or, if the children are satisfied by an index, the original
   103766   ** BETWEEN term is skipped.
   103767   */
   103768   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   103769     ExprList *pList = pExpr->x.pList;
   103770     int i;
   103771     static const u8 ops[] = {TK_GE, TK_LE};
   103772     assert( pList!=0 );
   103773     assert( pList->nExpr==2 );
   103774     for(i=0; i<2; i++){
   103775       Expr *pNewExpr;
   103776       int idxNew;
   103777       pNewExpr = sqlite3PExpr(pParse, ops[i],
   103778                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   103779                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   103780       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   103781       testcase( idxNew==0 );
   103782       exprAnalyze(pSrc, pWC, idxNew);
   103783       pTerm = &pWC->a[idxTerm];
   103784       pWC->a[idxNew].iParent = idxTerm;
   103785     }
   103786     pTerm->nChild = 2;
   103787   }
   103788 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   103789 
   103790 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   103791   /* Analyze a term that is composed of two or more subterms connected by
   103792   ** an OR operator.
   103793   */
   103794   else if( pExpr->op==TK_OR ){
   103795     assert( pWC->op==TK_AND );
   103796     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   103797     pTerm = &pWC->a[idxTerm];
   103798   }
   103799 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   103800 
   103801 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   103802   /* Add constraints to reduce the search space on a LIKE or GLOB
   103803   ** operator.
   103804   **
   103805   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   103806   **
   103807   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   103808   **
   103809   ** The last character of the prefix "abc" is incremented to form the
   103810   ** termination condition "abd".
   103811   */
   103812   if( pWC->op==TK_AND
   103813    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   103814   ){
   103815     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   103816     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   103817     Expr *pNewExpr1;
   103818     Expr *pNewExpr2;
   103819     int idxNew1;
   103820     int idxNew2;
   103821     CollSeq *pColl;    /* Collating sequence to use */
   103822 
   103823     pLeft = pExpr->x.pList->a[1].pExpr;
   103824     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   103825     if( !db->mallocFailed ){
   103826       u8 c, *pC;       /* Last character before the first wildcard */
   103827       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   103828       c = *pC;
   103829       if( noCase ){
   103830         /* The point is to increment the last character before the first
   103831         ** wildcard.  But if we increment '@', that will push it into the
   103832         ** alphabetic range where case conversions will mess up the
   103833         ** inequality.  To avoid this, make sure to also run the full
   103834         ** LIKE on all candidate expressions by clearing the isComplete flag
   103835         */
   103836         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
   103837 
   103838 
   103839         c = sqlite3UpperToLower[c];
   103840       }
   103841       *pC = c + 1;
   103842     }
   103843     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
   103844     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   103845                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   103846                      pStr1, 0);
   103847     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   103848     testcase( idxNew1==0 );
   103849     exprAnalyze(pSrc, pWC, idxNew1);
   103850     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   103851                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   103852                      pStr2, 0);
   103853     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   103854     testcase( idxNew2==0 );
   103855     exprAnalyze(pSrc, pWC, idxNew2);
   103856     pTerm = &pWC->a[idxTerm];
   103857     if( isComplete ){
   103858       pWC->a[idxNew1].iParent = idxTerm;
   103859       pWC->a[idxNew2].iParent = idxTerm;
   103860       pTerm->nChild = 2;
   103861     }
   103862   }
   103863 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   103864 
   103865 #ifndef SQLITE_OMIT_VIRTUALTABLE
   103866   /* Add a WO_MATCH auxiliary term to the constraint set if the
   103867   ** current expression is of the form:  column MATCH expr.
   103868   ** This information is used by the xBestIndex methods of
   103869   ** virtual tables.  The native query optimizer does not attempt
   103870   ** to do anything with MATCH functions.
   103871   */
   103872   if( isMatchOfColumn(pExpr) ){
   103873     int idxNew;
   103874     Expr *pRight, *pLeft;
   103875     WhereTerm *pNewTerm;
   103876     Bitmask prereqColumn, prereqExpr;
   103877 
   103878     pRight = pExpr->x.pList->a[0].pExpr;
   103879     pLeft = pExpr->x.pList->a[1].pExpr;
   103880     prereqExpr = exprTableUsage(pMaskSet, pRight);
   103881     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   103882     if( (prereqExpr & prereqColumn)==0 ){
   103883       Expr *pNewExpr;
   103884       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   103885                               0, sqlite3ExprDup(db, pRight, 0), 0);
   103886       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   103887       testcase( idxNew==0 );
   103888       pNewTerm = &pWC->a[idxNew];
   103889       pNewTerm->prereqRight = prereqExpr;
   103890       pNewTerm->leftCursor = pLeft->iTable;
   103891       pNewTerm->u.leftColumn = pLeft->iColumn;
   103892       pNewTerm->eOperator = WO_MATCH;
   103893       pNewTerm->iParent = idxTerm;
   103894       pTerm = &pWC->a[idxTerm];
   103895       pTerm->nChild = 1;
   103896       pTerm->wtFlags |= TERM_COPIED;
   103897       pNewTerm->prereqAll = pTerm->prereqAll;
   103898     }
   103899   }
   103900 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   103901 
   103902 #ifdef SQLITE_ENABLE_STAT3
   103903   /* When sqlite_stat3 histogram data is available an operator of the
   103904   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
   103905   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
   103906   ** virtual term of that form.
   103907   **
   103908   ** Note that the virtual term must be tagged with TERM_VNULL.  This
   103909   ** TERM_VNULL tag will suppress the not-null check at the beginning
   103910   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
   103911   ** the start of the loop will prevent any results from being returned.
   103912   */
   103913   if( pExpr->op==TK_NOTNULL
   103914    && pExpr->pLeft->op==TK_COLUMN
   103915    && pExpr->pLeft->iColumn>=0
   103916   ){
   103917     Expr *pNewExpr;
   103918     Expr *pLeft = pExpr->pLeft;
   103919     int idxNew;
   103920     WhereTerm *pNewTerm;
   103921 
   103922     pNewExpr = sqlite3PExpr(pParse, TK_GT,
   103923                             sqlite3ExprDup(db, pLeft, 0),
   103924                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
   103925 
   103926     idxNew = whereClauseInsert(pWC, pNewExpr,
   103927                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
   103928     if( idxNew ){
   103929       pNewTerm = &pWC->a[idxNew];
   103930       pNewTerm->prereqRight = 0;
   103931       pNewTerm->leftCursor = pLeft->iTable;
   103932       pNewTerm->u.leftColumn = pLeft->iColumn;
   103933       pNewTerm->eOperator = WO_GT;
   103934       pNewTerm->iParent = idxTerm;
   103935       pTerm = &pWC->a[idxTerm];
   103936       pTerm->nChild = 1;
   103937       pTerm->wtFlags |= TERM_COPIED;
   103938       pNewTerm->prereqAll = pTerm->prereqAll;
   103939     }
   103940   }
   103941 #endif /* SQLITE_ENABLE_STAT */
   103942 
   103943   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   103944   ** an index for tables to the left of the join.
   103945   */
   103946   pTerm->prereqRight |= extraRight;
   103947 }
   103948 
   103949 /*
   103950 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
   103951 ** a reference to any table other than the iBase table.
   103952 */
   103953 static int referencesOtherTables(
   103954   ExprList *pList,          /* Search expressions in ths list */
   103955   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
   103956   int iFirst,               /* Be searching with the iFirst-th expression */
   103957   int iBase                 /* Ignore references to this table */
   103958 ){
   103959   Bitmask allowed = ~getMask(pMaskSet, iBase);
   103960   while( iFirst<pList->nExpr ){
   103961     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
   103962       return 1;
   103963     }
   103964   }
   103965   return 0;
   103966 }
   103967 
   103968 /*
   103969 ** This function searches the expression list passed as the second argument
   103970 ** for an expression of type TK_COLUMN that refers to the same column and
   103971 ** uses the same collation sequence as the iCol'th column of index pIdx.
   103972 ** Argument iBase is the cursor number used for the table that pIdx refers
   103973 ** to.
   103974 **
   103975 ** If such an expression is found, its index in pList->a[] is returned. If
   103976 ** no expression is found, -1 is returned.
   103977 */
   103978 static int findIndexCol(
   103979   Parse *pParse,                  /* Parse context */
   103980   ExprList *pList,                /* Expression list to search */
   103981   int iBase,                      /* Cursor for table associated with pIdx */
   103982   Index *pIdx,                    /* Index to match column of */
   103983   int iCol                        /* Column of index to match */
   103984 ){
   103985   int i;
   103986   const char *zColl = pIdx->azColl[iCol];
   103987 
   103988   for(i=0; i<pList->nExpr; i++){
   103989     Expr *p = pList->a[i].pExpr;
   103990     if( p->op==TK_COLUMN
   103991      && p->iColumn==pIdx->aiColumn[iCol]
   103992      && p->iTable==iBase
   103993     ){
   103994       CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
   103995       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
   103996         return i;
   103997       }
   103998     }
   103999   }
   104000 
   104001   return -1;
   104002 }
   104003 
   104004 /*
   104005 ** This routine determines if pIdx can be used to assist in processing a
   104006 ** DISTINCT qualifier. In other words, it tests whether or not using this
   104007 ** index for the outer loop guarantees that rows with equal values for
   104008 ** all expressions in the pDistinct list are delivered grouped together.
   104009 **
   104010 ** For example, the query
   104011 **
   104012 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
   104013 **
   104014 ** can benefit from any index on columns "b" and "c".
   104015 */
   104016 static int isDistinctIndex(
   104017   Parse *pParse,                  /* Parsing context */
   104018   WhereClause *pWC,               /* The WHERE clause */
   104019   Index *pIdx,                    /* The index being considered */
   104020   int base,                       /* Cursor number for the table pIdx is on */
   104021   ExprList *pDistinct,            /* The DISTINCT expressions */
   104022   int nEqCol                      /* Number of index columns with == */
   104023 ){
   104024   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
   104025   int i;                          /* Iterator variable */
   104026 
   104027   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
   104028   testcase( pDistinct->nExpr==BMS-1 );
   104029 
   104030   /* Loop through all the expressions in the distinct list. If any of them
   104031   ** are not simple column references, return early. Otherwise, test if the
   104032   ** WHERE clause contains a "col=X" clause. If it does, the expression
   104033   ** can be ignored. If it does not, and the column does not belong to the
   104034   ** same table as index pIdx, return early. Finally, if there is no
   104035   ** matching "col=X" expression and the column is on the same table as pIdx,
   104036   ** set the corresponding bit in variable mask.
   104037   */
   104038   for(i=0; i<pDistinct->nExpr; i++){
   104039     WhereTerm *pTerm;
   104040     Expr *p = pDistinct->a[i].pExpr;
   104041     if( p->op!=TK_COLUMN ) return 0;
   104042     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
   104043     if( pTerm ){
   104044       Expr *pX = pTerm->pExpr;
   104045       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   104046       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
   104047       if( p1==p2 ) continue;
   104048     }
   104049     if( p->iTable!=base ) return 0;
   104050     mask |= (((Bitmask)1) << i);
   104051   }
   104052 
   104053   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
   104054     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
   104055     if( iExpr<0 ) break;
   104056     mask &= ~(((Bitmask)1) << iExpr);
   104057   }
   104058 
   104059   return (mask==0);
   104060 }
   104061 
   104062 
   104063 /*
   104064 ** Return true if the DISTINCT expression-list passed as the third argument
   104065 ** is redundant. A DISTINCT list is redundant if the database contains a
   104066 ** UNIQUE index that guarantees that the result of the query will be distinct
   104067 ** anyway.
   104068 */
   104069 static int isDistinctRedundant(
   104070   Parse *pParse,
   104071   SrcList *pTabList,
   104072   WhereClause *pWC,
   104073   ExprList *pDistinct
   104074 ){
   104075   Table *pTab;
   104076   Index *pIdx;
   104077   int i;
   104078   int iBase;
   104079 
   104080   /* If there is more than one table or sub-select in the FROM clause of
   104081   ** this query, then it will not be possible to show that the DISTINCT
   104082   ** clause is redundant. */
   104083   if( pTabList->nSrc!=1 ) return 0;
   104084   iBase = pTabList->a[0].iCursor;
   104085   pTab = pTabList->a[0].pTab;
   104086 
   104087   /* If any of the expressions is an IPK column on table iBase, then return
   104088   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   104089   ** current SELECT is a correlated sub-query.
   104090   */
   104091   for(i=0; i<pDistinct->nExpr; i++){
   104092     Expr *p = pDistinct->a[i].pExpr;
   104093     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   104094   }
   104095 
   104096   /* Loop through all indices on the table, checking each to see if it makes
   104097   ** the DISTINCT qualifier redundant. It does so if:
   104098   **
   104099   **   1. The index is itself UNIQUE, and
   104100   **
   104101   **   2. All of the columns in the index are either part of the pDistinct
   104102   **      list, or else the WHERE clause contains a term of the form "col=X",
   104103   **      where X is a constant value. The collation sequences of the
   104104   **      comparison and select-list expressions must match those of the index.
   104105   */
   104106   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   104107     if( pIdx->onError==OE_None ) continue;
   104108     for(i=0; i<pIdx->nColumn; i++){
   104109       int iCol = pIdx->aiColumn[i];
   104110       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
   104111        && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
   104112       ){
   104113         break;
   104114       }
   104115     }
   104116     if( i==pIdx->nColumn ){
   104117       /* This index implies that the DISTINCT qualifier is redundant. */
   104118       return 1;
   104119     }
   104120   }
   104121 
   104122   return 0;
   104123 }
   104124 
   104125 /*
   104126 ** This routine decides if pIdx can be used to satisfy the ORDER BY
   104127 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
   104128 ** ORDER BY clause, this routine returns 0.
   104129 **
   104130 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
   104131 ** left-most table in the FROM clause of that same SELECT statement and
   104132 ** the table has a cursor number of "base".  pIdx is an index on pTab.
   104133 **
   104134 ** nEqCol is the number of columns of pIdx that are used as equality
   104135 ** constraints.  Any of these columns may be missing from the ORDER BY
   104136 ** clause and the match can still be a success.
   104137 **
   104138 ** All terms of the ORDER BY that match against the index must be either
   104139 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
   104140 ** index do not need to satisfy this constraint.)  The *pbRev value is
   104141 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
   104142 ** the ORDER BY clause is all ASC.
   104143 */
   104144 static int isSortingIndex(
   104145   Parse *pParse,          /* Parsing context */
   104146   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
   104147   Index *pIdx,            /* The index we are testing */
   104148   int base,               /* Cursor number for the table to be sorted */
   104149   ExprList *pOrderBy,     /* The ORDER BY clause */
   104150   int nEqCol,             /* Number of index columns with == constraints */
   104151   int wsFlags,            /* Index usages flags */
   104152   int *pbRev              /* Set to 1 if ORDER BY is DESC */
   104153 ){
   104154   int i, j;                       /* Loop counters */
   104155   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
   104156   int nTerm;                      /* Number of ORDER BY terms */
   104157   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
   104158   sqlite3 *db = pParse->db;
   104159 
   104160   if( !pOrderBy ) return 0;
   104161   if( wsFlags & WHERE_COLUMN_IN ) return 0;
   104162   if( pIdx->bUnordered ) return 0;
   104163 
   104164   nTerm = pOrderBy->nExpr;
   104165   assert( nTerm>0 );
   104166 
   104167   /* Argument pIdx must either point to a 'real' named index structure,
   104168   ** or an index structure allocated on the stack by bestBtreeIndex() to
   104169   ** represent the rowid index that is part of every table.  */
   104170   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
   104171 
   104172   /* Match terms of the ORDER BY clause against columns of
   104173   ** the index.
   104174   **
   104175   ** Note that indices have pIdx->nColumn regular columns plus
   104176   ** one additional column containing the rowid.  The rowid column
   104177   ** of the index is also allowed to match against the ORDER BY
   104178   ** clause.
   104179   */
   104180   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
   104181     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
   104182     CollSeq *pColl;    /* The collating sequence of pExpr */
   104183     int termSortOrder; /* Sort order for this term */
   104184     int iColumn;       /* The i-th column of the index.  -1 for rowid */
   104185     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
   104186     const char *zColl; /* Name of the collating sequence for i-th index term */
   104187 
   104188     pExpr = pTerm->pExpr;
   104189     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
   104190       /* Can not use an index sort on anything that is not a column in the
   104191       ** left-most table of the FROM clause */
   104192       break;
   104193     }
   104194     pColl = sqlite3ExprCollSeq(pParse, pExpr);
   104195     if( !pColl ){
   104196       pColl = db->pDfltColl;
   104197     }
   104198     if( pIdx->zName && i<pIdx->nColumn ){
   104199       iColumn = pIdx->aiColumn[i];
   104200       if( iColumn==pIdx->pTable->iPKey ){
   104201         iColumn = -1;
   104202       }
   104203       iSortOrder = pIdx->aSortOrder[i];
   104204       zColl = pIdx->azColl[i];
   104205     }else{
   104206       iColumn = -1;
   104207       iSortOrder = 0;
   104208       zColl = pColl->zName;
   104209     }
   104210     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
   104211       /* Term j of the ORDER BY clause does not match column i of the index */
   104212       if( i<nEqCol ){
   104213         /* If an index column that is constrained by == fails to match an
   104214         ** ORDER BY term, that is OK.  Just ignore that column of the index
   104215         */
   104216         continue;
   104217       }else if( i==pIdx->nColumn ){
   104218         /* Index column i is the rowid.  All other terms match. */
   104219         break;
   104220       }else{
   104221         /* If an index column fails to match and is not constrained by ==
   104222         ** then the index cannot satisfy the ORDER BY constraint.
   104223         */
   104224         return 0;
   104225       }
   104226     }
   104227     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
   104228     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
   104229     assert( iSortOrder==0 || iSortOrder==1 );
   104230     termSortOrder = iSortOrder ^ pTerm->sortOrder;
   104231     if( i>nEqCol ){
   104232       if( termSortOrder!=sortOrder ){
   104233         /* Indices can only be used if all ORDER BY terms past the
   104234         ** equality constraints are all either DESC or ASC. */
   104235         return 0;
   104236       }
   104237     }else{
   104238       sortOrder = termSortOrder;
   104239     }
   104240     j++;
   104241     pTerm++;
   104242     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   104243       /* If the indexed column is the primary key and everything matches
   104244       ** so far and none of the ORDER BY terms to the right reference other
   104245       ** tables in the join, then we are assured that the index can be used
   104246       ** to sort because the primary key is unique and so none of the other
   104247       ** columns will make any difference
   104248       */
   104249       j = nTerm;
   104250     }
   104251   }
   104252 
   104253   *pbRev = sortOrder!=0;
   104254   if( j>=nTerm ){
   104255     /* All terms of the ORDER BY clause are covered by this index so
   104256     ** this index can be used for sorting. */
   104257     return 1;
   104258   }
   104259   if( pIdx->onError!=OE_None && i==pIdx->nColumn
   104260       && (wsFlags & WHERE_COLUMN_NULL)==0
   104261       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   104262     /* All terms of this index match some prefix of the ORDER BY clause
   104263     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
   104264     ** clause reference other tables in a join.  If this is all true then
   104265     ** the order by clause is superfluous.  Not that if the matching
   104266     ** condition is IS NULL then the result is not necessarily unique
   104267     ** even on a UNIQUE index, so disallow those cases. */
   104268     return 1;
   104269   }
   104270   return 0;
   104271 }
   104272 
   104273 /*
   104274 ** Prepare a crude estimate of the logarithm of the input value.
   104275 ** The results need not be exact.  This is only used for estimating
   104276 ** the total cost of performing operations with O(logN) or O(NlogN)
   104277 ** complexity.  Because N is just a guess, it is no great tragedy if
   104278 ** logN is a little off.
   104279 */
   104280 static double estLog(double N){
   104281   double logN = 1;
   104282   double x = 10;
   104283   while( N>x ){
   104284     logN += 1;
   104285     x *= 10;
   104286   }
   104287   return logN;
   104288 }
   104289 
   104290 /*
   104291 ** Two routines for printing the content of an sqlite3_index_info
   104292 ** structure.  Used for testing and debugging only.  If neither
   104293 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   104294 ** are no-ops.
   104295 */
   104296 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
   104297 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   104298   int i;
   104299   if( !sqlite3WhereTrace ) return;
   104300   for(i=0; i<p->nConstraint; i++){
   104301     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   104302        i,
   104303        p->aConstraint[i].iColumn,
   104304        p->aConstraint[i].iTermOffset,
   104305        p->aConstraint[i].op,
   104306        p->aConstraint[i].usable);
   104307   }
   104308   for(i=0; i<p->nOrderBy; i++){
   104309     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   104310        i,
   104311        p->aOrderBy[i].iColumn,
   104312        p->aOrderBy[i].desc);
   104313   }
   104314 }
   104315 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   104316   int i;
   104317   if( !sqlite3WhereTrace ) return;
   104318   for(i=0; i<p->nConstraint; i++){
   104319     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   104320        i,
   104321        p->aConstraintUsage[i].argvIndex,
   104322        p->aConstraintUsage[i].omit);
   104323   }
   104324   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   104325   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   104326   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   104327   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   104328 }
   104329 #else
   104330 #define TRACE_IDX_INPUTS(A)
   104331 #define TRACE_IDX_OUTPUTS(A)
   104332 #endif
   104333 
   104334 /*
   104335 ** Required because bestIndex() is called by bestOrClauseIndex()
   104336 */
   104337 static void bestIndex(
   104338     Parse*, WhereClause*, struct SrcList_item*,
   104339     Bitmask, Bitmask, ExprList*, WhereCost*);
   104340 
   104341 /*
   104342 ** This routine attempts to find an scanning strategy that can be used
   104343 ** to optimize an 'OR' expression that is part of a WHERE clause.
   104344 **
   104345 ** The table associated with FROM clause term pSrc may be either a
   104346 ** regular B-Tree table or a virtual table.
   104347 */
   104348 static void bestOrClauseIndex(
   104349   Parse *pParse,              /* The parsing context */
   104350   WhereClause *pWC,           /* The WHERE clause */
   104351   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   104352   Bitmask notReady,           /* Mask of cursors not available for indexing */
   104353   Bitmask notValid,           /* Cursors not available for any purpose */
   104354   ExprList *pOrderBy,         /* The ORDER BY clause */
   104355   WhereCost *pCost            /* Lowest cost query plan */
   104356 ){
   104357 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   104358   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   104359   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
   104360   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
   104361   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
   104362 
   104363   /* The OR-clause optimization is disallowed if the INDEXED BY or
   104364   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
   104365   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
   104366     return;
   104367   }
   104368   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
   104369     return;
   104370   }
   104371 
   104372   /* Search the WHERE clause terms for a usable WO_OR term. */
   104373   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104374     if( pTerm->eOperator==WO_OR
   104375      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
   104376      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
   104377     ){
   104378       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   104379       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   104380       WhereTerm *pOrTerm;
   104381       int flags = WHERE_MULTI_OR;
   104382       double rTotal = 0;
   104383       double nRow = 0;
   104384       Bitmask used = 0;
   104385 
   104386       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   104387         WhereCost sTermCost;
   104388         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
   104389           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
   104390         ));
   104391         if( pOrTerm->eOperator==WO_AND ){
   104392           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
   104393           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
   104394         }else if( pOrTerm->leftCursor==iCur ){
   104395           WhereClause tempWC;
   104396           tempWC.pParse = pWC->pParse;
   104397           tempWC.pMaskSet = pWC->pMaskSet;
   104398           tempWC.pOuter = pWC;
   104399           tempWC.op = TK_AND;
   104400           tempWC.a = pOrTerm;
   104401           tempWC.wctrlFlags = 0;
   104402           tempWC.nTerm = 1;
   104403           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
   104404         }else{
   104405           continue;
   104406         }
   104407         rTotal += sTermCost.rCost;
   104408         nRow += sTermCost.plan.nRow;
   104409         used |= sTermCost.used;
   104410         if( rTotal>=pCost->rCost ) break;
   104411       }
   104412 
   104413       /* If there is an ORDER BY clause, increase the scan cost to account
   104414       ** for the cost of the sort. */
   104415       if( pOrderBy!=0 ){
   104416         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
   104417                     rTotal, rTotal+nRow*estLog(nRow)));
   104418         rTotal += nRow*estLog(nRow);
   104419       }
   104420 
   104421       /* If the cost of scanning using this OR term for optimization is
   104422       ** less than the current cost stored in pCost, replace the contents
   104423       ** of pCost. */
   104424       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
   104425       if( rTotal<pCost->rCost ){
   104426         pCost->rCost = rTotal;
   104427         pCost->used = used;
   104428         pCost->plan.nRow = nRow;
   104429         pCost->plan.wsFlags = flags;
   104430         pCost->plan.u.pTerm = pTerm;
   104431       }
   104432     }
   104433   }
   104434 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   104435 }
   104436 
   104437 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104438 /*
   104439 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   104440 ** could be used with an index to access pSrc, assuming an appropriate
   104441 ** index existed.
   104442 */
   104443 static int termCanDriveIndex(
   104444   WhereTerm *pTerm,              /* WHERE clause term to check */
   104445   struct SrcList_item *pSrc,     /* Table we are trying to access */
   104446   Bitmask notReady               /* Tables in outer loops of the join */
   104447 ){
   104448   char aff;
   104449   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   104450   if( pTerm->eOperator!=WO_EQ ) return 0;
   104451   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   104452   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   104453   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   104454   return 1;
   104455 }
   104456 #endif
   104457 
   104458 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104459 /*
   104460 ** If the query plan for pSrc specified in pCost is a full table scan
   104461 ** and indexing is allows (if there is no NOT INDEXED clause) and it
   104462 ** possible to construct a transient index that would perform better
   104463 ** than a full table scan even when the cost of constructing the index
   104464 ** is taken into account, then alter the query plan to use the
   104465 ** transient index.
   104466 */
   104467 static void bestAutomaticIndex(
   104468   Parse *pParse,              /* The parsing context */
   104469   WhereClause *pWC,           /* The WHERE clause */
   104470   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   104471   Bitmask notReady,           /* Mask of cursors that are not available */
   104472   WhereCost *pCost            /* Lowest cost query plan */
   104473 ){
   104474   double nTableRow;           /* Rows in the input table */
   104475   double logN;                /* log(nTableRow) */
   104476   double costTempIdx;         /* per-query cost of the transient index */
   104477   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   104478   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   104479   Table *pTable;              /* Table tht might be indexed */
   104480 
   104481   if( pParse->nQueryLoop<=(double)1 ){
   104482     /* There is no point in building an automatic index for a single scan */
   104483     return;
   104484   }
   104485   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
   104486     /* Automatic indices are disabled at run-time */
   104487     return;
   104488   }
   104489   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
   104490     /* We already have some kind of index in use for this query. */
   104491     return;
   104492   }
   104493   if( pSrc->notIndexed ){
   104494     /* The NOT INDEXED clause appears in the SQL. */
   104495     return;
   104496   }
   104497   if( pSrc->isCorrelated ){
   104498     /* The source is a correlated sub-query. No point in indexing it. */
   104499     return;
   104500   }
   104501 
   104502   assert( pParse->nQueryLoop >= (double)1 );
   104503   pTable = pSrc->pTab;
   104504   nTableRow = pTable->nRowEst;
   104505   logN = estLog(nTableRow);
   104506   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
   104507   if( costTempIdx>=pCost->rCost ){
   104508     /* The cost of creating the transient table would be greater than
   104509     ** doing the full table scan */
   104510     return;
   104511   }
   104512 
   104513   /* Search for any equality comparison term */
   104514   pWCEnd = &pWC->a[pWC->nTerm];
   104515   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104516     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104517       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
   104518                     pCost->rCost, costTempIdx));
   104519       pCost->rCost = costTempIdx;
   104520       pCost->plan.nRow = logN + 1;
   104521       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
   104522       pCost->used = pTerm->prereqRight;
   104523       break;
   104524     }
   104525   }
   104526 }
   104527 #else
   104528 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
   104529 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   104530 
   104531 
   104532 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   104533 /*
   104534 ** Generate code to construct the Index object for an automatic index
   104535 ** and to set up the WhereLevel object pLevel so that the code generator
   104536 ** makes use of the automatic index.
   104537 */
   104538 static void constructAutomaticIndex(
   104539   Parse *pParse,              /* The parsing context */
   104540   WhereClause *pWC,           /* The WHERE clause */
   104541   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   104542   Bitmask notReady,           /* Mask of cursors that are not available */
   104543   WhereLevel *pLevel          /* Write new index here */
   104544 ){
   104545   int nColumn;                /* Number of columns in the constructed index */
   104546   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   104547   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   104548   int nByte;                  /* Byte of memory needed for pIdx */
   104549   Index *pIdx;                /* Object describing the transient index */
   104550   Vdbe *v;                    /* Prepared statement under construction */
   104551   int addrInit;               /* Address of the initialization bypass jump */
   104552   Table *pTable;              /* The table being indexed */
   104553   KeyInfo *pKeyinfo;          /* Key information for the index */
   104554   int addrTop;                /* Top of the index fill loop */
   104555   int regRecord;              /* Register holding an index record */
   104556   int n;                      /* Column counter */
   104557   int i;                      /* Loop counter */
   104558   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   104559   CollSeq *pColl;             /* Collating sequence to on a column */
   104560   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   104561   Bitmask extraCols;          /* Bitmap of additional columns */
   104562 
   104563   /* Generate code to skip over the creation and initialization of the
   104564   ** transient index on 2nd and subsequent iterations of the loop. */
   104565   v = pParse->pVdbe;
   104566   assert( v!=0 );
   104567   addrInit = sqlite3CodeOnce(pParse);
   104568 
   104569   /* Count the number of columns that will be added to the index
   104570   ** and used to match WHERE clause constraints */
   104571   nColumn = 0;
   104572   pTable = pSrc->pTab;
   104573   pWCEnd = &pWC->a[pWC->nTerm];
   104574   idxCols = 0;
   104575   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104576     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104577       int iCol = pTerm->u.leftColumn;
   104578       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   104579       testcase( iCol==BMS );
   104580       testcase( iCol==BMS-1 );
   104581       if( (idxCols & cMask)==0 ){
   104582         nColumn++;
   104583         idxCols |= cMask;
   104584       }
   104585     }
   104586   }
   104587   assert( nColumn>0 );
   104588   pLevel->plan.nEq = nColumn;
   104589 
   104590   /* Count the number of additional columns needed to create a
   104591   ** covering index.  A "covering index" is an index that contains all
   104592   ** columns that are needed by the query.  With a covering index, the
   104593   ** original table never needs to be accessed.  Automatic indices must
   104594   ** be a covering index because the index will not be updated if the
   104595   ** original table changes and the index and table cannot both be used
   104596   ** if they go out of sync.
   104597   */
   104598   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
   104599   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
   104600   testcase( pTable->nCol==BMS-1 );
   104601   testcase( pTable->nCol==BMS-2 );
   104602   for(i=0; i<mxBitCol; i++){
   104603     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
   104604   }
   104605   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   104606     nColumn += pTable->nCol - BMS + 1;
   104607   }
   104608   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
   104609 
   104610   /* Construct the Index object to describe this index */
   104611   nByte = sizeof(Index);
   104612   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
   104613   nByte += nColumn*sizeof(char*);   /* Index.azColl */
   104614   nByte += nColumn;                 /* Index.aSortOrder */
   104615   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
   104616   if( pIdx==0 ) return;
   104617   pLevel->plan.u.pIdx = pIdx;
   104618   pIdx->azColl = (char**)&pIdx[1];
   104619   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
   104620   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
   104621   pIdx->zName = "auto-index";
   104622   pIdx->nColumn = nColumn;
   104623   pIdx->pTable = pTable;
   104624   n = 0;
   104625   idxCols = 0;
   104626   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   104627     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   104628       int iCol = pTerm->u.leftColumn;
   104629       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   104630       if( (idxCols & cMask)==0 ){
   104631         Expr *pX = pTerm->pExpr;
   104632         idxCols |= cMask;
   104633         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   104634         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   104635         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
   104636         n++;
   104637       }
   104638     }
   104639   }
   104640   assert( (u32)n==pLevel->plan.nEq );
   104641 
   104642   /* Add additional columns needed to make the automatic index into
   104643   ** a covering index */
   104644   for(i=0; i<mxBitCol; i++){
   104645     if( extraCols & (((Bitmask)1)<<i) ){
   104646       pIdx->aiColumn[n] = i;
   104647       pIdx->azColl[n] = "BINARY";
   104648       n++;
   104649     }
   104650   }
   104651   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   104652     for(i=BMS-1; i<pTable->nCol; i++){
   104653       pIdx->aiColumn[n] = i;
   104654       pIdx->azColl[n] = "BINARY";
   104655       n++;
   104656     }
   104657   }
   104658   assert( n==nColumn );
   104659 
   104660   /* Create the automatic index */
   104661   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
   104662   assert( pLevel->iIdxCur>=0 );
   104663   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
   104664                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
   104665   VdbeComment((v, "for %s", pTable->zName));
   104666 
   104667   /* Fill the automatic index with content */
   104668   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
   104669   regRecord = sqlite3GetTempReg(pParse);
   104670   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
   104671   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   104672   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   104673   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
   104674   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   104675   sqlite3VdbeJumpHere(v, addrTop);
   104676   sqlite3ReleaseTempReg(pParse, regRecord);
   104677 
   104678   /* Jump here when skipping the initialization */
   104679   sqlite3VdbeJumpHere(v, addrInit);
   104680 }
   104681 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   104682 
   104683 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104684 /*
   104685 ** Allocate and populate an sqlite3_index_info structure. It is the
   104686 ** responsibility of the caller to eventually release the structure
   104687 ** by passing the pointer returned by this function to sqlite3_free().
   104688 */
   104689 static sqlite3_index_info *allocateIndexInfo(
   104690   Parse *pParse,
   104691   WhereClause *pWC,
   104692   struct SrcList_item *pSrc,
   104693   ExprList *pOrderBy
   104694 ){
   104695   int i, j;
   104696   int nTerm;
   104697   struct sqlite3_index_constraint *pIdxCons;
   104698   struct sqlite3_index_orderby *pIdxOrderBy;
   104699   struct sqlite3_index_constraint_usage *pUsage;
   104700   WhereTerm *pTerm;
   104701   int nOrderBy;
   104702   sqlite3_index_info *pIdxInfo;
   104703 
   104704   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
   104705 
   104706   /* Count the number of possible WHERE clause constraints referring
   104707   ** to this virtual table */
   104708   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   104709     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   104710     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   104711     testcase( pTerm->eOperator==WO_IN );
   104712     testcase( pTerm->eOperator==WO_ISNULL );
   104713     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   104714     if( pTerm->wtFlags & TERM_VNULL ) continue;
   104715     nTerm++;
   104716   }
   104717 
   104718   /* If the ORDER BY clause contains only columns in the current
   104719   ** virtual table then allocate space for the aOrderBy part of
   104720   ** the sqlite3_index_info structure.
   104721   */
   104722   nOrderBy = 0;
   104723   if( pOrderBy ){
   104724     for(i=0; i<pOrderBy->nExpr; i++){
   104725       Expr *pExpr = pOrderBy->a[i].pExpr;
   104726       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   104727     }
   104728     if( i==pOrderBy->nExpr ){
   104729       nOrderBy = pOrderBy->nExpr;
   104730     }
   104731   }
   104732 
   104733   /* Allocate the sqlite3_index_info structure
   104734   */
   104735   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   104736                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   104737                            + sizeof(*pIdxOrderBy)*nOrderBy );
   104738   if( pIdxInfo==0 ){
   104739     sqlite3ErrorMsg(pParse, "out of memory");
   104740     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   104741     return 0;
   104742   }
   104743 
   104744   /* Initialize the structure.  The sqlite3_index_info structure contains
   104745   ** many fields that are declared "const" to prevent xBestIndex from
   104746   ** changing them.  We have to do some funky casting in order to
   104747   ** initialize those fields.
   104748   */
   104749   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   104750   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   104751   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   104752   *(int*)&pIdxInfo->nConstraint = nTerm;
   104753   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   104754   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   104755   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   104756   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   104757                                                                    pUsage;
   104758 
   104759   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   104760     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   104761     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   104762     testcase( pTerm->eOperator==WO_IN );
   104763     testcase( pTerm->eOperator==WO_ISNULL );
   104764     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   104765     if( pTerm->wtFlags & TERM_VNULL ) continue;
   104766     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   104767     pIdxCons[j].iTermOffset = i;
   104768     pIdxCons[j].op = (u8)pTerm->eOperator;
   104769     /* The direct assignment in the previous line is possible only because
   104770     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   104771     ** following asserts verify this fact. */
   104772     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   104773     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   104774     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   104775     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   104776     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   104777     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   104778     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   104779     j++;
   104780   }
   104781   for(i=0; i<nOrderBy; i++){
   104782     Expr *pExpr = pOrderBy->a[i].pExpr;
   104783     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   104784     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   104785   }
   104786 
   104787   return pIdxInfo;
   104788 }
   104789 
   104790 /*
   104791 ** The table object reference passed as the second argument to this function
   104792 ** must represent a virtual table. This function invokes the xBestIndex()
   104793 ** method of the virtual table with the sqlite3_index_info pointer passed
   104794 ** as the argument.
   104795 **
   104796 ** If an error occurs, pParse is populated with an error message and a
   104797 ** non-zero value is returned. Otherwise, 0 is returned and the output
   104798 ** part of the sqlite3_index_info structure is left populated.
   104799 **
   104800 ** Whether or not an error is returned, it is the responsibility of the
   104801 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   104802 ** that this is required.
   104803 */
   104804 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   104805   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   104806   int i;
   104807   int rc;
   104808 
   104809   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
   104810   TRACE_IDX_INPUTS(p);
   104811   rc = pVtab->pModule->xBestIndex(pVtab, p);
   104812   TRACE_IDX_OUTPUTS(p);
   104813 
   104814   if( rc!=SQLITE_OK ){
   104815     if( rc==SQLITE_NOMEM ){
   104816       pParse->db->mallocFailed = 1;
   104817     }else if( !pVtab->zErrMsg ){
   104818       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   104819     }else{
   104820       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   104821     }
   104822   }
   104823   sqlite3_free(pVtab->zErrMsg);
   104824   pVtab->zErrMsg = 0;
   104825 
   104826   for(i=0; i<p->nConstraint; i++){
   104827     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   104828       sqlite3ErrorMsg(pParse,
   104829           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   104830     }
   104831   }
   104832 
   104833   return pParse->nErr;
   104834 }
   104835 
   104836 
   104837 /*
   104838 ** Compute the best index for a virtual table.
   104839 **
   104840 ** The best index is computed by the xBestIndex method of the virtual
   104841 ** table module.  This routine is really just a wrapper that sets up
   104842 ** the sqlite3_index_info structure that is used to communicate with
   104843 ** xBestIndex.
   104844 **
   104845 ** In a join, this routine might be called multiple times for the
   104846 ** same virtual table.  The sqlite3_index_info structure is created
   104847 ** and initialized on the first invocation and reused on all subsequent
   104848 ** invocations.  The sqlite3_index_info structure is also used when
   104849 ** code is generated to access the virtual table.  The whereInfoDelete()
   104850 ** routine takes care of freeing the sqlite3_index_info structure after
   104851 ** everybody has finished with it.
   104852 */
   104853 static void bestVirtualIndex(
   104854   Parse *pParse,                  /* The parsing context */
   104855   WhereClause *pWC,               /* The WHERE clause */
   104856   struct SrcList_item *pSrc,      /* The FROM clause term to search */
   104857   Bitmask notReady,               /* Mask of cursors not available for index */
   104858   Bitmask notValid,               /* Cursors not valid for any purpose */
   104859   ExprList *pOrderBy,             /* The order by clause */
   104860   WhereCost *pCost,               /* Lowest cost query plan */
   104861   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
   104862 ){
   104863   Table *pTab = pSrc->pTab;
   104864   sqlite3_index_info *pIdxInfo;
   104865   struct sqlite3_index_constraint *pIdxCons;
   104866   struct sqlite3_index_constraint_usage *pUsage;
   104867   WhereTerm *pTerm;
   104868   int i, j;
   104869   int nOrderBy;
   104870   double rCost;
   104871 
   104872   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
   104873   ** malloc in allocateIndexInfo() fails and this function returns leaving
   104874   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
   104875   */
   104876   memset(pCost, 0, sizeof(*pCost));
   104877   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
   104878 
   104879   /* If the sqlite3_index_info structure has not been previously
   104880   ** allocated and initialized, then allocate and initialize it now.
   104881   */
   104882   pIdxInfo = *ppIdxInfo;
   104883   if( pIdxInfo==0 ){
   104884     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
   104885   }
   104886   if( pIdxInfo==0 ){
   104887     return;
   104888   }
   104889 
   104890   /* At this point, the sqlite3_index_info structure that pIdxInfo points
   104891   ** to will have been initialized, either during the current invocation or
   104892   ** during some prior invocation.  Now we just have to customize the
   104893   ** details of pIdxInfo for the current invocation and pass it to
   104894   ** xBestIndex.
   104895   */
   104896 
   104897   /* The module name must be defined. Also, by this point there must
   104898   ** be a pointer to an sqlite3_vtab structure. Otherwise
   104899   ** sqlite3ViewGetColumnNames() would have picked up the error.
   104900   */
   104901   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
   104902   assert( sqlite3GetVTable(pParse->db, pTab) );
   104903 
   104904   /* Set the aConstraint[].usable fields and initialize all
   104905   ** output variables to zero.
   104906   **
   104907   ** aConstraint[].usable is true for constraints where the right-hand
   104908   ** side contains only references to tables to the left of the current
   104909   ** table.  In other words, if the constraint is of the form:
   104910   **
   104911   **           column = expr
   104912   **
   104913   ** and we are evaluating a join, then the constraint on column is
   104914   ** only valid if all tables referenced in expr occur to the left
   104915   ** of the table containing column.
   104916   **
   104917   ** The aConstraints[] array contains entries for all constraints
   104918   ** on the current table.  That way we only have to compute it once
   104919   ** even though we might try to pick the best index multiple times.
   104920   ** For each attempt at picking an index, the order of tables in the
   104921   ** join might be different so we have to recompute the usable flag
   104922   ** each time.
   104923   */
   104924   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   104925   pUsage = pIdxInfo->aConstraintUsage;
   104926   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   104927     j = pIdxCons->iTermOffset;
   104928     pTerm = &pWC->a[j];
   104929     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
   104930   }
   104931   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   104932   if( pIdxInfo->needToFreeIdxStr ){
   104933     sqlite3_free(pIdxInfo->idxStr);
   104934   }
   104935   pIdxInfo->idxStr = 0;
   104936   pIdxInfo->idxNum = 0;
   104937   pIdxInfo->needToFreeIdxStr = 0;
   104938   pIdxInfo->orderByConsumed = 0;
   104939   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
   104940   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
   104941   nOrderBy = pIdxInfo->nOrderBy;
   104942   if( !pOrderBy ){
   104943     pIdxInfo->nOrderBy = 0;
   104944   }
   104945 
   104946   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
   104947     return;
   104948   }
   104949 
   104950   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   104951   for(i=0; i<pIdxInfo->nConstraint; i++){
   104952     if( pUsage[i].argvIndex>0 ){
   104953       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
   104954     }
   104955   }
   104956 
   104957   /* If there is an ORDER BY clause, and the selected virtual table index
   104958   ** does not satisfy it, increase the cost of the scan accordingly. This
   104959   ** matches the processing for non-virtual tables in bestBtreeIndex().
   104960   */
   104961   rCost = pIdxInfo->estimatedCost;
   104962   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
   104963     rCost += estLog(rCost)*rCost;
   104964   }
   104965 
   104966   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
   104967   ** inital value of lowestCost in this loop. If it is, then the
   104968   ** (cost<lowestCost) test below will never be true.
   104969   **
   104970   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
   104971   ** is defined.
   104972   */
   104973   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
   104974     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
   104975   }else{
   104976     pCost->rCost = rCost;
   104977   }
   104978   pCost->plan.u.pVtabIdx = pIdxInfo;
   104979   if( pIdxInfo->orderByConsumed ){
   104980     pCost->plan.wsFlags |= WHERE_ORDERBY;
   104981   }
   104982   pCost->plan.nEq = 0;
   104983   pIdxInfo->nOrderBy = nOrderBy;
   104984 
   104985   /* Try to find a more efficient access pattern by using multiple indexes
   104986   ** to optimize an OR expression within the WHERE clause.
   104987   */
   104988   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   104989 }
   104990 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   104991 
   104992 #ifdef SQLITE_ENABLE_STAT3
   104993 /*
   104994 ** Estimate the location of a particular key among all keys in an
   104995 ** index.  Store the results in aStat as follows:
   104996 **
   104997 **    aStat[0]      Est. number of rows less than pVal
   104998 **    aStat[1]      Est. number of rows equal to pVal
   104999 **
   105000 ** Return SQLITE_OK on success.
   105001 */
   105002 static int whereKeyStats(
   105003   Parse *pParse,              /* Database connection */
   105004   Index *pIdx,                /* Index to consider domain of */
   105005   sqlite3_value *pVal,        /* Value to consider */
   105006   int roundUp,                /* Round up if true.  Round down if false */
   105007   tRowcnt *aStat              /* OUT: stats written here */
   105008 ){
   105009   tRowcnt n;
   105010   IndexSample *aSample;
   105011   int i, eType;
   105012   int isEq = 0;
   105013   i64 v;
   105014   double r, rS;
   105015 
   105016   assert( roundUp==0 || roundUp==1 );
   105017   assert( pIdx->nSample>0 );
   105018   if( pVal==0 ) return SQLITE_ERROR;
   105019   n = pIdx->aiRowEst[0];
   105020   aSample = pIdx->aSample;
   105021   eType = sqlite3_value_type(pVal);
   105022 
   105023   if( eType==SQLITE_INTEGER ){
   105024     v = sqlite3_value_int64(pVal);
   105025     r = (i64)v;
   105026     for(i=0; i<pIdx->nSample; i++){
   105027       if( aSample[i].eType==SQLITE_NULL ) continue;
   105028       if( aSample[i].eType>=SQLITE_TEXT ) break;
   105029       if( aSample[i].eType==SQLITE_INTEGER ){
   105030         if( aSample[i].u.i>=v ){
   105031           isEq = aSample[i].u.i==v;
   105032           break;
   105033         }
   105034       }else{
   105035         assert( aSample[i].eType==SQLITE_FLOAT );
   105036         if( aSample[i].u.r>=r ){
   105037           isEq = aSample[i].u.r==r;
   105038           break;
   105039         }
   105040       }
   105041     }
   105042   }else if( eType==SQLITE_FLOAT ){
   105043     r = sqlite3_value_double(pVal);
   105044     for(i=0; i<pIdx->nSample; i++){
   105045       if( aSample[i].eType==SQLITE_NULL ) continue;
   105046       if( aSample[i].eType>=SQLITE_TEXT ) break;
   105047       if( aSample[i].eType==SQLITE_FLOAT ){
   105048         rS = aSample[i].u.r;
   105049       }else{
   105050         rS = aSample[i].u.i;
   105051       }
   105052       if( rS>=r ){
   105053         isEq = rS==r;
   105054         break;
   105055       }
   105056     }
   105057   }else if( eType==SQLITE_NULL ){
   105058     i = 0;
   105059     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
   105060   }else{
   105061     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   105062     for(i=0; i<pIdx->nSample; i++){
   105063       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
   105064         break;
   105065       }
   105066     }
   105067     if( i<pIdx->nSample ){
   105068       sqlite3 *db = pParse->db;
   105069       CollSeq *pColl;
   105070       const u8 *z;
   105071       if( eType==SQLITE_BLOB ){
   105072         z = (const u8 *)sqlite3_value_blob(pVal);
   105073         pColl = db->pDfltColl;
   105074         assert( pColl->enc==SQLITE_UTF8 );
   105075       }else{
   105076         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
   105077         if( pColl==0 ){
   105078           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
   105079                           *pIdx->azColl);
   105080           return SQLITE_ERROR;
   105081         }
   105082         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
   105083         if( !z ){
   105084           return SQLITE_NOMEM;
   105085         }
   105086         assert( z && pColl && pColl->xCmp );
   105087       }
   105088       n = sqlite3ValueBytes(pVal, pColl->enc);
   105089 
   105090       for(; i<pIdx->nSample; i++){
   105091         int c;
   105092         int eSampletype = aSample[i].eType;
   105093         if( eSampletype<eType ) continue;
   105094         if( eSampletype!=eType ) break;
   105095 #ifndef SQLITE_OMIT_UTF16
   105096         if( pColl->enc!=SQLITE_UTF8 ){
   105097           int nSample;
   105098           char *zSample = sqlite3Utf8to16(
   105099               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
   105100           );
   105101           if( !zSample ){
   105102             assert( db->mallocFailed );
   105103             return SQLITE_NOMEM;
   105104           }
   105105           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
   105106           sqlite3DbFree(db, zSample);
   105107         }else
   105108 #endif
   105109         {
   105110           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
   105111         }
   105112         if( c>=0 ){
   105113           if( c==0 ) isEq = 1;
   105114           break;
   105115         }
   105116       }
   105117     }
   105118   }
   105119 
   105120   /* At this point, aSample[i] is the first sample that is greater than
   105121   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
   105122   ** than pVal.  If aSample[i]==pVal, then isEq==1.
   105123   */
   105124   if( isEq ){
   105125     assert( i<pIdx->nSample );
   105126     aStat[0] = aSample[i].nLt;
   105127     aStat[1] = aSample[i].nEq;
   105128   }else{
   105129     tRowcnt iLower, iUpper, iGap;
   105130     if( i==0 ){
   105131       iLower = 0;
   105132       iUpper = aSample[0].nLt;
   105133     }else{
   105134       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
   105135       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
   105136     }
   105137     aStat[1] = pIdx->avgEq;
   105138     if( iLower>=iUpper ){
   105139       iGap = 0;
   105140     }else{
   105141       iGap = iUpper - iLower;
   105142     }
   105143     if( roundUp ){
   105144       iGap = (iGap*2)/3;
   105145     }else{
   105146       iGap = iGap/3;
   105147     }
   105148     aStat[0] = iLower + iGap;
   105149   }
   105150   return SQLITE_OK;
   105151 }
   105152 #endif /* SQLITE_ENABLE_STAT3 */
   105153 
   105154 /*
   105155 ** If expression pExpr represents a literal value, set *pp to point to
   105156 ** an sqlite3_value structure containing the same value, with affinity
   105157 ** aff applied to it, before returning. It is the responsibility of the
   105158 ** caller to eventually release this structure by passing it to
   105159 ** sqlite3ValueFree().
   105160 **
   105161 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
   105162 ** is an SQL variable that currently has a non-NULL value bound to it,
   105163 ** create an sqlite3_value structure containing this value, again with
   105164 ** affinity aff applied to it, instead.
   105165 **
   105166 ** If neither of the above apply, set *pp to NULL.
   105167 **
   105168 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
   105169 */
   105170 #ifdef SQLITE_ENABLE_STAT3
   105171 static int valueFromExpr(
   105172   Parse *pParse,
   105173   Expr *pExpr,
   105174   u8 aff,
   105175   sqlite3_value **pp
   105176 ){
   105177   if( pExpr->op==TK_VARIABLE
   105178    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
   105179   ){
   105180     int iVar = pExpr->iColumn;
   105181     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
   105182     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
   105183     return SQLITE_OK;
   105184   }
   105185   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
   105186 }
   105187 #endif
   105188 
   105189 /*
   105190 ** This function is used to estimate the number of rows that will be visited
   105191 ** by scanning an index for a range of values. The range may have an upper
   105192 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   105193 ** and lower bounds are represented by pLower and pUpper respectively. For
   105194 ** example, assuming that index p is on t1(a):
   105195 **
   105196 **   ... FROM t1 WHERE a > ? AND a < ? ...
   105197 **                    |_____|   |_____|
   105198 **                       |         |
   105199 **                     pLower    pUpper
   105200 **
   105201 ** If either of the upper or lower bound is not present, then NULL is passed in
   105202 ** place of the corresponding WhereTerm.
   105203 **
   105204 ** The nEq parameter is passed the index of the index column subject to the
   105205 ** range constraint. Or, equivalently, the number of equality constraints
   105206 ** optimized by the proposed index scan. For example, assuming index p is
   105207 ** on t1(a, b), and the SQL query is:
   105208 **
   105209 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   105210 **
   105211 ** then nEq should be passed the value 1 (as the range restricted column,
   105212 ** b, is the second left-most column of the index). Or, if the query is:
   105213 **
   105214 **   ... FROM t1 WHERE a > ? AND a < ? ...
   105215 **
   105216 ** then nEq should be passed 0.
   105217 **
   105218 ** The returned value is an integer divisor to reduce the estimated
   105219 ** search space.  A return value of 1 means that range constraints are
   105220 ** no help at all.  A return value of 2 means range constraints are
   105221 ** expected to reduce the search space by half.  And so forth...
   105222 **
   105223 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
   105224 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
   105225 ** results in a return of 4 and a range constraint (x>? AND x<?) results
   105226 ** in a return of 16.
   105227 */
   105228 static int whereRangeScanEst(
   105229   Parse *pParse,       /* Parsing & code generating context */
   105230   Index *p,            /* The index containing the range-compared column; "x" */
   105231   int nEq,             /* index into p->aCol[] of the range-compared column */
   105232   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   105233   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   105234   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
   105235 ){
   105236   int rc = SQLITE_OK;
   105237 
   105238 #ifdef SQLITE_ENABLE_STAT3
   105239 
   105240   if( nEq==0 && p->nSample ){
   105241     sqlite3_value *pRangeVal;
   105242     tRowcnt iLower = 0;
   105243     tRowcnt iUpper = p->aiRowEst[0];
   105244     tRowcnt a[2];
   105245     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   105246 
   105247     if( pLower ){
   105248       Expr *pExpr = pLower->pExpr->pRight;
   105249       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
   105250       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
   105251       if( rc==SQLITE_OK
   105252        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
   105253       ){
   105254         iLower = a[0];
   105255         if( pLower->eOperator==WO_GT ) iLower += a[1];
   105256       }
   105257       sqlite3ValueFree(pRangeVal);
   105258     }
   105259     if( rc==SQLITE_OK && pUpper ){
   105260       Expr *pExpr = pUpper->pExpr->pRight;
   105261       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
   105262       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
   105263       if( rc==SQLITE_OK
   105264        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
   105265       ){
   105266         iUpper = a[0];
   105267         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
   105268       }
   105269       sqlite3ValueFree(pRangeVal);
   105270     }
   105271     if( rc==SQLITE_OK ){
   105272       if( iUpper<=iLower ){
   105273         *pRangeDiv = (double)p->aiRowEst[0];
   105274       }else{
   105275         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
   105276       }
   105277       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
   105278                   (u32)iLower, (u32)iUpper, *pRangeDiv));
   105279       return SQLITE_OK;
   105280     }
   105281   }
   105282 #else
   105283   UNUSED_PARAMETER(pParse);
   105284   UNUSED_PARAMETER(p);
   105285   UNUSED_PARAMETER(nEq);
   105286 #endif
   105287   assert( pLower || pUpper );
   105288   *pRangeDiv = (double)1;
   105289   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
   105290   if( pUpper ) *pRangeDiv *= (double)4;
   105291   return rc;
   105292 }
   105293 
   105294 #ifdef SQLITE_ENABLE_STAT3
   105295 /*
   105296 ** Estimate the number of rows that will be returned based on
   105297 ** an equality constraint x=VALUE and where that VALUE occurs in
   105298 ** the histogram data.  This only works when x is the left-most
   105299 ** column of an index and sqlite_stat3 histogram data is available
   105300 ** for that index.  When pExpr==NULL that means the constraint is
   105301 ** "x IS NULL" instead of "x=VALUE".
   105302 **
   105303 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   105304 ** If unable to make an estimate, leave *pnRow unchanged and return
   105305 ** non-zero.
   105306 **
   105307 ** This routine can fail if it is unable to load a collating sequence
   105308 ** required for string comparison, or if unable to allocate memory
   105309 ** for a UTF conversion required for comparison.  The error is stored
   105310 ** in the pParse structure.
   105311 */
   105312 static int whereEqualScanEst(
   105313   Parse *pParse,       /* Parsing & code generating context */
   105314   Index *p,            /* The index whose left-most column is pTerm */
   105315   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
   105316   double *pnRow        /* Write the revised row estimate here */
   105317 ){
   105318   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
   105319   u8 aff;                   /* Column affinity */
   105320   int rc;                   /* Subfunction return code */
   105321   tRowcnt a[2];             /* Statistics */
   105322 
   105323   assert( p->aSample!=0 );
   105324   assert( p->nSample>0 );
   105325   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   105326   if( pExpr ){
   105327     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
   105328     if( rc ) goto whereEqualScanEst_cancel;
   105329   }else{
   105330     pRhs = sqlite3ValueNew(pParse->db);
   105331   }
   105332   if( pRhs==0 ) return SQLITE_NOTFOUND;
   105333   rc = whereKeyStats(pParse, p, pRhs, 0, a);
   105334   if( rc==SQLITE_OK ){
   105335     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
   105336     *pnRow = a[1];
   105337   }
   105338 whereEqualScanEst_cancel:
   105339   sqlite3ValueFree(pRhs);
   105340   return rc;
   105341 }
   105342 #endif /* defined(SQLITE_ENABLE_STAT3) */
   105343 
   105344 #ifdef SQLITE_ENABLE_STAT3
   105345 /*
   105346 ** Estimate the number of rows that will be returned based on
   105347 ** an IN constraint where the right-hand side of the IN operator
   105348 ** is a list of values.  Example:
   105349 **
   105350 **        WHERE x IN (1,2,3,4)
   105351 **
   105352 ** Write the estimated row count into *pnRow and return SQLITE_OK.
   105353 ** If unable to make an estimate, leave *pnRow unchanged and return
   105354 ** non-zero.
   105355 **
   105356 ** This routine can fail if it is unable to load a collating sequence
   105357 ** required for string comparison, or if unable to allocate memory
   105358 ** for a UTF conversion required for comparison.  The error is stored
   105359 ** in the pParse structure.
   105360 */
   105361 static int whereInScanEst(
   105362   Parse *pParse,       /* Parsing & code generating context */
   105363   Index *p,            /* The index whose left-most column is pTerm */
   105364   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
   105365   double *pnRow        /* Write the revised row estimate here */
   105366 ){
   105367   int rc = SQLITE_OK;         /* Subfunction return code */
   105368   double nEst;                /* Number of rows for a single term */
   105369   double nRowEst = (double)0; /* New estimate of the number of rows */
   105370   int i;                      /* Loop counter */
   105371 
   105372   assert( p->aSample!=0 );
   105373   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
   105374     nEst = p->aiRowEst[0];
   105375     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
   105376     nRowEst += nEst;
   105377   }
   105378   if( rc==SQLITE_OK ){
   105379     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
   105380     *pnRow = nRowEst;
   105381     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
   105382   }
   105383   return rc;
   105384 }
   105385 #endif /* defined(SQLITE_ENABLE_STAT3) */
   105386 
   105387 
   105388 /*
   105389 ** Find the best query plan for accessing a particular table.  Write the
   105390 ** best query plan and its cost into the WhereCost object supplied as the
   105391 ** last parameter.
   105392 **
   105393 ** The lowest cost plan wins.  The cost is an estimate of the amount of
   105394 ** CPU and disk I/O needed to process the requested result.
   105395 ** Factors that influence cost include:
   105396 **
   105397 **    *  The estimated number of rows that will be retrieved.  (The
   105398 **       fewer the better.)
   105399 **
   105400 **    *  Whether or not sorting must occur.
   105401 **
   105402 **    *  Whether or not there must be separate lookups in the
   105403 **       index and in the main table.
   105404 **
   105405 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
   105406 ** the SQL statement, then this function only considers plans using the
   105407 ** named index. If no such plan is found, then the returned cost is
   105408 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
   105409 ** then the cost is calculated in the usual way.
   105410 **
   105411 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
   105412 ** in the SELECT statement, then no indexes are considered. However, the
   105413 ** selected plan may still take advantage of the built-in rowid primary key
   105414 ** index.
   105415 */
   105416 static void bestBtreeIndex(
   105417   Parse *pParse,              /* The parsing context */
   105418   WhereClause *pWC,           /* The WHERE clause */
   105419   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   105420   Bitmask notReady,           /* Mask of cursors not available for indexing */
   105421   Bitmask notValid,           /* Cursors not available for any purpose */
   105422   ExprList *pOrderBy,         /* The ORDER BY clause */
   105423   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
   105424   WhereCost *pCost            /* Lowest cost query plan */
   105425 ){
   105426   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   105427   Index *pProbe;              /* An index we are evaluating */
   105428   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
   105429   int eqTermMask;             /* Current mask of valid equality operators */
   105430   int idxEqTermMask;          /* Index mask of valid equality operators */
   105431   Index sPk;                  /* A fake index object for the primary key */
   105432   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
   105433   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   105434   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
   105435 
   105436   /* Initialize the cost to a worst-case value */
   105437   memset(pCost, 0, sizeof(*pCost));
   105438   pCost->rCost = SQLITE_BIG_DBL;
   105439 
   105440   /* If the pSrc table is the right table of a LEFT JOIN then we may not
   105441   ** use an index to satisfy IS NULL constraints on that table.  This is
   105442   ** because columns might end up being NULL if the table does not match -
   105443   ** a circumstance which the index cannot help us discover.  Ticket #2177.
   105444   */
   105445   if( pSrc->jointype & JT_LEFT ){
   105446     idxEqTermMask = WO_EQ|WO_IN;
   105447   }else{
   105448     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
   105449   }
   105450 
   105451   if( pSrc->pIndex ){
   105452     /* An INDEXED BY clause specifies a particular index to use */
   105453     pIdx = pProbe = pSrc->pIndex;
   105454     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   105455     eqTermMask = idxEqTermMask;
   105456   }else{
   105457     /* There is no INDEXED BY clause.  Create a fake Index object in local
   105458     ** variable sPk to represent the rowid primary key index.  Make this
   105459     ** fake index the first in a chain of Index objects with all of the real
   105460     ** indices to follow */
   105461     Index *pFirst;                  /* First of real indices on the table */
   105462     memset(&sPk, 0, sizeof(Index));
   105463     sPk.nColumn = 1;
   105464     sPk.aiColumn = &aiColumnPk;
   105465     sPk.aiRowEst = aiRowEstPk;
   105466     sPk.onError = OE_Replace;
   105467     sPk.pTable = pSrc->pTab;
   105468     aiRowEstPk[0] = pSrc->pTab->nRowEst;
   105469     aiRowEstPk[1] = 1;
   105470     pFirst = pSrc->pTab->pIndex;
   105471     if( pSrc->notIndexed==0 ){
   105472       /* The real indices of the table are only considered if the
   105473       ** NOT INDEXED qualifier is omitted from the FROM clause */
   105474       sPk.pNext = pFirst;
   105475     }
   105476     pProbe = &sPk;
   105477     wsFlagMask = ~(
   105478         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
   105479     );
   105480     eqTermMask = WO_EQ|WO_IN;
   105481     pIdx = 0;
   105482   }
   105483 
   105484   /* Loop over all indices looking for the best one to use
   105485   */
   105486   for(; pProbe; pIdx=pProbe=pProbe->pNext){
   105487     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
   105488     double cost;                /* Cost of using pProbe */
   105489     double nRow;                /* Estimated number of rows in result set */
   105490     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
   105491     int rev;                    /* True to scan in reverse order */
   105492     int wsFlags = 0;
   105493     Bitmask used = 0;
   105494 
   105495     /* The following variables are populated based on the properties of
   105496     ** index being evaluated. They are then used to determine the expected
   105497     ** cost and number of rows returned.
   105498     **
   105499     **  nEq:
   105500     **    Number of equality terms that can be implemented using the index.
   105501     **    In other words, the number of initial fields in the index that
   105502     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
   105503     **
   105504     **  nInMul:
   105505     **    The "in-multiplier". This is an estimate of how many seek operations
   105506     **    SQLite must perform on the index in question. For example, if the
   105507     **    WHERE clause is:
   105508     **
   105509     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
   105510     **
   105511     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
   105512     **    set to 9. Given the same schema and either of the following WHERE
   105513     **    clauses:
   105514     **
   105515     **      WHERE a =  1
   105516     **      WHERE a >= 2
   105517     **
   105518     **    nInMul is set to 1.
   105519     **
   105520     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
   105521     **    the sub-select is assumed to return 25 rows for the purposes of
   105522     **    determining nInMul.
   105523     **
   105524     **  bInEst:
   105525     **    Set to true if there was at least one "x IN (SELECT ...)" term used
   105526     **    in determining the value of nInMul.  Note that the RHS of the
   105527     **    IN operator must be a SELECT, not a value list, for this variable
   105528     **    to be true.
   105529     **
   105530     **  rangeDiv:
   105531     **    An estimate of a divisor by which to reduce the search space due
   105532     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
   105533     **    data, a single inequality reduces the search space to 1/4rd its
   105534     **    original size (rangeDiv==4).  Two inequalities reduce the search
   105535     **    space to 1/16th of its original size (rangeDiv==16).
   105536     **
   105537     **  bSort:
   105538     **    Boolean. True if there is an ORDER BY clause that will require an
   105539     **    external sort (i.e. scanning the index being evaluated will not
   105540     **    correctly order records).
   105541     **
   105542     **  bLookup:
   105543     **    Boolean. True if a table lookup is required for each index entry
   105544     **    visited.  In other words, true if this is not a covering index.
   105545     **    This is always false for the rowid primary key index of a table.
   105546     **    For other indexes, it is true unless all the columns of the table
   105547     **    used by the SELECT statement are present in the index (such an
   105548     **    index is sometimes described as a covering index).
   105549     **    For example, given the index on (a, b), the second of the following
   105550     **    two queries requires table b-tree lookups in order to find the value
   105551     **    of column c, but the first does not because columns a and b are
   105552     **    both available in the index.
   105553     **
   105554     **             SELECT a, b    FROM tbl WHERE a = 1;
   105555     **             SELECT a, b, c FROM tbl WHERE a = 1;
   105556     */
   105557     int nEq;                      /* Number of == or IN terms matching index */
   105558     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
   105559     int nInMul = 1;               /* Number of distinct equalities to lookup */
   105560     double rangeDiv = (double)1;  /* Estimated reduction in search space */
   105561     int nBound = 0;               /* Number of range constraints seen */
   105562     int bSort = !!pOrderBy;       /* True if external sort required */
   105563     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
   105564     int bLookup = 0;              /* True if not a covering index */
   105565     WhereTerm *pTerm;             /* A single term of the WHERE clause */
   105566 #ifdef SQLITE_ENABLE_STAT3
   105567     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
   105568 #endif
   105569 
   105570     /* Determine the values of nEq and nInMul */
   105571     for(nEq=0; nEq<pProbe->nColumn; nEq++){
   105572       int j = pProbe->aiColumn[nEq];
   105573       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
   105574       if( pTerm==0 ) break;
   105575       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
   105576       testcase( pTerm->pWC!=pWC );
   105577       if( pTerm->eOperator & WO_IN ){
   105578         Expr *pExpr = pTerm->pExpr;
   105579         wsFlags |= WHERE_COLUMN_IN;
   105580         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   105581           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
   105582           nInMul *= 25;
   105583           bInEst = 1;
   105584         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
   105585           /* "x IN (value, value, ...)" */
   105586           nInMul *= pExpr->x.pList->nExpr;
   105587         }
   105588       }else if( pTerm->eOperator & WO_ISNULL ){
   105589         wsFlags |= WHERE_COLUMN_NULL;
   105590       }
   105591 #ifdef SQLITE_ENABLE_STAT3
   105592       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
   105593 #endif
   105594       used |= pTerm->prereqRight;
   105595     }
   105596 
   105597     /* If the index being considered is UNIQUE, and there is an equality
   105598     ** constraint for all columns in the index, then this search will find
   105599     ** at most a single row. In this case set the WHERE_UNIQUE flag to
   105600     ** indicate this to the caller.
   105601     **
   105602     ** Otherwise, if the search may find more than one row, test to see if
   105603     ** there is a range constraint on indexed column (nEq+1) that can be
   105604     ** optimized using the index.
   105605     */
   105606     if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
   105607       testcase( wsFlags & WHERE_COLUMN_IN );
   105608       testcase( wsFlags & WHERE_COLUMN_NULL );
   105609       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
   105610         wsFlags |= WHERE_UNIQUE;
   105611       }
   105612     }else if( pProbe->bUnordered==0 ){
   105613       int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
   105614       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
   105615         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
   105616         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
   105617         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
   105618         if( pTop ){
   105619           nBound = 1;
   105620           wsFlags |= WHERE_TOP_LIMIT;
   105621           used |= pTop->prereqRight;
   105622           testcase( pTop->pWC!=pWC );
   105623         }
   105624         if( pBtm ){
   105625           nBound++;
   105626           wsFlags |= WHERE_BTM_LIMIT;
   105627           used |= pBtm->prereqRight;
   105628           testcase( pBtm->pWC!=pWC );
   105629         }
   105630         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
   105631       }
   105632     }
   105633 
   105634     /* If there is an ORDER BY clause and the index being considered will
   105635     ** naturally scan rows in the required order, set the appropriate flags
   105636     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
   105637     ** will scan rows in a different order, set the bSort variable.  */
   105638     if( isSortingIndex(
   105639           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
   105640     ){
   105641       bSort = 0;
   105642       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
   105643       wsFlags |= (rev ? WHERE_REVERSE : 0);
   105644     }
   105645 
   105646     /* If there is a DISTINCT qualifier and this index will scan rows in
   105647     ** order of the DISTINCT expressions, clear bDist and set the appropriate
   105648     ** flags in wsFlags. */
   105649     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
   105650      && (wsFlags & WHERE_COLUMN_IN)==0
   105651     ){
   105652       bDist = 0;
   105653       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
   105654     }
   105655 
   105656     /* If currently calculating the cost of using an index (not the IPK
   105657     ** index), determine if all required column data may be obtained without
   105658     ** using the main table (i.e. if the index is a covering
   105659     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
   105660     ** wsFlags. Otherwise, set the bLookup variable to true.  */
   105661     if( pIdx && wsFlags ){
   105662       Bitmask m = pSrc->colUsed;
   105663       int j;
   105664       for(j=0; j<pIdx->nColumn; j++){
   105665         int x = pIdx->aiColumn[j];
   105666         if( x<BMS-1 ){
   105667           m &= ~(((Bitmask)1)<<x);
   105668         }
   105669       }
   105670       if( m==0 ){
   105671         wsFlags |= WHERE_IDX_ONLY;
   105672       }else{
   105673         bLookup = 1;
   105674       }
   105675     }
   105676 
   105677     /*
   105678     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
   105679     ** constraint, do not let the estimate exceed half the rows in the table.
   105680     */
   105681     nRow = (double)(aiRowEst[nEq] * nInMul);
   105682     if( bInEst && nRow*2>aiRowEst[0] ){
   105683       nRow = aiRowEst[0]/2;
   105684       nInMul = (int)(nRow / aiRowEst[nEq]);
   105685     }
   105686 
   105687 #ifdef SQLITE_ENABLE_STAT3
   105688     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
   105689     ** and we do not think that values of x are unique and if histogram
   105690     ** data is available for column x, then it might be possible
   105691     ** to get a better estimate on the number of rows based on
   105692     ** VALUE and how common that value is according to the histogram.
   105693     */
   105694     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
   105695       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
   105696       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
   105697         testcase( pFirstTerm->eOperator==WO_EQ );
   105698         testcase( pFirstTerm->eOperator==WO_ISNULL );
   105699         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
   105700       }else if( bInEst==0 ){
   105701         assert( pFirstTerm->eOperator==WO_IN );
   105702         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
   105703       }
   105704     }
   105705 #endif /* SQLITE_ENABLE_STAT3 */
   105706 
   105707     /* Adjust the number of output rows and downward to reflect rows
   105708     ** that are excluded by range constraints.
   105709     */
   105710     nRow = nRow/rangeDiv;
   105711     if( nRow<1 ) nRow = 1;
   105712 
   105713     /* Experiments run on real SQLite databases show that the time needed
   105714     ** to do a binary search to locate a row in a table or index is roughly
   105715     ** log10(N) times the time to move from one row to the next row within
   105716     ** a table or index.  The actual times can vary, with the size of
   105717     ** records being an important factor.  Both moves and searches are
   105718     ** slower with larger records, presumably because fewer records fit
   105719     ** on one page and hence more pages have to be fetched.
   105720     **
   105721     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
   105722     ** not give us data on the relative sizes of table and index records.
   105723     ** So this computation assumes table records are about twice as big
   105724     ** as index records
   105725     */
   105726     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
   105727       /* The cost of a full table scan is a number of move operations equal
   105728       ** to the number of rows in the table.
   105729       **
   105730       ** We add an additional 4x penalty to full table scans.  This causes
   105731       ** the cost function to err on the side of choosing an index over
   105732       ** choosing a full scan.  This 4x full-scan penalty is an arguable
   105733       ** decision and one which we expect to revisit in the future.  But
   105734       ** it seems to be working well enough at the moment.
   105735       */
   105736       cost = aiRowEst[0]*4;
   105737     }else{
   105738       log10N = estLog(aiRowEst[0]);
   105739       cost = nRow;
   105740       if( pIdx ){
   105741         if( bLookup ){
   105742           /* For an index lookup followed by a table lookup:
   105743           **    nInMul index searches to find the start of each index range
   105744           **  + nRow steps through the index
   105745           **  + nRow table searches to lookup the table entry using the rowid
   105746           */
   105747           cost += (nInMul + nRow)*log10N;
   105748         }else{
   105749           /* For a covering index:
   105750           **     nInMul index searches to find the initial entry
   105751           **   + nRow steps through the index
   105752           */
   105753           cost += nInMul*log10N;
   105754         }
   105755       }else{
   105756         /* For a rowid primary key lookup:
   105757         **    nInMult table searches to find the initial entry for each range
   105758         **  + nRow steps through the table
   105759         */
   105760         cost += nInMul*log10N;
   105761       }
   105762     }
   105763 
   105764     /* Add in the estimated cost of sorting the result.  Actual experimental
   105765     ** measurements of sorting performance in SQLite show that sorting time
   105766     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
   105767     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
   105768     ** difference and select C of 3.0.
   105769     */
   105770     if( bSort ){
   105771       cost += nRow*estLog(nRow)*3;
   105772     }
   105773     if( bDist ){
   105774       cost += nRow*estLog(nRow)*3;
   105775     }
   105776 
   105777     /**** Cost of using this index has now been computed ****/
   105778 
   105779     /* If there are additional constraints on this table that cannot
   105780     ** be used with the current index, but which might lower the number
   105781     ** of output rows, adjust the nRow value accordingly.  This only
   105782     ** matters if the current index is the least costly, so do not bother
   105783     ** with this step if we already know this index will not be chosen.
   105784     ** Also, never reduce the output row count below 2 using this step.
   105785     **
   105786     ** It is critical that the notValid mask be used here instead of
   105787     ** the notReady mask.  When computing an "optimal" index, the notReady
   105788     ** mask will only have one bit set - the bit for the current table.
   105789     ** The notValid mask, on the other hand, always has all bits set for
   105790     ** tables that are not in outer loops.  If notReady is used here instead
   105791     ** of notValid, then a optimal index that depends on inner joins loops
   105792     ** might be selected even when there exists an optimal index that has
   105793     ** no such dependency.
   105794     */
   105795     if( nRow>2 && cost<=pCost->rCost ){
   105796       int k;                       /* Loop counter */
   105797       int nSkipEq = nEq;           /* Number of == constraints to skip */
   105798       int nSkipRange = nBound;     /* Number of < constraints to skip */
   105799       Bitmask thisTab;             /* Bitmap for pSrc */
   105800 
   105801       thisTab = getMask(pWC->pMaskSet, iCur);
   105802       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
   105803         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
   105804         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
   105805         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
   105806           if( nSkipEq ){
   105807             /* Ignore the first nEq equality matches since the index
   105808             ** has already accounted for these */
   105809             nSkipEq--;
   105810           }else{
   105811             /* Assume each additional equality match reduces the result
   105812             ** set size by a factor of 10 */
   105813             nRow /= 10;
   105814           }
   105815         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
   105816           if( nSkipRange ){
   105817             /* Ignore the first nSkipRange range constraints since the index
   105818             ** has already accounted for these */
   105819             nSkipRange--;
   105820           }else{
   105821             /* Assume each additional range constraint reduces the result
   105822             ** set size by a factor of 3.  Indexed range constraints reduce
   105823             ** the search space by a larger factor: 4.  We make indexed range
   105824             ** more selective intentionally because of the subjective
   105825             ** observation that indexed range constraints really are more
   105826             ** selective in practice, on average. */
   105827             nRow /= 3;
   105828           }
   105829         }else if( pTerm->eOperator!=WO_NOOP ){
   105830           /* Any other expression lowers the output row count by half */
   105831           nRow /= 2;
   105832         }
   105833       }
   105834       if( nRow<2 ) nRow = 2;
   105835     }
   105836 
   105837 
   105838     WHERETRACE((
   105839       "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
   105840       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
   105841       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
   105842       nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
   105843       notReady, log10N, nRow, cost, used
   105844     ));
   105845 
   105846     /* If this index is the best we have seen so far, then record this
   105847     ** index and its cost in the pCost structure.
   105848     */
   105849     if( (!pIdx || wsFlags)
   105850      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
   105851     ){
   105852       pCost->rCost = cost;
   105853       pCost->used = used;
   105854       pCost->plan.nRow = nRow;
   105855       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
   105856       pCost->plan.nEq = nEq;
   105857       pCost->plan.u.pIdx = pIdx;
   105858     }
   105859 
   105860     /* If there was an INDEXED BY clause, then only that one index is
   105861     ** considered. */
   105862     if( pSrc->pIndex ) break;
   105863 
   105864     /* Reset masks for the next index in the loop */
   105865     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   105866     eqTermMask = idxEqTermMask;
   105867   }
   105868 
   105869   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
   105870   ** is set, then reverse the order that the index will be scanned
   105871   ** in. This is used for application testing, to help find cases
   105872   ** where application behaviour depends on the (undefined) order that
   105873   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
   105874   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
   105875     pCost->plan.wsFlags |= WHERE_REVERSE;
   105876   }
   105877 
   105878   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
   105879   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
   105880   assert( pSrc->pIndex==0
   105881        || pCost->plan.u.pIdx==0
   105882        || pCost->plan.u.pIdx==pSrc->pIndex
   105883   );
   105884 
   105885   WHERETRACE(("best index is: %s\n",
   105886     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
   105887          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
   105888   ));
   105889 
   105890   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   105891   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
   105892   pCost->plan.wsFlags |= eqTermMask;
   105893 }
   105894 
   105895 /*
   105896 ** Find the query plan for accessing table pSrc->pTab. Write the
   105897 ** best query plan and its cost into the WhereCost object supplied
   105898 ** as the last parameter. This function may calculate the cost of
   105899 ** both real and virtual table scans.
   105900 */
   105901 static void bestIndex(
   105902   Parse *pParse,              /* The parsing context */
   105903   WhereClause *pWC,           /* The WHERE clause */
   105904   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   105905   Bitmask notReady,           /* Mask of cursors not available for indexing */
   105906   Bitmask notValid,           /* Cursors not available for any purpose */
   105907   ExprList *pOrderBy,         /* The ORDER BY clause */
   105908   WhereCost *pCost            /* Lowest cost query plan */
   105909 ){
   105910 #ifndef SQLITE_OMIT_VIRTUALTABLE
   105911   if( IsVirtual(pSrc->pTab) ){
   105912     sqlite3_index_info *p = 0;
   105913     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
   105914     if( p->needToFreeIdxStr ){
   105915       sqlite3_free(p->idxStr);
   105916     }
   105917     sqlite3DbFree(pParse->db, p);
   105918   }else
   105919 #endif
   105920   {
   105921     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
   105922   }
   105923 }
   105924 
   105925 /*
   105926 ** Disable a term in the WHERE clause.  Except, do not disable the term
   105927 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   105928 ** or USING clause of that join.
   105929 **
   105930 ** Consider the term t2.z='ok' in the following queries:
   105931 **
   105932 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   105933 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   105934 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   105935 **
   105936 ** The t2.z='ok' is disabled in the in (2) because it originates
   105937 ** in the ON clause.  The term is disabled in (3) because it is not part
   105938 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   105939 **
   105940 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
   105941 ** completely satisfied by indices.
   105942 **
   105943 ** Disabling a term causes that term to not be tested in the inner loop
   105944 ** of the join.  Disabling is an optimization.  When terms are satisfied
   105945 ** by indices, we disable them to prevent redundant tests in the inner
   105946 ** loop.  We would get the correct results if nothing were ever disabled,
   105947 ** but joins might run a little slower.  The trick is to disable as much
   105948 ** as we can without disabling too much.  If we disabled in (1), we'd get
   105949 ** the wrong answer.  See ticket #813.
   105950 */
   105951 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   105952   if( pTerm
   105953       && (pTerm->wtFlags & TERM_CODED)==0
   105954       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   105955   ){
   105956     pTerm->wtFlags |= TERM_CODED;
   105957     if( pTerm->iParent>=0 ){
   105958       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   105959       if( (--pOther->nChild)==0 ){
   105960         disableTerm(pLevel, pOther);
   105961       }
   105962     }
   105963   }
   105964 }
   105965 
   105966 /*
   105967 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   105968 ** to the n registers starting at base.
   105969 **
   105970 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   105971 ** beginning and end of zAff are ignored.  If all entries in zAff are
   105972 ** SQLITE_AFF_NONE, then no code gets generated.
   105973 **
   105974 ** This routine makes its own copy of zAff so that the caller is free
   105975 ** to modify zAff after this routine returns.
   105976 */
   105977 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   105978   Vdbe *v = pParse->pVdbe;
   105979   if( zAff==0 ){
   105980     assert( pParse->db->mallocFailed );
   105981     return;
   105982   }
   105983   assert( v!=0 );
   105984 
   105985   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   105986   ** and end of the affinity string.
   105987   */
   105988   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   105989     n--;
   105990     base++;
   105991     zAff++;
   105992   }
   105993   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   105994     n--;
   105995   }
   105996 
   105997   /* Code the OP_Affinity opcode if there is anything left to do. */
   105998   if( n>0 ){
   105999     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   106000     sqlite3VdbeChangeP4(v, -1, zAff, n);
   106001     sqlite3ExprCacheAffinityChange(pParse, base, n);
   106002   }
   106003 }
   106004 
   106005 
   106006 /*
   106007 ** Generate code for a single equality term of the WHERE clause.  An equality
   106008 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   106009 ** coded.
   106010 **
   106011 ** The current value for the constraint is left in register iReg.
   106012 **
   106013 ** For a constraint of the form X=expr, the expression is evaluated and its
   106014 ** result is left on the stack.  For constraints of the form X IN (...)
   106015 ** this routine sets up a loop that will iterate over all values of X.
   106016 */
   106017 static int codeEqualityTerm(
   106018   Parse *pParse,      /* The parsing context */
   106019   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   106020   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
   106021   int iTarget         /* Attempt to leave results in this register */
   106022 ){
   106023   Expr *pX = pTerm->pExpr;
   106024   Vdbe *v = pParse->pVdbe;
   106025   int iReg;                  /* Register holding results */
   106026 
   106027   assert( iTarget>0 );
   106028   if( pX->op==TK_EQ ){
   106029     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   106030   }else if( pX->op==TK_ISNULL ){
   106031     iReg = iTarget;
   106032     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   106033 #ifndef SQLITE_OMIT_SUBQUERY
   106034   }else{
   106035     int eType;
   106036     int iTab;
   106037     struct InLoop *pIn;
   106038 
   106039     assert( pX->op==TK_IN );
   106040     iReg = iTarget;
   106041     eType = sqlite3FindInIndex(pParse, pX, 0);
   106042     iTab = pX->iTable;
   106043     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   106044     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
   106045     if( pLevel->u.in.nIn==0 ){
   106046       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   106047     }
   106048     pLevel->u.in.nIn++;
   106049     pLevel->u.in.aInLoop =
   106050        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   106051                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   106052     pIn = pLevel->u.in.aInLoop;
   106053     if( pIn ){
   106054       pIn += pLevel->u.in.nIn - 1;
   106055       pIn->iCur = iTab;
   106056       if( eType==IN_INDEX_ROWID ){
   106057         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   106058       }else{
   106059         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   106060       }
   106061       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
   106062     }else{
   106063       pLevel->u.in.nIn = 0;
   106064     }
   106065 #endif
   106066   }
   106067   disableTerm(pLevel, pTerm);
   106068   return iReg;
   106069 }
   106070 
   106071 /*
   106072 ** Generate code that will evaluate all == and IN constraints for an
   106073 ** index.
   106074 **
   106075 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   106076 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   106077 ** The index has as many as three equality constraints, but in this
   106078 ** example, the third "c" value is an inequality.  So only two
   106079 ** constraints are coded.  This routine will generate code to evaluate
   106080 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   106081 ** in consecutive registers and the index of the first register is returned.
   106082 **
   106083 ** In the example above nEq==2.  But this subroutine works for any value
   106084 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   106085 ** The only thing it does is allocate the pLevel->iMem memory cell and
   106086 ** compute the affinity string.
   106087 **
   106088 ** This routine always allocates at least one memory cell and returns
   106089 ** the index of that memory cell. The code that
   106090 ** calls this routine will use that memory cell to store the termination
   106091 ** key value of the loop.  If one or more IN operators appear, then
   106092 ** this routine allocates an additional nEq memory cells for internal
   106093 ** use.
   106094 **
   106095 ** Before returning, *pzAff is set to point to a buffer containing a
   106096 ** copy of the column affinity string of the index allocated using
   106097 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   106098 ** with equality constraints that use NONE affinity are set to
   106099 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   106100 **
   106101 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   106102 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   106103 **
   106104 ** In the example above, the index on t1(a) has TEXT affinity. But since
   106105 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   106106 ** no conversion should be attempted before using a t2.b value as part of
   106107 ** a key to search the index. Hence the first byte in the returned affinity
   106108 ** string in this example would be set to SQLITE_AFF_NONE.
   106109 */
   106110 static int codeAllEqualityTerms(
   106111   Parse *pParse,        /* Parsing context */
   106112   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   106113   WhereClause *pWC,     /* The WHERE clause */
   106114   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
   106115   int nExtraReg,        /* Number of extra registers to allocate */
   106116   char **pzAff          /* OUT: Set to point to affinity string */
   106117 ){
   106118   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
   106119   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   106120   Index *pIdx;                  /* The index being used for this loop */
   106121   int iCur = pLevel->iTabCur;   /* The cursor of the table */
   106122   WhereTerm *pTerm;             /* A single constraint term */
   106123   int j;                        /* Loop counter */
   106124   int regBase;                  /* Base register */
   106125   int nReg;                     /* Number of registers to allocate */
   106126   char *zAff;                   /* Affinity string to return */
   106127 
   106128   /* This module is only called on query plans that use an index. */
   106129   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
   106130   pIdx = pLevel->plan.u.pIdx;
   106131 
   106132   /* Figure out how many memory cells we will need then allocate them.
   106133   */
   106134   regBase = pParse->nMem + 1;
   106135   nReg = pLevel->plan.nEq + nExtraReg;
   106136   pParse->nMem += nReg;
   106137 
   106138   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   106139   if( !zAff ){
   106140     pParse->db->mallocFailed = 1;
   106141   }
   106142 
   106143   /* Evaluate the equality constraints
   106144   */
   106145   assert( pIdx->nColumn>=nEq );
   106146   for(j=0; j<nEq; j++){
   106147     int r1;
   106148     int k = pIdx->aiColumn[j];
   106149     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
   106150     if( NEVER(pTerm==0) ) break;
   106151     /* The following true for indices with redundant columns.
   106152     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   106153     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   106154     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106155     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
   106156     if( r1!=regBase+j ){
   106157       if( nReg==1 ){
   106158         sqlite3ReleaseTempReg(pParse, regBase);
   106159         regBase = r1;
   106160       }else{
   106161         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   106162       }
   106163     }
   106164     testcase( pTerm->eOperator & WO_ISNULL );
   106165     testcase( pTerm->eOperator & WO_IN );
   106166     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   106167       Expr *pRight = pTerm->pExpr->pRight;
   106168       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
   106169       if( zAff ){
   106170         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   106171           zAff[j] = SQLITE_AFF_NONE;
   106172         }
   106173         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   106174           zAff[j] = SQLITE_AFF_NONE;
   106175         }
   106176       }
   106177     }
   106178   }
   106179   *pzAff = zAff;
   106180   return regBase;
   106181 }
   106182 
   106183 #ifndef SQLITE_OMIT_EXPLAIN
   106184 /*
   106185 ** This routine is a helper for explainIndexRange() below
   106186 **
   106187 ** pStr holds the text of an expression that we are building up one term
   106188 ** at a time.  This routine adds a new term to the end of the expression.
   106189 ** Terms are separated by AND so add the "AND" text for second and subsequent
   106190 ** terms only.
   106191 */
   106192 static void explainAppendTerm(
   106193   StrAccum *pStr,             /* The text expression being built */
   106194   int iTerm,                  /* Index of this term.  First is zero */
   106195   const char *zColumn,        /* Name of the column */
   106196   const char *zOp             /* Name of the operator */
   106197 ){
   106198   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   106199   sqlite3StrAccumAppend(pStr, zColumn, -1);
   106200   sqlite3StrAccumAppend(pStr, zOp, 1);
   106201   sqlite3StrAccumAppend(pStr, "?", 1);
   106202 }
   106203 
   106204 /*
   106205 ** Argument pLevel describes a strategy for scanning table pTab. This
   106206 ** function returns a pointer to a string buffer containing a description
   106207 ** of the subset of table rows scanned by the strategy in the form of an
   106208 ** SQL expression. Or, if all rows are scanned, NULL is returned.
   106209 **
   106210 ** For example, if the query:
   106211 **
   106212 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   106213 **
   106214 ** is run and there is an index on (a, b), then this function returns a
   106215 ** string similar to:
   106216 **
   106217 **   "a=? AND b>?"
   106218 **
   106219 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
   106220 ** It is the responsibility of the caller to free the buffer when it is
   106221 ** no longer required.
   106222 */
   106223 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
   106224   WherePlan *pPlan = &pLevel->plan;
   106225   Index *pIndex = pPlan->u.pIdx;
   106226   int nEq = pPlan->nEq;
   106227   int i, j;
   106228   Column *aCol = pTab->aCol;
   106229   int *aiColumn = pIndex->aiColumn;
   106230   StrAccum txt;
   106231 
   106232   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
   106233     return 0;
   106234   }
   106235   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
   106236   txt.db = db;
   106237   sqlite3StrAccumAppend(&txt, " (", 2);
   106238   for(i=0; i<nEq; i++){
   106239     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
   106240   }
   106241 
   106242   j = i;
   106243   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
   106244     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
   106245     explainAppendTerm(&txt, i++, z, ">");
   106246   }
   106247   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
   106248     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
   106249     explainAppendTerm(&txt, i, z, "<");
   106250   }
   106251   sqlite3StrAccumAppend(&txt, ")", 1);
   106252   return sqlite3StrAccumFinish(&txt);
   106253 }
   106254 
   106255 /*
   106256 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   106257 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
   106258 ** record is added to the output to describe the table scan strategy in
   106259 ** pLevel.
   106260 */
   106261 static void explainOneScan(
   106262   Parse *pParse,                  /* Parse context */
   106263   SrcList *pTabList,              /* Table list this loop refers to */
   106264   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   106265   int iLevel,                     /* Value for "level" column of output */
   106266   int iFrom,                      /* Value for "from" column of output */
   106267   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   106268 ){
   106269   if( pParse->explain==2 ){
   106270     u32 flags = pLevel->plan.wsFlags;
   106271     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   106272     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   106273     sqlite3 *db = pParse->db;     /* Database handle */
   106274     char *zMsg;                   /* Text to add to EQP output */
   106275     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
   106276     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   106277     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   106278 
   106279     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
   106280 
   106281     isSearch = (pLevel->plan.nEq>0)
   106282              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   106283              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   106284 
   106285     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
   106286     if( pItem->pSelect ){
   106287       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
   106288     }else{
   106289       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
   106290     }
   106291 
   106292     if( pItem->zAlias ){
   106293       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   106294     }
   106295     if( (flags & WHERE_INDEXED)!=0 ){
   106296       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
   106297       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
   106298           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
   106299           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
   106300           ((flags & WHERE_TEMP_INDEX)?"":" "),
   106301           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
   106302           zWhere
   106303       );
   106304       sqlite3DbFree(db, zWhere);
   106305     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   106306       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
   106307 
   106308       if( flags&WHERE_ROWID_EQ ){
   106309         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
   106310       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   106311         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
   106312       }else if( flags&WHERE_BTM_LIMIT ){
   106313         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
   106314       }else if( flags&WHERE_TOP_LIMIT ){
   106315         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
   106316       }
   106317     }
   106318 #ifndef SQLITE_OMIT_VIRTUALTABLE
   106319     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   106320       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   106321       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   106322                   pVtabIdx->idxNum, pVtabIdx->idxStr);
   106323     }
   106324 #endif
   106325     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
   106326       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
   106327       nRow = 1;
   106328     }else{
   106329       nRow = (sqlite3_int64)pLevel->plan.nRow;
   106330     }
   106331     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
   106332     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
   106333   }
   106334 }
   106335 #else
   106336 # define explainOneScan(u,v,w,x,y,z)
   106337 #endif /* SQLITE_OMIT_EXPLAIN */
   106338 
   106339 
   106340 /*
   106341 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   106342 ** implementation described by pWInfo.
   106343 */
   106344 static Bitmask codeOneLoopStart(
   106345   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   106346   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   106347   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
   106348   Bitmask notReady     /* Which tables are currently available */
   106349 ){
   106350   int j, k;            /* Loop counters */
   106351   int iCur;            /* The VDBE cursor for the table */
   106352   int addrNxt;         /* Where to jump to continue with the next IN case */
   106353   int omitTable;       /* True if we use the index only */
   106354   int bRev;            /* True if we need to scan in reverse order */
   106355   WhereLevel *pLevel;  /* The where level to be coded */
   106356   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   106357   WhereTerm *pTerm;               /* A WHERE clause term */
   106358   Parse *pParse;                  /* Parsing context */
   106359   Vdbe *v;                        /* The prepared stmt under constructions */
   106360   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   106361   int addrBrk;                    /* Jump here to break out of the loop */
   106362   int addrCont;                   /* Jump here to continue with next cycle */
   106363   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   106364   int iReleaseReg = 0;      /* Temp register to free before returning */
   106365 
   106366   pParse = pWInfo->pParse;
   106367   v = pParse->pVdbe;
   106368   pWC = pWInfo->pWC;
   106369   pLevel = &pWInfo->a[iLevel];
   106370   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   106371   iCur = pTabItem->iCursor;
   106372   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
   106373   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
   106374            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
   106375 
   106376   /* Create labels for the "break" and "continue" instructions
   106377   ** for the current loop.  Jump to addrBrk to break out of a loop.
   106378   ** Jump to cont to go immediately to the next iteration of the
   106379   ** loop.
   106380   **
   106381   ** When there is an IN operator, we also have a "addrNxt" label that
   106382   ** means to continue with the next IN value combination.  When
   106383   ** there are no IN operators in the constraints, the "addrNxt" label
   106384   ** is the same as "addrBrk".
   106385   */
   106386   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   106387   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   106388 
   106389   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   106390   ** initialize a memory cell that records if this table matches any
   106391   ** row of the left table of the join.
   106392   */
   106393   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   106394     pLevel->iLeftJoin = ++pParse->nMem;
   106395     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   106396     VdbeComment((v, "init LEFT JOIN no-match flag"));
   106397   }
   106398 
   106399 #ifndef SQLITE_OMIT_VIRTUALTABLE
   106400   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   106401     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
   106402     **          to access the data.
   106403     */
   106404     int iReg;   /* P3 Value for OP_VFilter */
   106405     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   106406     int nConstraint = pVtabIdx->nConstraint;
   106407     struct sqlite3_index_constraint_usage *aUsage =
   106408                                                 pVtabIdx->aConstraintUsage;
   106409     const struct sqlite3_index_constraint *aConstraint =
   106410                                                 pVtabIdx->aConstraint;
   106411 
   106412     sqlite3ExprCachePush(pParse);
   106413     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   106414     for(j=1; j<=nConstraint; j++){
   106415       for(k=0; k<nConstraint; k++){
   106416         if( aUsage[k].argvIndex==j ){
   106417           int iTerm = aConstraint[k].iTermOffset;
   106418           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
   106419           break;
   106420         }
   106421       }
   106422       if( k==nConstraint ) break;
   106423     }
   106424     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
   106425     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
   106426     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
   106427                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
   106428     pVtabIdx->needToFreeIdxStr = 0;
   106429     for(j=0; j<nConstraint; j++){
   106430       if( aUsage[j].omit ){
   106431         int iTerm = aConstraint[j].iTermOffset;
   106432         disableTerm(pLevel, &pWC->a[iTerm]);
   106433       }
   106434     }
   106435     pLevel->op = OP_VNext;
   106436     pLevel->p1 = iCur;
   106437     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   106438     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   106439     sqlite3ExprCachePop(pParse, 1);
   106440   }else
   106441 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   106442 
   106443   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
   106444     /* Case 1:  We can directly reference a single row using an
   106445     **          equality comparison against the ROWID field.  Or
   106446     **          we reference multiple rows using a "rowid IN (...)"
   106447     **          construct.
   106448     */
   106449     iReleaseReg = sqlite3GetTempReg(pParse);
   106450     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
   106451     assert( pTerm!=0 );
   106452     assert( pTerm->pExpr!=0 );
   106453     assert( pTerm->leftCursor==iCur );
   106454     assert( omitTable==0 );
   106455     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106456     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
   106457     addrNxt = pLevel->addrNxt;
   106458     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
   106459     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   106460     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106461     VdbeComment((v, "pk"));
   106462     pLevel->op = OP_Noop;
   106463   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
   106464     /* Case 2:  We have an inequality comparison against the ROWID field.
   106465     */
   106466     int testOp = OP_Noop;
   106467     int start;
   106468     int memEndValue = 0;
   106469     WhereTerm *pStart, *pEnd;
   106470 
   106471     assert( omitTable==0 );
   106472     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
   106473     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
   106474     if( bRev ){
   106475       pTerm = pStart;
   106476       pStart = pEnd;
   106477       pEnd = pTerm;
   106478     }
   106479     if( pStart ){
   106480       Expr *pX;             /* The expression that defines the start bound */
   106481       int r1, rTemp;        /* Registers for holding the start boundary */
   106482 
   106483       /* The following constant maps TK_xx codes into corresponding
   106484       ** seek opcodes.  It depends on a particular ordering of TK_xx
   106485       */
   106486       const u8 aMoveOp[] = {
   106487            /* TK_GT */  OP_SeekGt,
   106488            /* TK_LE */  OP_SeekLe,
   106489            /* TK_LT */  OP_SeekLt,
   106490            /* TK_GE */  OP_SeekGe
   106491       };
   106492       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   106493       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   106494       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   106495 
   106496       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106497       pX = pStart->pExpr;
   106498       assert( pX!=0 );
   106499       assert( pStart->leftCursor==iCur );
   106500       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   106501       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   106502       VdbeComment((v, "pk"));
   106503       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   106504       sqlite3ReleaseTempReg(pParse, rTemp);
   106505       disableTerm(pLevel, pStart);
   106506     }else{
   106507       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   106508     }
   106509     if( pEnd ){
   106510       Expr *pX;
   106511       pX = pEnd->pExpr;
   106512       assert( pX!=0 );
   106513       assert( pEnd->leftCursor==iCur );
   106514       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106515       memEndValue = ++pParse->nMem;
   106516       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   106517       if( pX->op==TK_LT || pX->op==TK_GT ){
   106518         testOp = bRev ? OP_Le : OP_Ge;
   106519       }else{
   106520         testOp = bRev ? OP_Lt : OP_Gt;
   106521       }
   106522       disableTerm(pLevel, pEnd);
   106523     }
   106524     start = sqlite3VdbeCurrentAddr(v);
   106525     pLevel->op = bRev ? OP_Prev : OP_Next;
   106526     pLevel->p1 = iCur;
   106527     pLevel->p2 = start;
   106528     if( pStart==0 && pEnd==0 ){
   106529       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   106530     }else{
   106531       assert( pLevel->p5==0 );
   106532     }
   106533     if( testOp!=OP_Noop ){
   106534       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   106535       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   106536       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106537       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   106538       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   106539     }
   106540   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
   106541     /* Case 3: A scan using an index.
   106542     **
   106543     **         The WHERE clause may contain zero or more equality
   106544     **         terms ("==" or "IN" operators) that refer to the N
   106545     **         left-most columns of the index. It may also contain
   106546     **         inequality constraints (>, <, >= or <=) on the indexed
   106547     **         column that immediately follows the N equalities. Only
   106548     **         the right-most column can be an inequality - the rest must
   106549     **         use the "==" and "IN" operators. For example, if the
   106550     **         index is on (x,y,z), then the following clauses are all
   106551     **         optimized:
   106552     **
   106553     **            x=5
   106554     **            x=5 AND y=10
   106555     **            x=5 AND y<10
   106556     **            x=5 AND y>5 AND y<10
   106557     **            x=5 AND y=5 AND z<=10
   106558     **
   106559     **         The z<10 term of the following cannot be used, only
   106560     **         the x=5 term:
   106561     **
   106562     **            x=5 AND z<10
   106563     **
   106564     **         N may be zero if there are inequality constraints.
   106565     **         If there are no inequality constraints, then N is at
   106566     **         least one.
   106567     **
   106568     **         This case is also used when there are no WHERE clause
   106569     **         constraints but an index is selected anyway, in order
   106570     **         to force the output order to conform to an ORDER BY.
   106571     */
   106572     static const u8 aStartOp[] = {
   106573       0,
   106574       0,
   106575       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   106576       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   106577       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
   106578       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
   106579       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
   106580       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
   106581     };
   106582     static const u8 aEndOp[] = {
   106583       OP_Noop,             /* 0: (!end_constraints) */
   106584       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
   106585       OP_IdxLT             /* 2: (end_constraints && bRev) */
   106586     };
   106587     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
   106588     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
   106589     int regBase;                 /* Base register holding constraint values */
   106590     int r1;                      /* Temp register */
   106591     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   106592     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   106593     int startEq;                 /* True if range start uses ==, >= or <= */
   106594     int endEq;                   /* True if range end uses ==, >= or <= */
   106595     int start_constraints;       /* Start of range is constrained */
   106596     int nConstraint;             /* Number of constraint terms */
   106597     Index *pIdx;                 /* The index we will be using */
   106598     int iIdxCur;                 /* The VDBE cursor for the index */
   106599     int nExtraReg = 0;           /* Number of extra registers needed */
   106600     int op;                      /* Instruction opcode */
   106601     char *zStartAff;             /* Affinity for start of range constraint */
   106602     char *zEndAff;               /* Affinity for end of range constraint */
   106603 
   106604     pIdx = pLevel->plan.u.pIdx;
   106605     iIdxCur = pLevel->iIdxCur;
   106606     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
   106607 
   106608     /* If this loop satisfies a sort order (pOrderBy) request that
   106609     ** was passed to this function to implement a "SELECT min(x) ..."
   106610     ** query, then the caller will only allow the loop to run for
   106611     ** a single iteration. This means that the first row returned
   106612     ** should not have a NULL value stored in 'x'. If column 'x' is
   106613     ** the first one after the nEq equality constraints in the index,
   106614     ** this requires some special handling.
   106615     */
   106616     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
   106617      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
   106618      && (pIdx->nColumn>nEq)
   106619     ){
   106620       /* assert( pOrderBy->nExpr==1 ); */
   106621       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
   106622       isMinQuery = 1;
   106623       nExtraReg = 1;
   106624     }
   106625 
   106626     /* Find any inequality constraint terms for the start and end
   106627     ** of the range.
   106628     */
   106629     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
   106630       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
   106631       nExtraReg = 1;
   106632     }
   106633     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
   106634       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
   106635       nExtraReg = 1;
   106636     }
   106637 
   106638     /* Generate code to evaluate all constraint terms using == or IN
   106639     ** and store the values of those terms in an array of registers
   106640     ** starting at regBase.
   106641     */
   106642     regBase = codeAllEqualityTerms(
   106643         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
   106644     );
   106645     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
   106646     addrNxt = pLevel->addrNxt;
   106647 
   106648     /* If we are doing a reverse order scan on an ascending index, or
   106649     ** a forward order scan on a descending index, interchange the
   106650     ** start and end terms (pRangeStart and pRangeEnd).
   106651     */
   106652     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
   106653      || (bRev && pIdx->nColumn==nEq)
   106654     ){
   106655       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   106656     }
   106657 
   106658     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
   106659     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
   106660     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
   106661     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
   106662     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   106663     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   106664     start_constraints = pRangeStart || nEq>0;
   106665 
   106666     /* Seek the index cursor to the start of the range. */
   106667     nConstraint = nEq;
   106668     if( pRangeStart ){
   106669       Expr *pRight = pRangeStart->pExpr->pRight;
   106670       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   106671       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
   106672         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   106673       }
   106674       if( zStartAff ){
   106675         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
   106676           /* Since the comparison is to be performed with no conversions
   106677           ** applied to the operands, set the affinity to apply to pRight to
   106678           ** SQLITE_AFF_NONE.  */
   106679           zStartAff[nEq] = SQLITE_AFF_NONE;
   106680         }
   106681         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
   106682           zStartAff[nEq] = SQLITE_AFF_NONE;
   106683         }
   106684       }
   106685       nConstraint++;
   106686       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106687     }else if( isMinQuery ){
   106688       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   106689       nConstraint++;
   106690       startEq = 0;
   106691       start_constraints = 1;
   106692     }
   106693     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
   106694     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   106695     assert( op!=0 );
   106696     testcase( op==OP_Rewind );
   106697     testcase( op==OP_Last );
   106698     testcase( op==OP_SeekGt );
   106699     testcase( op==OP_SeekGe );
   106700     testcase( op==OP_SeekLe );
   106701     testcase( op==OP_SeekLt );
   106702     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   106703 
   106704     /* Load the value for the inequality constraint at the end of the
   106705     ** range (if any).
   106706     */
   106707     nConstraint = nEq;
   106708     if( pRangeEnd ){
   106709       Expr *pRight = pRangeEnd->pExpr->pRight;
   106710       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   106711       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   106712       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
   106713         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   106714       }
   106715       if( zEndAff ){
   106716         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
   106717           /* Since the comparison is to be performed with no conversions
   106718           ** applied to the operands, set the affinity to apply to pRight to
   106719           ** SQLITE_AFF_NONE.  */
   106720           zEndAff[nEq] = SQLITE_AFF_NONE;
   106721         }
   106722         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
   106723           zEndAff[nEq] = SQLITE_AFF_NONE;
   106724         }
   106725       }
   106726       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
   106727       nConstraint++;
   106728       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   106729     }
   106730     sqlite3DbFree(pParse->db, zStartAff);
   106731     sqlite3DbFree(pParse->db, zEndAff);
   106732 
   106733     /* Top of the loop body */
   106734     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   106735 
   106736     /* Check if the index cursor is past the end of the range. */
   106737     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
   106738     testcase( op==OP_Noop );
   106739     testcase( op==OP_IdxGE );
   106740     testcase( op==OP_IdxLT );
   106741     if( op!=OP_Noop ){
   106742       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   106743       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
   106744     }
   106745 
   106746     /* If there are inequality constraints, check that the value
   106747     ** of the table column that the inequality contrains is not NULL.
   106748     ** If it is, jump to the next iteration of the loop.
   106749     */
   106750     r1 = sqlite3GetTempReg(pParse);
   106751     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
   106752     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
   106753     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
   106754       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
   106755       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
   106756     }
   106757     sqlite3ReleaseTempReg(pParse, r1);
   106758 
   106759     /* Seek the table cursor, if required */
   106760     disableTerm(pLevel, pRangeStart);
   106761     disableTerm(pLevel, pRangeEnd);
   106762     if( !omitTable ){
   106763       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   106764       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   106765       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   106766       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   106767     }
   106768 
   106769     /* Record the instruction used to terminate the loop. Disable
   106770     ** WHERE clause terms made redundant by the index range scan.
   106771     */
   106772     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
   106773       pLevel->op = OP_Noop;
   106774     }else if( bRev ){
   106775       pLevel->op = OP_Prev;
   106776     }else{
   106777       pLevel->op = OP_Next;
   106778     }
   106779     pLevel->p1 = iIdxCur;
   106780   }else
   106781 
   106782 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   106783   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
   106784     /* Case 4:  Two or more separately indexed terms connected by OR
   106785     **
   106786     ** Example:
   106787     **
   106788     **   CREATE TABLE t1(a,b,c,d);
   106789     **   CREATE INDEX i1 ON t1(a);
   106790     **   CREATE INDEX i2 ON t1(b);
   106791     **   CREATE INDEX i3 ON t1(c);
   106792     **
   106793     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   106794     **
   106795     ** In the example, there are three indexed terms connected by OR.
   106796     ** The top of the loop looks like this:
   106797     **
   106798     **          Null       1                # Zero the rowset in reg 1
   106799     **
   106800     ** Then, for each indexed term, the following. The arguments to
   106801     ** RowSetTest are such that the rowid of the current row is inserted
   106802     ** into the RowSet. If it is already present, control skips the
   106803     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   106804     **
   106805     **        sqlite3WhereBegin(<term>)
   106806     **          RowSetTest                  # Insert rowid into rowset
   106807     **          Gosub      2 A
   106808     **        sqlite3WhereEnd()
   106809     **
   106810     ** Following the above, code to terminate the loop. Label A, the target
   106811     ** of the Gosub above, jumps to the instruction right after the Goto.
   106812     **
   106813     **          Null       1                # Zero the rowset in reg 1
   106814     **          Goto       B                # The loop is finished.
   106815     **
   106816     **       A: <loop body>                 # Return data, whatever.
   106817     **
   106818     **          Return     2                # Jump back to the Gosub
   106819     **
   106820     **       B: <after the loop>
   106821     **
   106822     */
   106823     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   106824     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   106825 
   106826     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   106827     int regRowset = 0;                        /* Register for RowSet object */
   106828     int regRowid = 0;                         /* Register holding rowid */
   106829     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   106830     int iRetInit;                             /* Address of regReturn init */
   106831     int untestedTerms = 0;             /* Some terms not completely tested */
   106832     int ii;                            /* Loop counter */
   106833     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
   106834 
   106835     pTerm = pLevel->plan.u.pTerm;
   106836     assert( pTerm!=0 );
   106837     assert( pTerm->eOperator==WO_OR );
   106838     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   106839     pOrWc = &pTerm->u.pOrInfo->wc;
   106840     pLevel->op = OP_Return;
   106841     pLevel->p1 = regReturn;
   106842 
   106843     /* Set up a new SrcList ni pOrTab containing the table being scanned
   106844     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   106845     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   106846     */
   106847     if( pWInfo->nLevel>1 ){
   106848       int nNotReady;                 /* The number of notReady tables */
   106849       struct SrcList_item *origSrc;     /* Original list of tables */
   106850       nNotReady = pWInfo->nLevel - iLevel - 1;
   106851       pOrTab = sqlite3StackAllocRaw(pParse->db,
   106852                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   106853       if( pOrTab==0 ) return notReady;
   106854       pOrTab->nAlloc = (i16)(nNotReady + 1);
   106855       pOrTab->nSrc = pOrTab->nAlloc;
   106856       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   106857       origSrc = pWInfo->pTabList->a;
   106858       for(k=1; k<=nNotReady; k++){
   106859         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   106860       }
   106861     }else{
   106862       pOrTab = pWInfo->pTabList;
   106863     }
   106864 
   106865     /* Initialize the rowset register to contain NULL. An SQL NULL is
   106866     ** equivalent to an empty rowset.
   106867     **
   106868     ** Also initialize regReturn to contain the address of the instruction
   106869     ** immediately following the OP_Return at the bottom of the loop. This
   106870     ** is required in a few obscure LEFT JOIN cases where control jumps
   106871     ** over the top of the loop into the body of it. In this case the
   106872     ** correct response for the end-of-loop code (the OP_Return) is to
   106873     ** fall through to the next instruction, just as an OP_Next does if
   106874     ** called on an uninitialized cursor.
   106875     */
   106876     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   106877       regRowset = ++pParse->nMem;
   106878       regRowid = ++pParse->nMem;
   106879       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   106880     }
   106881     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   106882 
   106883     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
   106884     ** Then for every term xN, evaluate as the subexpression: xN AND z
   106885     ** That way, terms in y that are factored into the disjunction will
   106886     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
   106887     **
   106888     ** Actually, each subexpression is converted to "xN AND w" where w is
   106889     ** the "interesting" terms of z - terms that did not originate in the
   106890     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
   106891     ** indices.
   106892     */
   106893     if( pWC->nTerm>1 ){
   106894       int iTerm;
   106895       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
   106896         Expr *pExpr = pWC->a[iTerm].pExpr;
   106897         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
   106898         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
   106899         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
   106900         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
   106901         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
   106902       }
   106903       if( pAndExpr ){
   106904         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
   106905       }
   106906     }
   106907 
   106908     for(ii=0; ii<pOrWc->nTerm; ii++){
   106909       WhereTerm *pOrTerm = &pOrWc->a[ii];
   106910       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
   106911         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
   106912         Expr *pOrExpr = pOrTerm->pExpr;
   106913         if( pAndExpr ){
   106914           pAndExpr->pLeft = pOrExpr;
   106915           pOrExpr = pAndExpr;
   106916         }
   106917         /* Loop through table entries that match term pOrTerm. */
   106918         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
   106919                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
   106920                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
   106921         if( pSubWInfo ){
   106922           explainOneScan(
   106923               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   106924           );
   106925           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   106926             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   106927             int r;
   106928             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
   106929                                          regRowid);
   106930             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
   106931                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
   106932           }
   106933           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   106934 
   106935           /* The pSubWInfo->untestedTerms flag means that this OR term
   106936           ** contained one or more AND term from a notReady table.  The
   106937           ** terms from the notReady table could not be tested and will
   106938           ** need to be tested later.
   106939           */
   106940           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   106941 
   106942           /* Finish the loop through table entries that match term pOrTerm. */
   106943           sqlite3WhereEnd(pSubWInfo);
   106944         }
   106945       }
   106946     }
   106947     if( pAndExpr ){
   106948       pAndExpr->pLeft = 0;
   106949       sqlite3ExprDelete(pParse->db, pAndExpr);
   106950     }
   106951     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   106952     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   106953     sqlite3VdbeResolveLabel(v, iLoopBody);
   106954 
   106955     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
   106956     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   106957   }else
   106958 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   106959 
   106960   {
   106961     /* Case 5:  There is no usable index.  We must do a complete
   106962     **          scan of the entire table.
   106963     */
   106964     static const u8 aStep[] = { OP_Next, OP_Prev };
   106965     static const u8 aStart[] = { OP_Rewind, OP_Last };
   106966     assert( bRev==0 || bRev==1 );
   106967     assert( omitTable==0 );
   106968     pLevel->op = aStep[bRev];
   106969     pLevel->p1 = iCur;
   106970     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   106971     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   106972   }
   106973   notReady &= ~getMask(pWC->pMaskSet, iCur);
   106974 
   106975   /* Insert code to test every subexpression that can be completely
   106976   ** computed using the current set of tables.
   106977   **
   106978   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
   106979   ** the use of indices become tests that are evaluated against each row of
   106980   ** the relevant input tables.
   106981   */
   106982   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   106983     Expr *pE;
   106984     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
   106985     testcase( pTerm->wtFlags & TERM_CODED );
   106986     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   106987     if( (pTerm->prereqAll & notReady)!=0 ){
   106988       testcase( pWInfo->untestedTerms==0
   106989                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   106990       pWInfo->untestedTerms = 1;
   106991       continue;
   106992     }
   106993     pE = pTerm->pExpr;
   106994     assert( pE!=0 );
   106995     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   106996       continue;
   106997     }
   106998     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   106999     pTerm->wtFlags |= TERM_CODED;
   107000   }
   107001 
   107002   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   107003   ** at least one row of the right table has matched the left table.
   107004   */
   107005   if( pLevel->iLeftJoin ){
   107006     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   107007     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   107008     VdbeComment((v, "record LEFT JOIN hit"));
   107009     sqlite3ExprCacheClear(pParse);
   107010     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   107011       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
   107012       testcase( pTerm->wtFlags & TERM_CODED );
   107013       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   107014       if( (pTerm->prereqAll & notReady)!=0 ){
   107015         assert( pWInfo->untestedTerms );
   107016         continue;
   107017       }
   107018       assert( pTerm->pExpr );
   107019       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   107020       pTerm->wtFlags |= TERM_CODED;
   107021     }
   107022   }
   107023   sqlite3ReleaseTempReg(pParse, iReleaseReg);
   107024 
   107025   return notReady;
   107026 }
   107027 
   107028 #if defined(SQLITE_TEST)
   107029 /*
   107030 ** The following variable holds a text description of query plan generated
   107031 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
   107032 ** overwrites the previous.  This information is used for testing and
   107033 ** analysis only.
   107034 */
   107035 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
   107036 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
   107037 
   107038 #endif /* SQLITE_TEST */
   107039 
   107040 
   107041 /*
   107042 ** Free a WhereInfo structure
   107043 */
   107044 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   107045   if( ALWAYS(pWInfo) ){
   107046     int i;
   107047     for(i=0; i<pWInfo->nLevel; i++){
   107048       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
   107049       if( pInfo ){
   107050         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
   107051         if( pInfo->needToFreeIdxStr ){
   107052           sqlite3_free(pInfo->idxStr);
   107053         }
   107054         sqlite3DbFree(db, pInfo);
   107055       }
   107056       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
   107057         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
   107058         if( pIdx ){
   107059           sqlite3DbFree(db, pIdx->zColAff);
   107060           sqlite3DbFree(db, pIdx);
   107061         }
   107062       }
   107063     }
   107064     whereClauseClear(pWInfo->pWC);
   107065     sqlite3DbFree(db, pWInfo);
   107066   }
   107067 }
   107068 
   107069 
   107070 /*
   107071 ** Generate the beginning of the loop used for WHERE clause processing.
   107072 ** The return value is a pointer to an opaque structure that contains
   107073 ** information needed to terminate the loop.  Later, the calling routine
   107074 ** should invoke sqlite3WhereEnd() with the return value of this function
   107075 ** in order to complete the WHERE clause processing.
   107076 **
   107077 ** If an error occurs, this routine returns NULL.
   107078 **
   107079 ** The basic idea is to do a nested loop, one loop for each table in
   107080 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   107081 ** same as a SELECT with only a single table in the FROM clause.)  For
   107082 ** example, if the SQL is this:
   107083 **
   107084 **       SELECT * FROM t1, t2, t3 WHERE ...;
   107085 **
   107086 ** Then the code generated is conceptually like the following:
   107087 **
   107088 **      foreach row1 in t1 do       \    Code generated
   107089 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   107090 **          foreach row3 in t3 do   /
   107091 **            ...
   107092 **          end                     \    Code generated
   107093 **        end                        |-- by sqlite3WhereEnd()
   107094 **      end                         /
   107095 **
   107096 ** Note that the loops might not be nested in the order in which they
   107097 ** appear in the FROM clause if a different order is better able to make
   107098 ** use of indices.  Note also that when the IN operator appears in
   107099 ** the WHERE clause, it might result in additional nested loops for
   107100 ** scanning through all values on the right-hand side of the IN.
   107101 **
   107102 ** There are Btree cursors associated with each table.  t1 uses cursor
   107103 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   107104 ** And so forth.  This routine generates code to open those VDBE cursors
   107105 ** and sqlite3WhereEnd() generates the code to close them.
   107106 **
   107107 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   107108 ** in pTabList pointing at their appropriate entries.  The [...] code
   107109 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   107110 ** data from the various tables of the loop.
   107111 **
   107112 ** If the WHERE clause is empty, the foreach loops must each scan their
   107113 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   107114 ** the tables have indices and there are terms in the WHERE clause that
   107115 ** refer to those indices, a complete table scan can be avoided and the
   107116 ** code will run much faster.  Most of the work of this routine is checking
   107117 ** to see if there are indices that can be used to speed up the loop.
   107118 **
   107119 ** Terms of the WHERE clause are also used to limit which rows actually
   107120 ** make it to the "..." in the middle of the loop.  After each "foreach",
   107121 ** terms of the WHERE clause that use only terms in that loop and outer
   107122 ** loops are evaluated and if false a jump is made around all subsequent
   107123 ** inner loops (or around the "..." if the test occurs within the inner-
   107124 ** most loop)
   107125 **
   107126 ** OUTER JOINS
   107127 **
   107128 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   107129 **
   107130 **    foreach row1 in t1 do
   107131 **      flag = 0
   107132 **      foreach row2 in t2 do
   107133 **        start:
   107134 **          ...
   107135 **          flag = 1
   107136 **      end
   107137 **      if flag==0 then
   107138 **        move the row2 cursor to a null row
   107139 **        goto start
   107140 **      fi
   107141 **    end
   107142 **
   107143 ** ORDER BY CLAUSE PROCESSING
   107144 **
   107145 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
   107146 ** if there is one.  If there is no ORDER BY clause or if this routine
   107147 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
   107148 **
   107149 ** If an index can be used so that the natural output order of the table
   107150 ** scan is correct for the ORDER BY clause, then that index is used and
   107151 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
   107152 ** unnecessary sort of the result set if an index appropriate for the
   107153 ** ORDER BY clause already exists.
   107154 **
   107155 ** If the where clause loops cannot be arranged to provide the correct
   107156 ** output order, then the *ppOrderBy is unchanged.
   107157 */
   107158 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   107159   Parse *pParse,        /* The parser context */
   107160   SrcList *pTabList,    /* A list of all tables to be scanned */
   107161   Expr *pWhere,         /* The WHERE clause */
   107162   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
   107163   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
   107164   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
   107165 ){
   107166   int i;                     /* Loop counter */
   107167   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   107168   int nTabList;              /* Number of elements in pTabList */
   107169   WhereInfo *pWInfo;         /* Will become the return value of this function */
   107170   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   107171   Bitmask notReady;          /* Cursors that are not yet positioned */
   107172   WhereMaskSet *pMaskSet;    /* The expression mask set */
   107173   WhereClause *pWC;               /* Decomposition of the WHERE clause */
   107174   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
   107175   WhereLevel *pLevel;             /* A single level in the pWInfo list */
   107176   int iFrom;                      /* First unused FROM clause element */
   107177   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
   107178   sqlite3 *db;               /* Database connection */
   107179 
   107180   /* The number of tables in the FROM clause is limited by the number of
   107181   ** bits in a Bitmask
   107182   */
   107183   testcase( pTabList->nSrc==BMS );
   107184   if( pTabList->nSrc>BMS ){
   107185     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   107186     return 0;
   107187   }
   107188 
   107189   /* This function normally generates a nested loop for all tables in
   107190   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   107191   ** only generate code for the first table in pTabList and assume that
   107192   ** any cursors associated with subsequent tables are uninitialized.
   107193   */
   107194   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   107195 
   107196   /* Allocate and initialize the WhereInfo structure that will become the
   107197   ** return value. A single allocation is used to store the WhereInfo
   107198   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   107199   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   107200   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   107201   ** some architectures. Hence the ROUND8() below.
   107202   */
   107203   db = pParse->db;
   107204   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   107205   pWInfo = sqlite3DbMallocZero(db,
   107206       nByteWInfo +
   107207       sizeof(WhereClause) +
   107208       sizeof(WhereMaskSet)
   107209   );
   107210   if( db->mallocFailed ){
   107211     sqlite3DbFree(db, pWInfo);
   107212     pWInfo = 0;
   107213     goto whereBeginError;
   107214   }
   107215   pWInfo->nLevel = nTabList;
   107216   pWInfo->pParse = pParse;
   107217   pWInfo->pTabList = pTabList;
   107218   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
   107219   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
   107220   pWInfo->wctrlFlags = wctrlFlags;
   107221   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   107222   pMaskSet = (WhereMaskSet*)&pWC[1];
   107223 
   107224   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
   107225   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
   107226   if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
   107227 
   107228   /* Split the WHERE clause into separate subexpressions where each
   107229   ** subexpression is separated by an AND operator.
   107230   */
   107231   initMaskSet(pMaskSet);
   107232   whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
   107233   sqlite3ExprCodeConstants(pParse, pWhere);
   107234   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
   107235 
   107236   /* Special case: a WHERE clause that is constant.  Evaluate the
   107237   ** expression and either jump over all of the code or fall thru.
   107238   */
   107239   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
   107240     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
   107241     pWhere = 0;
   107242   }
   107243 
   107244   /* Assign a bit from the bitmask to every term in the FROM clause.
   107245   **
   107246   ** When assigning bitmask values to FROM clause cursors, it must be
   107247   ** the case that if X is the bitmask for the N-th FROM clause term then
   107248   ** the bitmask for all FROM clause terms to the left of the N-th term
   107249   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   107250   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   107251   ** of the join.  Subtracting one from the right table bitmask gives a
   107252   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   107253   ** for all tables to the left of a left join is important.  Ticket #3015.
   107254   **
   107255   ** Configure the WhereClause.vmask variable so that bits that correspond
   107256   ** to virtual table cursors are set. This is used to selectively disable
   107257   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
   107258   ** with virtual tables.
   107259   **
   107260   ** Note that bitmasks are created for all pTabList->nSrc tables in
   107261   ** pTabList, not just the first nTabList tables.  nTabList is normally
   107262   ** equal to pTabList->nSrc but might be shortened to 1 if the
   107263   ** WHERE_ONETABLE_ONLY flag is set.
   107264   */
   107265   assert( pWC->vmask==0 && pMaskSet->n==0 );
   107266   for(i=0; i<pTabList->nSrc; i++){
   107267     createMask(pMaskSet, pTabList->a[i].iCursor);
   107268 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107269     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
   107270       pWC->vmask |= ((Bitmask)1 << i);
   107271     }
   107272 #endif
   107273   }
   107274 #ifndef NDEBUG
   107275   {
   107276     Bitmask toTheLeft = 0;
   107277     for(i=0; i<pTabList->nSrc; i++){
   107278       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
   107279       assert( (m-1)==toTheLeft );
   107280       toTheLeft |= m;
   107281     }
   107282   }
   107283 #endif
   107284 
   107285   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   107286   ** add new virtual terms onto the end of the WHERE clause.  We do not
   107287   ** want to analyze these virtual terms, so start analyzing at the end
   107288   ** and work forward so that the added virtual terms are never processed.
   107289   */
   107290   exprAnalyzeAll(pTabList, pWC);
   107291   if( db->mallocFailed ){
   107292     goto whereBeginError;
   107293   }
   107294 
   107295   /* Check if the DISTINCT qualifier, if there is one, is redundant.
   107296   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
   107297   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
   107298   */
   107299   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
   107300     pDistinct = 0;
   107301     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
   107302   }
   107303 
   107304   /* Chose the best index to use for each table in the FROM clause.
   107305   **
   107306   ** This loop fills in the following fields:
   107307   **
   107308   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
   107309   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
   107310   **   pWInfo->a[].nEq       The number of == and IN constraints
   107311   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
   107312   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
   107313   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
   107314   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
   107315   **
   107316   ** This loop also figures out the nesting order of tables in the FROM
   107317   ** clause.
   107318   */
   107319   notReady = ~(Bitmask)0;
   107320   andFlags = ~0;
   107321   WHERETRACE(("*** Optimizer Start ***\n"));
   107322   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   107323     WhereCost bestPlan;         /* Most efficient plan seen so far */
   107324     Index *pIdx;                /* Index for FROM table at pTabItem */
   107325     int j;                      /* For looping over FROM tables */
   107326     int bestJ = -1;             /* The value of j */
   107327     Bitmask m;                  /* Bitmask value for j or bestJ */
   107328     int isOptimal;              /* Iterator for optimal/non-optimal search */
   107329     int nUnconstrained;         /* Number tables without INDEXED BY */
   107330     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
   107331 
   107332     memset(&bestPlan, 0, sizeof(bestPlan));
   107333     bestPlan.rCost = SQLITE_BIG_DBL;
   107334     WHERETRACE(("*** Begin search for loop %d ***\n", i));
   107335 
   107336     /* Loop through the remaining entries in the FROM clause to find the
   107337     ** next nested loop. The loop tests all FROM clause entries
   107338     ** either once or twice.
   107339     **
   107340     ** The first test is always performed if there are two or more entries
   107341     ** remaining and never performed if there is only one FROM clause entry
   107342     ** to choose from.  The first test looks for an "optimal" scan.  In
   107343     ** this context an optimal scan is one that uses the same strategy
   107344     ** for the given FROM clause entry as would be selected if the entry
   107345     ** were used as the innermost nested loop.  In other words, a table
   107346     ** is chosen such that the cost of running that table cannot be reduced
   107347     ** by waiting for other tables to run first.  This "optimal" test works
   107348     ** by first assuming that the FROM clause is on the inner loop and finding
   107349     ** its query plan, then checking to see if that query plan uses any
   107350     ** other FROM clause terms that are notReady.  If no notReady terms are
   107351     ** used then the "optimal" query plan works.
   107352     **
   107353     ** Note that the WhereCost.nRow parameter for an optimal scan might
   107354     ** not be as small as it would be if the table really were the innermost
   107355     ** join.  The nRow value can be reduced by WHERE clause constraints
   107356     ** that do not use indices.  But this nRow reduction only happens if the
   107357     ** table really is the innermost join.
   107358     **
   107359     ** The second loop iteration is only performed if no optimal scan
   107360     ** strategies were found by the first iteration. This second iteration
   107361     ** is used to search for the lowest cost scan overall.
   107362     **
   107363     ** Previous versions of SQLite performed only the second iteration -
   107364     ** the next outermost loop was always that with the lowest overall
   107365     ** cost. However, this meant that SQLite could select the wrong plan
   107366     ** for scripts such as the following:
   107367     **
   107368     **   CREATE TABLE t1(a, b);
   107369     **   CREATE TABLE t2(c, d);
   107370     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
   107371     **
   107372     ** The best strategy is to iterate through table t1 first. However it
   107373     ** is not possible to determine this with a simple greedy algorithm.
   107374     ** Since the cost of a linear scan through table t2 is the same
   107375     ** as the cost of a linear scan through table t1, a simple greedy
   107376     ** algorithm may choose to use t2 for the outer loop, which is a much
   107377     ** costlier approach.
   107378     */
   107379     nUnconstrained = 0;
   107380     notIndexed = 0;
   107381     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
   107382       Bitmask mask;             /* Mask of tables not yet ready */
   107383       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
   107384         int doNotReorder;    /* True if this table should not be reordered */
   107385         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
   107386         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
   107387         ExprList *pDist;     /* DISTINCT clause for index to optimize */
   107388 
   107389         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
   107390         if( j!=iFrom && doNotReorder ) break;
   107391         m = getMask(pMaskSet, pTabItem->iCursor);
   107392         if( (m & notReady)==0 ){
   107393           if( j==iFrom ) iFrom++;
   107394           continue;
   107395         }
   107396         mask = (isOptimal ? m : notReady);
   107397         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
   107398         pDist = (i==0 ? pDistinct : 0);
   107399         if( pTabItem->pIndex==0 ) nUnconstrained++;
   107400 
   107401         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
   107402                     j, isOptimal));
   107403         assert( pTabItem->pTab );
   107404 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107405         if( IsVirtual(pTabItem->pTab) ){
   107406           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
   107407           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   107408                            &sCost, pp);
   107409         }else
   107410 #endif
   107411         {
   107412           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   107413               pDist, &sCost);
   107414         }
   107415         assert( isOptimal || (sCost.used&notReady)==0 );
   107416 
   107417         /* If an INDEXED BY clause is present, then the plan must use that
   107418         ** index if it uses any index at all */
   107419         assert( pTabItem->pIndex==0
   107420                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
   107421                   || sCost.plan.u.pIdx==pTabItem->pIndex );
   107422 
   107423         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
   107424           notIndexed |= m;
   107425         }
   107426 
   107427         /* Conditions under which this table becomes the best so far:
   107428         **
   107429         **   (1) The table must not depend on other tables that have not
   107430         **       yet run.
   107431         **
   107432         **   (2) A full-table-scan plan cannot supercede indexed plan unless
   107433         **       the full-table-scan is an "optimal" plan as defined above.
   107434         **
   107435         **   (3) All tables have an INDEXED BY clause or this table lacks an
   107436         **       INDEXED BY clause or this table uses the specific
   107437         **       index specified by its INDEXED BY clause.  This rule ensures
   107438         **       that a best-so-far is always selected even if an impossible
   107439         **       combination of INDEXED BY clauses are given.  The error
   107440         **       will be detected and relayed back to the application later.
   107441         **       The NEVER() comes about because rule (2) above prevents
   107442         **       An indexable full-table-scan from reaching rule (3).
   107443         **
   107444         **   (4) The plan cost must be lower than prior plans or else the
   107445         **       cost must be the same and the number of rows must be lower.
   107446         */
   107447         if( (sCost.used&notReady)==0                       /* (1) */
   107448             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
   107449                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
   107450                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
   107451             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
   107452                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
   107453             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
   107454                 || (sCost.rCost<=bestPlan.rCost
   107455                  && sCost.plan.nRow<bestPlan.plan.nRow))
   107456         ){
   107457           WHERETRACE(("=== table %d is best so far"
   107458                       " with cost=%g and nRow=%g\n",
   107459                       j, sCost.rCost, sCost.plan.nRow));
   107460           bestPlan = sCost;
   107461           bestJ = j;
   107462         }
   107463         if( doNotReorder ) break;
   107464       }
   107465     }
   107466     assert( bestJ>=0 );
   107467     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
   107468     WHERETRACE(("*** Optimizer selects table %d for loop %d"
   107469                 " with cost=%g and nRow=%g\n",
   107470                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
   107471     /* The ALWAYS() that follows was added to hush up clang scan-build */
   107472     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
   107473       *ppOrderBy = 0;
   107474     }
   107475     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
   107476       assert( pWInfo->eDistinct==0 );
   107477       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
   107478     }
   107479     andFlags &= bestPlan.plan.wsFlags;
   107480     pLevel->plan = bestPlan.plan;
   107481     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
   107482     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
   107483     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
   107484       pLevel->iIdxCur = pParse->nTab++;
   107485     }else{
   107486       pLevel->iIdxCur = -1;
   107487     }
   107488     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
   107489     pLevel->iFrom = (u8)bestJ;
   107490     if( bestPlan.plan.nRow>=(double)1 ){
   107491       pParse->nQueryLoop *= bestPlan.plan.nRow;
   107492     }
   107493 
   107494     /* Check that if the table scanned by this loop iteration had an
   107495     ** INDEXED BY clause attached to it, that the named index is being
   107496     ** used for the scan. If not, then query compilation has failed.
   107497     ** Return an error.
   107498     */
   107499     pIdx = pTabList->a[bestJ].pIndex;
   107500     if( pIdx ){
   107501       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
   107502         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
   107503         goto whereBeginError;
   107504       }else{
   107505         /* If an INDEXED BY clause is used, the bestIndex() function is
   107506         ** guaranteed to find the index specified in the INDEXED BY clause
   107507         ** if it find an index at all. */
   107508         assert( bestPlan.plan.u.pIdx==pIdx );
   107509       }
   107510     }
   107511   }
   107512   WHERETRACE(("*** Optimizer Finished ***\n"));
   107513   if( pParse->nErr || db->mallocFailed ){
   107514     goto whereBeginError;
   107515   }
   107516 
   107517   /* If the total query only selects a single row, then the ORDER BY
   107518   ** clause is irrelevant.
   107519   */
   107520   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
   107521     *ppOrderBy = 0;
   107522   }
   107523 
   107524   /* If the caller is an UPDATE or DELETE statement that is requesting
   107525   ** to use a one-pass algorithm, determine if this is appropriate.
   107526   ** The one-pass algorithm only works if the WHERE clause constraints
   107527   ** the statement to update a single row.
   107528   */
   107529   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   107530   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
   107531     pWInfo->okOnePass = 1;
   107532     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
   107533   }
   107534 
   107535   /* Open all tables in the pTabList and any indices selected for
   107536   ** searching those tables.
   107537   */
   107538   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
   107539   notReady = ~(Bitmask)0;
   107540   pWInfo->nRowOut = (double)1;
   107541   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   107542     Table *pTab;     /* Table to open */
   107543     int iDb;         /* Index of database containing table/index */
   107544 
   107545     pTabItem = &pTabList->a[pLevel->iFrom];
   107546     pTab = pTabItem->pTab;
   107547     pLevel->iTabCur = pTabItem->iCursor;
   107548     pWInfo->nRowOut *= pLevel->plan.nRow;
   107549     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   107550     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   107551       /* Do nothing */
   107552     }else
   107553 #ifndef SQLITE_OMIT_VIRTUALTABLE
   107554     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   107555       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   107556       int iCur = pTabItem->iCursor;
   107557       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   107558     }else
   107559 #endif
   107560     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107561          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
   107562       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
   107563       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   107564       testcase( pTab->nCol==BMS-1 );
   107565       testcase( pTab->nCol==BMS );
   107566       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
   107567         Bitmask b = pTabItem->colUsed;
   107568         int n = 0;
   107569         for(; b; b=b>>1, n++){}
   107570         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   107571                             SQLITE_INT_TO_PTR(n), P4_INT32);
   107572         assert( n<=pTab->nCol );
   107573       }
   107574     }else{
   107575       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   107576     }
   107577 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   107578     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
   107579       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
   107580     }else
   107581 #endif
   107582     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   107583       Index *pIx = pLevel->plan.u.pIdx;
   107584       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
   107585       int iIdxCur = pLevel->iIdxCur;
   107586       assert( pIx->pSchema==pTab->pSchema );
   107587       assert( iIdxCur>=0 );
   107588       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
   107589                         (char*)pKey, P4_KEYINFO_HANDOFF);
   107590       VdbeComment((v, "%s", pIx->zName));
   107591     }
   107592     sqlite3CodeVerifySchema(pParse, iDb);
   107593     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
   107594   }
   107595   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   107596   if( db->mallocFailed ) goto whereBeginError;
   107597 
   107598   /* Generate the code to do the search.  Each iteration of the for
   107599   ** loop below generates code for a single nested loop of the VM
   107600   ** program.
   107601   */
   107602   notReady = ~(Bitmask)0;
   107603   for(i=0; i<nTabList; i++){
   107604     pLevel = &pWInfo->a[i];
   107605     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
   107606     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
   107607     pWInfo->iContinue = pLevel->addrCont;
   107608   }
   107609 
   107610 #ifdef SQLITE_TEST  /* For testing and debugging use only */
   107611   /* Record in the query plan information about the current table
   107612   ** and the index used to access it (if any).  If the table itself
   107613   ** is not used, its name is just '{}'.  If no index is used
   107614   ** the index is listed as "{}".  If the primary key is used the
   107615   ** index name is '*'.
   107616   */
   107617   for(i=0; i<nTabList; i++){
   107618     char *z;
   107619     int n;
   107620     pLevel = &pWInfo->a[i];
   107621     pTabItem = &pTabList->a[pLevel->iFrom];
   107622     z = pTabItem->zAlias;
   107623     if( z==0 ) z = pTabItem->pTab->zName;
   107624     n = sqlite3Strlen30(z);
   107625     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
   107626       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
   107627         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
   107628         nQPlan += 2;
   107629       }else{
   107630         memcpy(&sqlite3_query_plan[nQPlan], z, n);
   107631         nQPlan += n;
   107632       }
   107633       sqlite3_query_plan[nQPlan++] = ' ';
   107634     }
   107635     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
   107636     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
   107637     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   107638       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
   107639       nQPlan += 2;
   107640     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   107641       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
   107642       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
   107643         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
   107644         nQPlan += n;
   107645         sqlite3_query_plan[nQPlan++] = ' ';
   107646       }
   107647     }else{
   107648       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
   107649       nQPlan += 3;
   107650     }
   107651   }
   107652   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
   107653     sqlite3_query_plan[--nQPlan] = 0;
   107654   }
   107655   sqlite3_query_plan[nQPlan] = 0;
   107656   nQPlan = 0;
   107657 #endif /* SQLITE_TEST // Testing and debugging use only */
   107658 
   107659   /* Record the continuation address in the WhereInfo structure.  Then
   107660   ** clean up and return.
   107661   */
   107662   return pWInfo;
   107663 
   107664   /* Jump here if malloc fails */
   107665 whereBeginError:
   107666   if( pWInfo ){
   107667     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   107668     whereInfoFree(db, pWInfo);
   107669   }
   107670   return 0;
   107671 }
   107672 
   107673 /*
   107674 ** Generate the end of the WHERE loop.  See comments on
   107675 ** sqlite3WhereBegin() for additional information.
   107676 */
   107677 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   107678   Parse *pParse = pWInfo->pParse;
   107679   Vdbe *v = pParse->pVdbe;
   107680   int i;
   107681   WhereLevel *pLevel;
   107682   SrcList *pTabList = pWInfo->pTabList;
   107683   sqlite3 *db = pParse->db;
   107684 
   107685   /* Generate loop termination code.
   107686   */
   107687   sqlite3ExprCacheClear(pParse);
   107688   for(i=pWInfo->nLevel-1; i>=0; i--){
   107689     pLevel = &pWInfo->a[i];
   107690     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   107691     if( pLevel->op!=OP_Noop ){
   107692       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
   107693       sqlite3VdbeChangeP5(v, pLevel->p5);
   107694     }
   107695     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   107696       struct InLoop *pIn;
   107697       int j;
   107698       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   107699       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   107700         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   107701         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
   107702         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   107703       }
   107704       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   107705     }
   107706     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   107707     if( pLevel->iLeftJoin ){
   107708       int addr;
   107709       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
   107710       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107711            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
   107712       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
   107713         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   107714       }
   107715       if( pLevel->iIdxCur>=0 ){
   107716         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   107717       }
   107718       if( pLevel->op==OP_Return ){
   107719         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   107720       }else{
   107721         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   107722       }
   107723       sqlite3VdbeJumpHere(v, addr);
   107724     }
   107725   }
   107726 
   107727   /* The "break" point is here, just past the end of the outer loop.
   107728   ** Set it.
   107729   */
   107730   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   107731 
   107732   /* Close all of the cursors that were opened by sqlite3WhereBegin.
   107733   */
   107734   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
   107735   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   107736     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   107737     Table *pTab = pTabItem->pTab;
   107738     assert( pTab!=0 );
   107739     if( (pTab->tabFlags & TF_Ephemeral)==0
   107740      && pTab->pSelect==0
   107741      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
   107742     ){
   107743       int ws = pLevel->plan.wsFlags;
   107744       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
   107745         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   107746       }
   107747       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
   107748         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   107749       }
   107750     }
   107751 
   107752     /* If this scan uses an index, make code substitutions to read data
   107753     ** from the index in preference to the table. Sometimes, this means
   107754     ** the table need never be read from. This is a performance boost,
   107755     ** as the vdbe level waits until the table is read before actually
   107756     ** seeking the table cursor to the record corresponding to the current
   107757     ** position in the index.
   107758     **
   107759     ** Calls to the code generator in between sqlite3WhereBegin and
   107760     ** sqlite3WhereEnd will have created code that references the table
   107761     ** directly.  This loop scans all that code looking for opcodes
   107762     ** that reference the table and converts them into opcodes that
   107763     ** reference the index.
   107764     */
   107765     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
   107766       int k, j, last;
   107767       VdbeOp *pOp;
   107768       Index *pIdx = pLevel->plan.u.pIdx;
   107769 
   107770       assert( pIdx!=0 );
   107771       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
   107772       last = sqlite3VdbeCurrentAddr(v);
   107773       for(k=pWInfo->iTop; k<last; k++, pOp++){
   107774         if( pOp->p1!=pLevel->iTabCur ) continue;
   107775         if( pOp->opcode==OP_Column ){
   107776           for(j=0; j<pIdx->nColumn; j++){
   107777             if( pOp->p2==pIdx->aiColumn[j] ){
   107778               pOp->p2 = j;
   107779               pOp->p1 = pLevel->iIdxCur;
   107780               break;
   107781             }
   107782           }
   107783           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   107784                || j<pIdx->nColumn );
   107785         }else if( pOp->opcode==OP_Rowid ){
   107786           pOp->p1 = pLevel->iIdxCur;
   107787           pOp->opcode = OP_IdxRowid;
   107788         }
   107789       }
   107790     }
   107791   }
   107792 
   107793   /* Final cleanup
   107794   */
   107795   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   107796   whereInfoFree(db, pWInfo);
   107797   return;
   107798 }
   107799 
   107800 /************** End of where.c ***********************************************/
   107801 /************** Begin file parse.c *******************************************/
   107802 /* Driver template for the LEMON parser generator.
   107803 ** The author disclaims copyright to this source code.
   107804 **
   107805 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   107806 ** The only modifications are the addition of a couple of NEVER()
   107807 ** macros to disable tests that are needed in the case of a general
   107808 ** LALR(1) grammar but which are always false in the
   107809 ** specific grammar used by SQLite.
   107810 */
   107811 /* First off, code is included that follows the "include" declaration
   107812 ** in the input grammar file. */
   107813 /* #include <stdio.h> */
   107814 
   107815 
   107816 /*
   107817 ** Disable all error recovery processing in the parser push-down
   107818 ** automaton.
   107819 */
   107820 #define YYNOERRORRECOVERY 1
   107821 
   107822 /*
   107823 ** Make yytestcase() the same as testcase()
   107824 */
   107825 #define yytestcase(X) testcase(X)
   107826 
   107827 /*
   107828 ** An instance of this structure holds information about the
   107829 ** LIMIT clause of a SELECT statement.
   107830 */
   107831 struct LimitVal {
   107832   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   107833   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   107834 };
   107835 
   107836 /*
   107837 ** An instance of this structure is used to store the LIKE,
   107838 ** GLOB, NOT LIKE, and NOT GLOB operators.
   107839 */
   107840 struct LikeOp {
   107841   Token eOperator;  /* "like" or "glob" or "regexp" */
   107842   int not;         /* True if the NOT keyword is present */
   107843 };
   107844 
   107845 /*
   107846 ** An instance of the following structure describes the event of a
   107847 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   107848 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   107849 **
   107850 **      UPDATE ON (a,b,c)
   107851 **
   107852 ** Then the "b" IdList records the list "a,b,c".
   107853 */
   107854 struct TrigEvent { int a; IdList * b; };
   107855 
   107856 /*
   107857 ** An instance of this structure holds the ATTACH key and the key type.
   107858 */
   107859 struct AttachKey { int type;  Token key; };
   107860 
   107861 /*
   107862 ** One or more VALUES claues
   107863 */
   107864 struct ValueList {
   107865   ExprList *pList;
   107866   Select *pSelect;
   107867 };
   107868 
   107869 
   107870   /* This is a utility routine used to set the ExprSpan.zStart and
   107871   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   107872   ** range of text beginning with pStart and going to the end of pEnd.
   107873   */
   107874   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   107875     pOut->zStart = pStart->z;
   107876     pOut->zEnd = &pEnd->z[pEnd->n];
   107877   }
   107878 
   107879   /* Construct a new Expr object from a single identifier.  Use the
   107880   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   107881   ** that created the expression.
   107882   */
   107883   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   107884     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   107885     pOut->zStart = pValue->z;
   107886     pOut->zEnd = &pValue->z[pValue->n];
   107887   }
   107888 
   107889   /* This routine constructs a binary expression node out of two ExprSpan
   107890   ** objects and uses the result to populate a new ExprSpan object.
   107891   */
   107892   static void spanBinaryExpr(
   107893     ExprSpan *pOut,     /* Write the result here */
   107894     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   107895     int op,             /* The binary operation */
   107896     ExprSpan *pLeft,    /* The left operand */
   107897     ExprSpan *pRight    /* The right operand */
   107898   ){
   107899     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   107900     pOut->zStart = pLeft->zStart;
   107901     pOut->zEnd = pRight->zEnd;
   107902   }
   107903 
   107904   /* Construct an expression node for a unary postfix operator
   107905   */
   107906   static void spanUnaryPostfix(
   107907     ExprSpan *pOut,        /* Write the new expression node here */
   107908     Parse *pParse,         /* Parsing context to record errors */
   107909     int op,                /* The operator */
   107910     ExprSpan *pOperand,    /* The operand */
   107911     Token *pPostOp         /* The operand token for setting the span */
   107912   ){
   107913     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   107914     pOut->zStart = pOperand->zStart;
   107915     pOut->zEnd = &pPostOp->z[pPostOp->n];
   107916   }
   107917 
   107918   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   107919   ** unary TK_ISNULL or TK_NOTNULL expression. */
   107920   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   107921     sqlite3 *db = pParse->db;
   107922     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   107923       pA->op = (u8)op;
   107924       sqlite3ExprDelete(db, pA->pRight);
   107925       pA->pRight = 0;
   107926     }
   107927   }
   107928 
   107929   /* Construct an expression node for a unary prefix operator
   107930   */
   107931   static void spanUnaryPrefix(
   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 *pPreOp         /* The operand token for setting the span */
   107937   ){
   107938     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   107939     pOut->zStart = pPreOp->z;
   107940     pOut->zEnd = pOperand->zEnd;
   107941   }
   107942 /* Next is all token values, in a form suitable for use by makeheaders.
   107943 ** This section will be null unless lemon is run with the -m switch.
   107944 */
   107945 /*
   107946 ** These constants (all generated automatically by the parser generator)
   107947 ** specify the various kinds of tokens (terminals) that the parser
   107948 ** understands.
   107949 **
   107950 ** Each symbol here is a terminal symbol in the grammar.
   107951 */
   107952 /* Make sure the INTERFACE macro is defined.
   107953 */
   107954 #ifndef INTERFACE
   107955 # define INTERFACE 1
   107956 #endif
   107957 /* The next thing included is series of defines which control
   107958 ** various aspects of the generated parser.
   107959 **    YYCODETYPE         is the data type used for storing terminal
   107960 **                       and nonterminal numbers.  "unsigned char" is
   107961 **                       used if there are fewer than 250 terminals
   107962 **                       and nonterminals.  "int" is used otherwise.
   107963 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   107964 **                       to no legal terminal or nonterminal number.  This
   107965 **                       number is used to fill in empty slots of the hash
   107966 **                       table.
   107967 **    YYFALLBACK         If defined, this indicates that one or more tokens
   107968 **                       have fall-back values which should be used if the
   107969 **                       original value of the token will not parse.
   107970 **    YYACTIONTYPE       is the data type used for storing terminal
   107971 **                       and nonterminal numbers.  "unsigned char" is
   107972 **                       used if there are fewer than 250 rules and
   107973 **                       states combined.  "int" is used otherwise.
   107974 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   107975 **                       directly to the parser from the tokenizer.
   107976 **    YYMINORTYPE        is the data type used for all minor tokens.
   107977 **                       This is typically a union of many types, one of
   107978 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   107979 **                       for base tokens is called "yy0".
   107980 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   107981 **                       zero the stack is dynamically sized using realloc()
   107982 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   107983 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   107984 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   107985 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   107986 **    YYNSTATE           the combined number of states.
   107987 **    YYNRULE            the number of rules in the grammar
   107988 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   107989 **                       defined, then do no error processing.
   107990 */
   107991 #define YYCODETYPE unsigned char
   107992 #define YYNOCODE 251
   107993 #define YYACTIONTYPE unsigned short int
   107994 #define YYWILDCARD 67
   107995 #define sqlite3ParserTOKENTYPE Token
   107996 typedef union {
   107997   int yyinit;
   107998   sqlite3ParserTOKENTYPE yy0;
   107999   struct LimitVal yy64;
   108000   Expr* yy122;
   108001   Select* yy159;
   108002   IdList* yy180;
   108003   struct {int value; int mask;} yy207;
   108004   u8 yy258;
   108005   struct LikeOp yy318;
   108006   TriggerStep* yy327;
   108007   ExprSpan yy342;
   108008   SrcList* yy347;
   108009   int yy392;
   108010   struct TrigEvent yy410;
   108011   ExprList* yy442;
   108012   struct ValueList yy487;
   108013 } YYMINORTYPE;
   108014 #ifndef YYSTACKDEPTH
   108015 #define YYSTACKDEPTH 100
   108016 #endif
   108017 #define sqlite3ParserARG_SDECL Parse *pParse;
   108018 #define sqlite3ParserARG_PDECL ,Parse *pParse
   108019 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   108020 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   108021 #define YYNSTATE 629
   108022 #define YYNRULE 327
   108023 #define YYFALLBACK 1
   108024 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   108025 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   108026 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   108027 
   108028 /* The yyzerominor constant is used to initialize instances of
   108029 ** YYMINORTYPE objects to zero. */
   108030 static const YYMINORTYPE yyzerominor = { 0 };
   108031 
   108032 /* Define the yytestcase() macro to be a no-op if is not already defined
   108033 ** otherwise.
   108034 **
   108035 ** Applications can choose to define yytestcase() in the %include section
   108036 ** to a macro that can assist in verifying code coverage.  For production
   108037 ** code the yytestcase() macro should be turned off.  But it is useful
   108038 ** for testing.
   108039 */
   108040 #ifndef yytestcase
   108041 # define yytestcase(X)
   108042 #endif
   108043 
   108044 
   108045 /* Next are the tables used to determine what action to take based on the
   108046 ** current state and lookahead token.  These tables are used to implement
   108047 ** functions that take a state number and lookahead value and return an
   108048 ** action integer.
   108049 **
   108050 ** Suppose the action integer is N.  Then the action is determined as
   108051 ** follows
   108052 **
   108053 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   108054 **                                      token onto the stack and goto state N.
   108055 **
   108056 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   108057 **
   108058 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   108059 **
   108060 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   108061 **
   108062 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   108063 **                                      slots in the yy_action[] table.
   108064 **
   108065 ** The action table is constructed as a single large table named yy_action[].
   108066 ** Given state S and lookahead X, the action is computed as
   108067 **
   108068 **      yy_action[ yy_shift_ofst[S] + X ]
   108069 **
   108070 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   108071 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   108072 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   108073 ** and that yy_default[S] should be used instead.
   108074 **
   108075 ** The formula above is for computing the action when the lookahead is
   108076 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   108077 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   108078 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   108079 ** YY_SHIFT_USE_DFLT.
   108080 **
   108081 ** The following are the tables generated in this section:
   108082 **
   108083 **  yy_action[]        A single table containing all actions.
   108084 **  yy_lookahead[]     A table containing the lookahead for each entry in
   108085 **                     yy_action.  Used to detect hash collisions.
   108086 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   108087 **                     shifting terminals.
   108088 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   108089 **                     shifting non-terminals after a reduce.
   108090 **  yy_default[]       Default action for each state.
   108091 */
   108092 #define YY_ACTTAB_COUNT (1580)
   108093 static const YYACTIONTYPE yy_action[] = {
   108094  /*     0 */   310,  328,  574,  573,   15,  172,  187,  596,   56,   56,
   108095  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
   108096  /*    20 */    52,   52,   51,  234,  622,  621,  626,  622,  621,  299,
   108097  /*    30 */   589,  583,   56,   56,   56,   56,  236,   54,   54,   54,
   108098  /*    40 */    54,   53,   53,   52,   52,   52,   51,  234,  351,   57,
   108099  /*    50 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108100  /*    60 */    56,   56,  570,   54,   54,   54,   54,   53,   53,   52,
   108101  /*    70 */    52,   52,   51,  234,  310,  596,  326,  607,  233,  232,
   108102  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108103  /*    90 */    51,  234,  619,  618,  326,  619,  618,  166,  605,  492,
   108104  /*   100 */   381,  378,  377,  235,  589,  583,  554,  495,    1,   59,
   108105  /*   110 */    19,  376,  622,  621,   53,   53,   52,   52,   52,   51,
   108106  /*   120 */   234,  571,  571,   57,   58,   48,  581,  580,  582,  582,
   108107  /*   130 */    55,   55,   56,   56,   56,   56,  215,   54,   54,   54,
   108108  /*   140 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  224,
   108109  /*   150 */    50,   47,  147,  177,  139,  281,  384,  276,  383,  169,
   108110  /*   160 */   408,  553,  578,  578,  622,  621,  272,  224,  439,  550,
   108111  /*   170 */   552,  410,  139,  281,  384,  276,  383,  169,  589,  583,
   108112  /*   180 */   619,  618,  280,  620,  272,  195,  413,  309,  440,  441,
   108113  /*   190 */   567,  491,  214,  279,  560,  600,   92,   57,   58,   48,
   108114  /*   200 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108115  /*   210 */   559,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108116  /*   220 */    51,  234,  310,  464,  233,  232,  558,  133,  519,   50,
   108117  /*   230 */    47,  147,  619,  618,  565,  436,  397,  515,  514,  518,
   108118  /*   240 */   410,  387,  438,  389,  437,  622,  621,  442,  570,  433,
   108119  /*   250 */   203,  390,  589,  583,    6,  413,  166,  670,  250,  381,
   108120  /*   260 */   378,  377,  525,  190,  600,   92,  594,  571,  571,  465,
   108121  /*   270 */   376,   57,   58,   48,  581,  580,  582,  582,   55,   55,
   108122  /*   280 */    56,   56,   56,   56,  599,   54,   54,   54,   54,   53,
   108123  /*   290 */    53,   52,   52,   52,   51,  234,  310,  592,  592,  592,
   108124  /*   300 */   490,  182,  247,  548,  249,  397,  273,  410,    7,  439,
   108125  /*   310 */   398,  606,   67,  619,  618,  620,  472,  256,  347,  255,
   108126  /*   320 */   473,  620,  413,  576,  620,   65,  589,  583,  236,  440,
   108127  /*   330 */   336,  600,   92,   68,  364,  192,  481,  622,  621,  547,
   108128  /*   340 */   622,  621,  560,  323,  207,   57,   58,   48,  581,  580,
   108129  /*   350 */   582,  582,   55,   55,   56,   56,   56,   56,  559,   54,
   108130  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108131  /*   370 */   310,  410,  397,  146,  558,  531,  401,  348,  599,  166,
   108132  /*   380 */   248,  204,  381,  378,  377,  541,  413,  171,  337,  570,
   108133  /*   390 */   622,  621,   40,  376,   38,  600,   74,  465,  548,  490,
   108134  /*   400 */   589,  583,  532,  350,  579,  619,  618,  297,  619,  618,
   108135  /*   410 */   480,   67,  470,   39,  620,  599,  406,  574,  573,   57,
   108136  /*   420 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108137  /*   430 */    56,   56,  577,   54,   54,   54,   54,   53,   53,   52,
   108138  /*   440 */    52,   52,   51,  234,  310,  256,  347,  255,  530,   52,
   108139  /*   450 */    52,   52,   51,  234,  345,  564,  236,  386,  619,  618,
   108140  /*   460 */   957,  185,  418,    2,  408,  410,  578,  578,  198,  197,
   108141  /*   470 */   196,  499,  183,  167,  589,  583,  671,  570,  505,  506,
   108142  /*   480 */   413,  267,  601,  672,  546,  208,  602,   36,  601,  600,
   108143  /*   490 */    91,  468,  602,   57,   58,   48,  581,  580,  582,  582,
   108144  /*   500 */    55,   55,   56,   56,   56,   56,  202,   54,   54,   54,
   108145  /*   510 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  599,
   108146  /*   520 */   157,  408,  527,  578,  578,  263,  490,  265,  410,  873,
   108147  /*   530 */   410,  474,  474,  366,  373,  410,  504,  428,   67,  290,
   108148  /*   540 */   599,  620,  352,  413,  408,  413,  578,  578,  589,  583,
   108149  /*   550 */   413,  382,  600,   92,  600,   16,  543,   62,  503,  600,
   108150  /*   560 */    92,  408,  346,  578,  578,  168,   45,   57,   58,   48,
   108151  /*   570 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108152  /*   580 */   200,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108153  /*   590 */    51,  234,  310,  393,  395,  534,  510,  617,  616,  615,
   108154  /*   600 */   318,  314,  172,   66,  596,  410,  338,  596,  324,  571,
   108155  /*   610 */   571,   50,   47,  147,  599,  629,  627,  330,  539,  315,
   108156  /*   620 */   413,   30,  589,  583,  272,  236,  199,  144,  176,  600,
   108157  /*   630 */    73,  420,  947,  620,  947,  420,  946,  351,  946,  175,
   108158  /*   640 */   596,   57,   58,   48,  581,  580,  582,  582,   55,   55,
   108159  /*   650 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
   108160  /*   660 */    53,   52,   52,   52,   51,  234,  310,  261,  410,  413,
   108161  /*   670 */   269,  208,  596,  363,  410,  596,  424,  360,  600,   69,
   108162  /*   680 */   424,  327,  620,  413,   50,   47,  147,  410,  358,  413,
   108163  /*   690 */   575,  553,  600,   94,  483,  509,  589,  583,  600,   97,
   108164  /*   700 */   552,  484,  413,  620,  188,  599,  551,  563,  596,  566,
   108165  /*   710 */   334,  600,   95,  205,  201,   57,   58,   48,  581,  580,
   108166  /*   720 */   582,  582,   55,   55,   56,   56,   56,   56,  352,   54,
   108167  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108168  /*   740 */   310,  410,  261,  410,  167,   22,  356,  599,  359,  623,
   108169  /*   750 */    50,   47,  147,  548,  357,  562,  413,  620,  413,  332,
   108170  /*   760 */   523,  270,  410,  167,  620,  600,  104,  600,  103,  603,
   108171  /*   770 */   589,  583,  339,  539,  304,  423,  222,  413,  174,  304,
   108172  /*   780 */   422,  561,  567,  405,  214,  260,  600,  106,  620,   57,
   108173  /*   790 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108174  /*   800 */    56,   56,  410,   54,   54,   54,   54,   53,   53,   52,
   108175  /*   810 */    52,   52,   51,  234,  310,  410,  557,  413,  410,  421,
   108176  /*   820 */   273,   35,  512,  146,  421,   12,  600,  107,  213,  144,
   108177  /*   830 */   413,  410,   32,  413,  410,  620,  365,  353,  358,  600,
   108178  /*   840 */   134,   11,  600,  135,  589,  583,  413,   21,  548,  413,
   108179  /*   850 */   316,  148,  620,  620,  170,  600,   98,  223,  600,  102,
   108180  /*   860 */   374,  168,  167,   57,   58,   48,  581,  580,  582,  582,
   108181  /*   870 */    55,   55,   56,   56,   56,   56,  410,   54,   54,   54,
   108182  /*   880 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  410,
   108183  /*   890 */   273,  413,  410,  273,  212,  469,  410,  167,  628,    2,
   108184  /*   900 */   600,  101,  545,  221,  413,  620,  130,  413,  620,  410,
   108185  /*   910 */   539,  413,  537,  600,   93,  315,  600,  100,  589,  583,
   108186  /*   920 */   600,   77,  425,  305,  413,  620,  254,  322,  599,  458,
   108187  /*   930 */   320,  171,  543,  600,   96,  521,  520,   57,   58,   48,
   108188  /*   940 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
   108189  /*   950 */   410,   54,   54,   54,   54,   53,   53,   52,   52,   52,
   108190  /*   960 */    51,  234,  310,  410,  273,  413,  410,  457,  358,   35,
   108191  /*   970 */   426,  230,  306,  319,  600,  138,  467,  520,  413,  620,
   108192  /*   980 */   143,  413,  410,  620,  410,  353,  529,  600,  137,  142,
   108193  /*   990 */   600,  136,  589,  583,  604,  261,  528,  413,  229,  413,
   108194  /*  1000 */   620,  321,  495,   28,  543,  543,  600,   76,  600,   90,
   108195  /*  1010 */   620,   57,   46,   48,  581,  580,  582,  582,   55,   55,
   108196  /*  1020 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
   108197  /*  1030 */    53,   52,   52,   52,   51,  234,  310,  261,  451,  413,
   108198  /*  1040 */   410,  211,  611,  285,  283,  610,  609,  502,  600,   89,
   108199  /*  1050 */   380,  217,  620,  128,  140,  413,  220,  620,  410,  409,
   108200  /*  1060 */   620,  620,  588,  587,  600,   75,  589,  583,  271,  620,
   108201  /*  1070 */    51,  234,  127,  413,  620,  599,  627,  330,   27,  375,
   108202  /*  1080 */   449,  279,  600,   88,  585,  584,   58,   48,  581,  580,
   108203  /*  1090 */   582,  582,   55,   55,   56,   56,   56,   56,  410,   54,
   108204  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
   108205  /*  1110 */   310,  586,  410,  413,  410,  261,  593,  165,  399,  556,
   108206  /*  1120 */   126,  371,  600,   87,  478,  186,  123,  413,  367,  413,
   108207  /*  1130 */   620,  620,  410,  620,  620,  410,  600,   99,  600,   86,
   108208  /*  1140 */   589,  583,  475,  122,  258,  171,  471,  413,  160,  121,
   108209  /*  1150 */   413,   14,  159,  463,   25,   24,  600,   17,  448,  600,
   108210  /*  1160 */    85,   48,  581,  580,  582,  582,   55,   55,   56,   56,
   108211  /*  1170 */    56,   56,  158,   54,   54,   54,   54,   53,   53,   52,
   108212  /*  1180 */    52,   52,   51,  234,   44,  404,  261,    3,  544,  261,
   108213  /*  1190 */   540,  414,  621,  460,  119,  118,  538,  275,   10,  349,
   108214  /*  1200 */     4,  620,  407,  620,  620,  620,  116,   44,  404,  410,
   108215  /*  1210 */     3,  620,  620,  410,  414,  621,  456,  454,  252,  450,
   108216  /*  1220 */   508,  402,  111,  109,  413,  407,  155,  444,  413,  447,
   108217  /*  1230 */   435,  565,  219,  600,   84,  620,  108,  600,   83,   64,
   108218  /*  1240 */   434,  417,  625,  150,  402,  333,  410,  237,  238,  124,
   108219  /*  1250 */   274,   41,   42,  533,  565,  206,  189,  261,   43,  412,
   108220  /*  1260 */   411,  413,  261,  594,  488,  620,  329,  149,  419,  268,
   108221  /*  1270 */   600,   72,  620,  266,   41,   42,  181,  620,  410,  620,
   108222  /*  1280 */   105,   43,  412,  411,  620,  624,  594,  614,  620,  599,
   108223  /*  1290 */   228,  125,  313,  413,  592,  592,  592,  591,  590,   13,
   108224  /*  1300 */   218,  410,  600,   71,  236,  244,   44,  404,  264,    3,
   108225  /*  1310 */   312,  613,  340,  414,  621,  180,  413,  592,  592,  592,
   108226  /*  1320 */   591,  590,   13,  620,  407,  600,   82,  410,  416,   34,
   108227  /*  1330 */   404,  410,    3,  410,  262,  410,  414,  621,  612,  331,
   108228  /*  1340 */   178,  415,  413,  402,    8,  236,  413,  407,  413,  620,
   108229  /*  1350 */   413,  600,   81,  565,  257,  600,   80,  600,   70,  600,
   108230  /*  1360 */    18,  598,  361,  462,  461,   30,  402,  294,   31,  620,
   108231  /*  1370 */   293,  354,  251,   41,   42,  410,  565,  620,  620,  620,
   108232  /*  1380 */    43,  412,  411,  453,  396,  594,  620,  620,  394,   61,
   108233  /*  1390 */   413,  292,  443,  622,  621,  243,   41,   42,  620,  600,
   108234  /*  1400 */    79,  597,  291,   43,  412,  411,   60,  620,  594,  240,
   108235  /*  1410 */   620,  410,  231,   37,  555,  173,  592,  592,  592,  591,
   108236  /*  1420 */   590,   13,  216,  239,  620,  184,  413,  302,  301,  300,
   108237  /*  1430 */   179,  298,  388,  565,  452,  600,   78,  286,  620,  592,
   108238  /*  1440 */   592,  592,  591,  590,   13,  429,   29,  413,  151,  289,
   108239  /*  1450 */   242,  145,  392,  194,  193,  288,  600,    9,  542,  241,
   108240  /*  1460 */   620,  525,  391,  284,  620,  594,  620,  620,  522,  536,
   108241  /*  1470 */   620,  535,  153,  385,  465,  516,  282,  325,  154,  517,
   108242  /*  1480 */   277,  152,  512,  511,  513,  129,  226,  308,  487,  486,
   108243  /*  1490 */   485,  164,  372,  493,  307,  227,  592,  592,  592,  225,
   108244  /*  1500 */   479,  163,  368,  370,  162,  476,  210,  477,   26,  259,
   108245  /*  1510 */   161,  466,  362,  141,  132,  120,  117,  455,  156,  115,
   108246  /*  1520 */   344,  343,  256,  342,  245,  114,  113,  446,  311,  112,
   108247  /*  1530 */    23,  317,  432,  236,  131,  431,  110,  430,   20,  427,
   108248  /*  1540 */   608,  595,  295,   63,  379,  287,  509,  191,  278,  403,
   108249  /*  1550 */   572,  569,  497,  498,  496,  494,  335,  459,  445,  303,
   108250  /*  1560 */   296,  246,  341,  355,    5,  568,  369,  507,  253,  549,
   108251  /*  1570 */   526,  209,  400,  501,  500,  524,  234,  958,  489,  482,
   108252 };
   108253 static const YYCODETYPE yy_lookahead[] = {
   108254  /*     0 */    19,  169,  170,  171,   22,   24,   24,   26,   77,   78,
   108255  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
   108256  /*    20 */    89,   90,   91,   92,   26,   27,    1,   26,   27,   15,
   108257  /*    30 */    49,   50,   77,   78,   79,   80,  116,   82,   83,   84,
   108258  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,  128,   68,
   108259  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108260  /*    60 */    79,   80,  230,   82,   83,   84,   85,   86,   87,   88,
   108261  /*    70 */    89,   90,   91,   92,   19,   94,   19,   23,   86,   87,
   108262  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108263  /*    90 */    91,   92,   94,   95,   19,   94,   95,   96,  172,  173,
   108264  /*   100 */    99,  100,  101,  197,   49,   50,  177,  181,   22,   54,
   108265  /*   110 */   204,  110,   26,   27,   86,   87,   88,   89,   90,   91,
   108266  /*   120 */    92,  129,  130,   68,   69,   70,   71,   72,   73,   74,
   108267  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
   108268  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
   108269  /*   150 */   221,  222,  223,   96,   97,   98,   99,  100,  101,  102,
   108270  /*   160 */   112,   32,  114,  115,   26,   27,  109,   92,  150,   25,
   108271  /*   170 */    41,  150,   97,   98,   99,  100,  101,  102,   49,   50,
   108272  /*   180 */    94,   95,   98,  165,  109,   25,  165,  163,  170,  171,
   108273  /*   190 */   166,  167,  168,  109,   12,  174,  175,   68,   69,   70,
   108274  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108275  /*   210 */    28,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108276  /*   220 */    91,   92,   19,   11,   86,   87,   44,   24,   46,  221,
   108277  /*   230 */   222,  223,   94,   95,   66,   97,  215,    7,    8,   57,
   108278  /*   240 */   150,  220,  104,   19,  106,   26,   27,  229,  230,  241,
   108279  /*   250 */   160,   27,   49,   50,   22,  165,   96,  118,   16,   99,
   108280  /*   260 */   100,  101,   94,  119,  174,  175,   98,  129,  130,   57,
   108281  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108282  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
   108283  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
   108284  /*   300 */   150,   23,   60,   25,   62,  215,  150,  150,   76,  150,
   108285  /*   310 */   220,  161,  162,   94,   95,  165,   30,  105,  106,  107,
   108286  /*   320 */    34,  165,  165,   23,  165,   25,   49,   50,  116,  170,
   108287  /*   330 */   171,  174,  175,   22,   48,  185,  186,   26,   27,  120,
   108288  /*   340 */    26,   27,   12,  187,  160,   68,   69,   70,   71,   72,
   108289  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   28,   82,
   108290  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108291  /*   370 */    19,  150,  215,   95,   44,   23,   46,  220,  194,   96,
   108292  /*   380 */   138,  160,   99,  100,  101,   23,  165,   25,  229,  230,
   108293  /*   390 */    26,   27,  135,  110,  137,  174,  175,   57,  120,  150,
   108294  /*   400 */    49,   50,   88,  219,  113,   94,   95,  158,   94,   95,
   108295  /*   410 */   161,  162,   21,  136,  165,  194,  169,  170,  171,   68,
   108296  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108297  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
   108298  /*   440 */    89,   90,   91,   92,   19,  105,  106,  107,   23,   88,
   108299  /*   450 */    89,   90,   91,   92,   63,   23,  116,   88,   94,   95,
   108300  /*   460 */   142,  143,  144,  145,  112,  150,  114,  115,  105,  106,
   108301  /*   470 */   107,   23,   23,   25,   49,   50,  118,  230,   97,   98,
   108302  /*   480 */   165,   16,  113,  118,  120,  160,  117,  136,  113,  174,
   108303  /*   490 */   175,  100,  117,   68,   69,   70,   71,   72,   73,   74,
   108304  /*   500 */    75,   76,   77,   78,   79,   80,  160,   82,   83,   84,
   108305  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
   108306  /*   520 */    25,  112,   23,  114,  115,   60,  150,   62,  150,  138,
   108307  /*   530 */   150,  105,  106,  107,   19,  150,   36,  161,  162,  224,
   108308  /*   540 */   194,  165,  217,  165,  112,  165,  114,  115,   49,   50,
   108309  /*   550 */   165,   51,  174,  175,  174,  175,  166,  232,   58,  174,
   108310  /*   560 */   175,  112,  237,  114,  115,   50,   22,   68,   69,   70,
   108311  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108312  /*   580 */   160,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108313  /*   590 */    91,   92,   19,  215,  214,  205,   23,    7,    8,    9,
   108314  /*   600 */   215,  155,   24,   22,   26,  150,   97,   26,  108,  129,
   108315  /*   610 */   130,  221,  222,  223,  194,    0,    1,    2,  150,  104,
   108316  /*   620 */   165,  126,   49,   50,  109,  116,  206,  207,  118,  174,
   108317  /*   630 */   175,   22,   23,  165,   25,   22,   23,  128,   25,  118,
   108318  /*   640 */    26,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108319  /*   650 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   108320  /*   660 */    87,   88,   89,   90,   91,   92,   19,  150,  150,  165,
   108321  /*   670 */    23,  160,   94,  227,  150,   94,   67,  231,  174,  175,
   108322  /*   680 */    67,  213,  165,  165,  221,  222,  223,  150,  150,  165,
   108323  /*   690 */    23,   32,  174,  175,  181,  182,   49,   50,  174,  175,
   108324  /*   700 */    41,  188,  165,  165,   22,  194,  177,   11,   94,   23,
   108325  /*   710 */   193,  174,  175,  160,   22,   68,   69,   70,   71,   72,
   108326  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  217,   82,
   108327  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108328  /*   740 */    19,  150,  150,  150,   25,   24,   19,  194,  237,  150,
   108329  /*   750 */   221,  222,  223,   25,   27,   23,  165,  165,  165,  242,
   108330  /*   760 */   165,   23,  150,   25,  165,  174,  175,  174,  175,  174,
   108331  /*   770 */    49,   50,  219,  150,   22,   23,  238,  165,   25,   22,
   108332  /*   780 */    23,   23,  166,  167,  168,  193,  174,  175,  165,   68,
   108333  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108334  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
   108335  /*   810 */    89,   90,   91,   92,   19,  150,   23,  165,  150,   67,
   108336  /*   820 */   150,   25,  103,   95,   67,   35,  174,  175,  206,  207,
   108337  /*   830 */   165,  150,   25,  165,  150,  165,  213,  150,  150,  174,
   108338  /*   840 */   175,   35,  174,  175,   49,   50,  165,   52,  120,  165,
   108339  /*   850 */   245,  246,  165,  165,   35,  174,  175,  187,  174,  175,
   108340  /*   860 */    23,   50,   25,   68,   69,   70,   71,   72,   73,   74,
   108341  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
   108342  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
   108343  /*   890 */   150,  165,  150,  150,  160,   23,  150,   25,  144,  145,
   108344  /*   900 */   174,  175,  120,  216,  165,  165,   22,  165,  165,  150,
   108345  /*   910 */   150,  165,   27,  174,  175,  104,  174,  175,   49,   50,
   108346  /*   920 */   174,  175,  247,  248,  165,  165,  238,  187,  194,   23,
   108347  /*   930 */   187,   25,  166,  174,  175,  190,  191,   68,   69,   70,
   108348  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   108349  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   108350  /*   960 */    91,   92,   19,  150,  150,  165,  150,   23,  150,   25,
   108351  /*   970 */    23,  205,   25,  213,  174,  175,  190,  191,  165,  165,
   108352  /*   980 */   118,  165,  150,  165,  150,  150,   23,  174,  175,   39,
   108353  /*   990 */   174,  175,   49,   50,  173,  150,   23,  165,   52,  165,
   108354  /*  1000 */   165,  187,  181,   22,  166,  166,  174,  175,  174,  175,
   108355  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   108356  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   108357  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
   108358  /*  1040 */   150,  160,  150,  205,  205,  150,  150,   29,  174,  175,
   108359  /*  1050 */    52,  216,  165,   22,  150,  165,  238,  165,  150,  150,
   108360  /*  1060 */   165,  165,   49,   50,  174,  175,   49,   50,   23,  165,
   108361  /*  1070 */    91,   92,   22,  165,  165,  194,    1,    2,   22,   52,
   108362  /*  1080 */   193,  109,  174,  175,   71,   72,   69,   70,   71,   72,
   108363  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
   108364  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   108365  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  102,  150,  150,
   108366  /*  1120 */    22,   19,  174,  175,   20,   24,  104,  165,   43,  165,
   108367  /*  1130 */   165,  165,  150,  165,  165,  150,  174,  175,  174,  175,
   108368  /*  1140 */    49,   50,   59,   53,  138,   25,   53,  165,  104,   22,
   108369  /*  1150 */   165,    5,  118,    1,   76,   76,  174,  175,  193,  174,
   108370  /*  1160 */   175,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   108371  /*  1170 */    79,   80,   35,   82,   83,   84,   85,   86,   87,   88,
   108372  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,  150,
   108373  /*  1190 */   150,   26,   27,   27,  108,  127,  150,  150,   22,   25,
   108374  /*  1200 */    22,  165,   37,  165,  165,  165,  119,   19,   20,  150,
   108375  /*  1210 */    22,  165,  165,  150,   26,   27,   23,    1,   16,   20,
   108376  /*  1220 */   150,   56,  119,  108,  165,   37,  121,  128,  165,  193,
   108377  /*  1230 */    23,   66,  193,  174,  175,  165,  127,  174,  175,   16,
   108378  /*  1240 */    23,  146,  147,   15,   56,   65,  150,  152,  140,  154,
   108379  /*  1250 */   150,   86,   87,   88,   66,  160,   22,  150,   93,   94,
   108380  /*  1260 */    95,  165,  150,   98,  150,  165,    3,  246,    4,  150,
   108381  /*  1270 */   174,  175,  165,  150,   86,   87,    6,  165,  150,  165,
   108382  /*  1280 */   164,   93,   94,   95,  165,  149,   98,  149,  165,  194,
   108383  /*  1290 */   180,  180,  249,  165,  129,  130,  131,  132,  133,  134,
   108384  /*  1300 */   193,  150,  174,  175,  116,  193,   19,   20,  150,   22,
   108385  /*  1310 */   249,  149,  217,   26,   27,  151,  165,  129,  130,  131,
   108386  /*  1320 */   132,  133,  134,  165,   37,  174,  175,  150,  149,   19,
   108387  /*  1330 */    20,  150,   22,  150,  150,  150,   26,   27,   13,  244,
   108388  /*  1340 */   151,  159,  165,   56,   25,  116,  165,   37,  165,  165,
   108389  /*  1350 */   165,  174,  175,   66,  150,  174,  175,  174,  175,  174,
   108390  /*  1360 */   175,  194,  150,  150,  150,  126,   56,  199,  124,  165,
   108391  /*  1370 */   200,  150,  150,   86,   87,  150,   66,  165,  165,  165,
   108392  /*  1380 */    93,   94,   95,  150,  122,   98,  165,  165,  123,   22,
   108393  /*  1390 */   165,  201,  150,   26,   27,  150,   86,   87,  165,  174,
   108394  /*  1400 */   175,  203,  202,   93,   94,   95,  125,  165,   98,  150,
   108395  /*  1410 */   165,  150,  225,  135,  157,  118,  129,  130,  131,  132,
   108396  /*  1420 */   133,  134,    5,  150,  165,  157,  165,   10,   11,   12,
   108397  /*  1430 */    13,   14,  150,   66,   17,  174,  175,  210,  165,  129,
   108398  /*  1440 */   130,  131,  132,  133,  134,  150,  104,  165,   31,  150,
   108399  /*  1450 */    33,  150,  150,   86,   87,  150,  174,  175,  211,   42,
   108400  /*  1460 */   165,   94,  121,  210,  165,   98,  165,  165,  176,  211,
   108401  /*  1470 */   165,  211,   55,  104,   57,  184,  210,   47,   61,  176,
   108402  /*  1480 */   176,   64,  103,  176,  178,   22,   92,  179,  176,  176,
   108403  /*  1490 */   176,  156,   18,  184,  179,  228,  129,  130,  131,  228,
   108404  /*  1500 */   157,  156,   45,  157,  156,  236,  157,  157,  135,  235,
   108405  /*  1510 */   156,  189,  157,   68,  218,  189,   22,  199,  156,  192,
   108406  /*  1520 */   157,   18,  105,  106,  107,  192,  192,  199,  111,  192,
   108407  /*  1530 */   240,  157,   40,  116,  218,  157,  189,  157,  240,   38,
   108408  /*  1540 */   153,  166,  198,  243,  178,  209,  182,  196,  177,  226,
   108409  /*  1550 */   230,  230,  166,  177,  177,  166,  139,  199,  199,  148,
   108410  /*  1560 */   195,  209,  209,  239,  196,  166,  234,  183,  239,  208,
   108411  /*  1570 */   174,  233,  191,  183,  183,  174,   92,  250,  186,  186,
   108412 };
   108413 #define YY_SHIFT_USE_DFLT (-81)
   108414 #define YY_SHIFT_COUNT (417)
   108415 #define YY_SHIFT_MIN   (-80)
   108416 #define YY_SHIFT_MAX   (1503)
   108417 static const short yy_shift_ofst[] = {
   108418  /*     0 */  1075, 1188, 1417, 1188, 1287, 1287,  138,  138,    1,  -19,
   108419  /*    10 */  1287, 1287, 1287, 1287,  340,   -2,  129,  129,  795, 1165,
   108420  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108421  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108422  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
   108423  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
   108424  /*    60 */  1287, 1287,  212,   -2,   -2,   -8,   -8,  614, 1229,   55,
   108425  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
   108426  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
   108427  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
   108428  /*   100 */   -45,  -45,  -45,  -45,   -1,   57,   28,  361,   -2,   -2,
   108429  /*   110 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108430  /*   120 */    -2,   -2,   -2,   -2,  391,  515,   -2,   -2,   -2,   -2,
   108431  /*   130 */    -2,  509,  -80,  614,  979, 1484,  -81,  -81,  -81, 1367,
   108432  /*   140 */    75,  182,  182,  314,  311,  364,  219,   86,  613,  609,
   108433  /*   150 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108434  /*   160 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108435  /*   170 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
   108436  /*   180 */    -2,   -2,  578,  578,  578,  615, 1229, 1229, 1229,  -81,
   108437  /*   190 */   -81,  -81,  160,  168,  168,  283,  500,  500,  500,  278,
   108438  /*   200 */   449,  330,  432,  409,  352,   48,   48,   48,   48,  426,
   108439  /*   210 */   286,   48,   48,  728,  581,  369,  590,  495,  224,  224,
   108440  /*   220 */   727,  495,  727,  719,  614,  659,  614,  659,  811,  659,
   108441  /*   230 */   224,  257,  480,  480,  614,  144,  375,  -18, 1501, 1297,
   108442  /*   240 */  1297, 1492, 1492, 1297, 1494, 1445, 1239, 1503, 1503, 1503,
   108443  /*   250 */  1503, 1297, 1474, 1239, 1494, 1445, 1445, 1297, 1474, 1373,
   108444  /*   260 */  1457, 1297, 1297, 1474, 1297, 1474, 1297, 1474, 1463, 1369,
   108445  /*   270 */  1369, 1369, 1430, 1394, 1394, 1463, 1369, 1379, 1369, 1430,
   108446  /*   280 */  1369, 1369, 1341, 1342, 1341, 1342, 1341, 1342, 1297, 1297,
   108447  /*   290 */  1278, 1281, 1262, 1244, 1265, 1239, 1229, 1319, 1325, 1325,
   108448  /*   300 */  1270, 1270, 1270, 1270,  -81,  -81,  -81,  -81,  -81,  -81,
   108449  /*   310 */  1013,  242,  757,  752,  465,  363,  947,  232,  944,  906,
   108450  /*   320 */   872,  837,  738,  448,  381,  230,   84,  362,  300, 1264,
   108451  /*   330 */  1263, 1234, 1108, 1228, 1180, 1223, 1217, 1207, 1099, 1174,
   108452  /*   340 */  1109, 1115, 1103, 1199, 1105, 1202, 1216, 1087, 1193, 1178,
   108453  /*   350 */  1174, 1176, 1068, 1079, 1078, 1086, 1166, 1137, 1034, 1152,
   108454  /*   360 */  1146, 1127, 1044, 1006, 1093, 1120, 1090, 1083, 1085, 1022,
   108455  /*   370 */  1101, 1104, 1102,  972, 1015, 1098, 1027, 1056, 1050, 1045,
   108456  /*   380 */  1031,  998, 1018,  981,  946,  950,  973,  963,  862,  885,
   108457  /*   390 */   819,  884,  782,  796,  806,  807,  790,  796,  793,  758,
   108458  /*   400 */   753,  732,  692,  696,  682,  686,  667,  544,  291,  521,
   108459  /*   410 */   510,  365,  358,  139,  114,   54,   14,   25,
   108460 };
   108461 #define YY_REDUCE_USE_DFLT (-169)
   108462 #define YY_REDUCE_COUNT (309)
   108463 #define YY_REDUCE_MIN   (-168)
   108464 #define YY_REDUCE_MAX   (1411)
   108465 static const short yy_reduce_ofst[] = {
   108466  /*     0 */   318,   90, 1095,  221,  157,   21,  159,   18,  150,  390,
   108467  /*    10 */   385,  378,  380,  315,  325,  249,  529,  -71,    8, 1282,
   108468  /*    20 */  1261, 1225, 1185, 1183, 1181, 1177, 1151, 1128, 1096, 1063,
   108469  /*    30 */  1059,  985,  982,  964,  962,  948,  908,  890,  874,  834,
   108470  /*    40 */   832,  816,  813,  800,  759,  746,  742,  739,  726,  684,
   108471  /*    50 */   681,  668,  665,  652,  612,  593,  591,  537,  524,  518,
   108472  /*    60 */   504,  455,  511,  376,  517,  247, -168,   24,  420,  463,
   108473  /*    70 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108474  /*    80 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108475  /*    90 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
   108476  /*   100 */   463,  463,  463,  463,  463,  -74,  463,  463, 1112,  835,
   108477  /*   110 */  1107, 1039, 1036,  965,  887,  845,  818,  760,  688,  687,
   108478  /*   120 */   538,  743,  623,  592,  446,  513,  814,  740,  670,  156,
   108479  /*   130 */   468,  553,  184,  616,  463,  463,  463,  463,  463,  595,
   108480  /*   140 */   821,  786,  745,  909, 1305, 1302, 1301, 1299,  675,  675,
   108481  /*   150 */  1295, 1273, 1259, 1245, 1242, 1233, 1222, 1221, 1214, 1213,
   108482  /*   160 */  1212, 1204, 1184, 1158, 1123, 1119, 1114, 1100, 1070, 1047,
   108483  /*   170 */  1046, 1040, 1038,  969,  968,  966,  909,  904,  896,  895,
   108484  /*   180 */   892,  599,  839,  838,  766,  754,  881,  734,  346,  605,
   108485  /*   190 */   622,  -94, 1393, 1401, 1396, 1392, 1391, 1390, 1384, 1361,
   108486  /*   200 */  1365, 1381, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1332,
   108487  /*   210 */  1338, 1365, 1365, 1361, 1399, 1368, 1411, 1359, 1353, 1352,
   108488  /*   220 */  1329, 1358, 1324, 1366, 1389, 1377, 1386, 1376, 1364, 1371,
   108489  /*   230 */  1336, 1323, 1321, 1320, 1375, 1344, 1351, 1387, 1300, 1380,
   108490  /*   240 */  1378, 1298, 1290, 1374, 1316, 1347, 1328, 1337, 1334, 1333,
   108491  /*   250 */  1327, 1363, 1362, 1318, 1296, 1326, 1322, 1355, 1354, 1269,
   108492  /*   260 */  1274, 1350, 1349, 1348, 1346, 1345, 1343, 1335, 1315, 1314,
   108493  /*   270 */  1313, 1312, 1309, 1271, 1267, 1308, 1307, 1306, 1304, 1291,
   108494  /*   280 */  1303, 1292, 1260, 1266, 1258, 1253, 1247, 1227, 1268, 1257,
   108495  /*   290 */  1187, 1198, 1200, 1190, 1170, 1168, 1167, 1182, 1189, 1164,
   108496  /*   300 */  1179, 1162, 1138, 1136, 1061, 1043, 1021, 1111, 1110, 1116,
   108497 };
   108498 static const YYACTIONTYPE yy_default[] = {
   108499  /*     0 */   634,  868,  956,  956,  868,  868,  956,  956,  956,  758,
   108500  /*    10 */   956,  956,  956,  866,  956,  956,  786,  786,  930,  956,
   108501  /*    20 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108502  /*    30 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108503  /*    40 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108504  /*    50 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108505  /*    60 */   956,  956,  956,  956,  956,  956,  956,  673,  762,  792,
   108506  /*    70 */   956,  956,  956,  956,  956,  956,  956,  956,  929,  931,
   108507  /*    80 */   800,  799,  909,  773,  797,  790,  794,  869,  862,  863,
   108508  /*    90 */   861,  865,  870,  956,  793,  829,  846,  828,  840,  845,
   108509  /*   100 */   852,  844,  841,  831,  830,  665,  832,  833,  956,  956,
   108510  /*   110 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108511  /*   120 */   956,  956,  956,  956,  660,  727,  956,  956,  956,  956,
   108512  /*   130 */   956,  956,  956,  956,  834,  835,  849,  848,  847,  956,
   108513  /*   140 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108514  /*   150 */   956,  936,  934,  956,  881,  956,  956,  956,  956,  956,
   108515  /*   160 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108516  /*   170 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108517  /*   180 */   956,  640,  758,  758,  758,  634,  956,  956,  956,  948,
   108518  /*   190 */   762,  752,  718,  956,  956,  956,  956,  956,  956,  956,
   108519  /*   200 */   956,  956,  956,  956,  956,  802,  741,  919,  921,  956,
   108520  /*   210 */   902,  739,  662,  760,  675,  750,  642,  796,  775,  775,
   108521  /*   220 */   914,  796,  914,  699,  956,  786,  956,  786,  696,  786,
   108522  /*   230 */   775,  864,  956,  956,  956,  759,  750,  956,  941,  766,
   108523  /*   240 */   766,  933,  933,  766,  808,  731,  796,  738,  738,  738,
   108524  /*   250 */   738,  766,  657,  796,  808,  731,  731,  766,  657,  908,
   108525  /*   260 */   906,  766,  766,  657,  766,  657,  766,  657,  874,  729,
   108526  /*   270 */   729,  729,  714,  878,  878,  874,  729,  699,  729,  714,
   108527  /*   280 */   729,  729,  779,  774,  779,  774,  779,  774,  766,  766,
   108528  /*   290 */   956,  791,  780,  789,  787,  796,  956,  717,  650,  650,
   108529  /*   300 */   639,  639,  639,  639,  953,  953,  948,  701,  701,  683,
   108530  /*   310 */   956,  956,  956,  956,  956,  956,  956,  883,  956,  956,
   108531  /*   320 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108532  /*   330 */   635,  943,  956,  956,  940,  956,  956,  956,  956,  801,
   108533  /*   340 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108534  /*   350 */   918,  956,  956,  956,  956,  956,  956,  956,  912,  956,
   108535  /*   360 */   956,  956,  956,  956,  956,  905,  904,  956,  956,  956,
   108536  /*   370 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108537  /*   380 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
   108538  /*   390 */   956,  956,  956,  788,  956,  781,  956,  867,  956,  956,
   108539  /*   400 */   956,  956,  956,  956,  956,  956,  956,  956,  744,  817,
   108540  /*   410 */   956,  816,  820,  815,  667,  956,  648,  956,  631,  636,
   108541  /*   420 */   952,  955,  954,  951,  950,  949,  944,  942,  939,  938,
   108542  /*   430 */   937,  935,  932,  928,  887,  885,  892,  891,  890,  889,
   108543  /*   440 */   888,  886,  884,  882,  803,  798,  795,  927,  880,  740,
   108544  /*   450 */   737,  736,  656,  945,  911,  920,  807,  806,  809,  917,
   108545  /*   460 */   916,  915,  913,  910,  897,  805,  804,  732,  872,  871,
   108546  /*   470 */   659,  901,  900,  899,  903,  907,  898,  768,  658,  655,
   108547  /*   480 */   664,  721,  720,  728,  726,  725,  724,  723,  722,  719,
   108548  /*   490 */   666,  674,  685,  713,  698,  697,  877,  879,  876,  875,
   108549  /*   500 */   706,  705,  711,  710,  709,  708,  707,  704,  703,  702,
   108550  /*   510 */   695,  694,  700,  693,  716,  715,  712,  692,  735,  734,
   108551  /*   520 */   733,  730,  691,  690,  689,  820,  688,  687,  826,  825,
   108552  /*   530 */   813,  856,  755,  754,  753,  765,  764,  777,  776,  811,
   108553  /*   540 */   810,  778,  763,  757,  756,  772,  771,  770,  769,  761,
   108554  /*   550 */   751,  783,  785,  784,  782,  858,  767,  855,  926,  925,
   108555  /*   560 */   924,  923,  922,  860,  859,  827,  824,  678,  679,  895,
   108556  /*   570 */   894,  896,  893,  681,  680,  677,  676,  857,  746,  745,
   108557  /*   580 */   853,  850,  842,  838,  854,  851,  843,  839,  837,  836,
   108558  /*   590 */   822,  821,  819,  818,  814,  823,  669,  747,  743,  742,
   108559  /*   600 */   812,  749,  748,  686,  684,  682,  663,  661,  654,  652,
   108560  /*   610 */   651,  653,  649,  647,  646,  645,  644,  643,  672,  671,
   108561  /*   620 */   670,  668,  667,  641,  638,  637,  633,  632,  630,
   108562 };
   108563 
   108564 /* The next table maps tokens into fallback tokens.  If a construct
   108565 ** like the following:
   108566 **
   108567 **      %fallback ID X Y Z.
   108568 **
   108569 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   108570 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   108571 ** but it does not parse, the type of the token is changed to ID and
   108572 ** the parse is retried before an error is thrown.
   108573 */
   108574 #ifdef YYFALLBACK
   108575 static const YYCODETYPE yyFallback[] = {
   108576     0,  /*          $ => nothing */
   108577     0,  /*       SEMI => nothing */
   108578    26,  /*    EXPLAIN => ID */
   108579    26,  /*      QUERY => ID */
   108580    26,  /*       PLAN => ID */
   108581    26,  /*      BEGIN => ID */
   108582     0,  /* TRANSACTION => nothing */
   108583    26,  /*   DEFERRED => ID */
   108584    26,  /*  IMMEDIATE => ID */
   108585    26,  /*  EXCLUSIVE => ID */
   108586     0,  /*     COMMIT => nothing */
   108587    26,  /*        END => ID */
   108588    26,  /*   ROLLBACK => ID */
   108589    26,  /*  SAVEPOINT => ID */
   108590    26,  /*    RELEASE => ID */
   108591     0,  /*         TO => nothing */
   108592     0,  /*      TABLE => nothing */
   108593     0,  /*     CREATE => nothing */
   108594    26,  /*         IF => ID */
   108595     0,  /*        NOT => nothing */
   108596     0,  /*     EXISTS => nothing */
   108597    26,  /*       TEMP => ID */
   108598     0,  /*         LP => nothing */
   108599     0,  /*         RP => nothing */
   108600     0,  /*         AS => nothing */
   108601     0,  /*      COMMA => nothing */
   108602     0,  /*         ID => nothing */
   108603     0,  /*    INDEXED => nothing */
   108604    26,  /*      ABORT => ID */
   108605    26,  /*     ACTION => ID */
   108606    26,  /*      AFTER => ID */
   108607    26,  /*    ANALYZE => ID */
   108608    26,  /*        ASC => ID */
   108609    26,  /*     ATTACH => ID */
   108610    26,  /*     BEFORE => ID */
   108611    26,  /*         BY => ID */
   108612    26,  /*    CASCADE => ID */
   108613    26,  /*       CAST => ID */
   108614    26,  /*   COLUMNKW => ID */
   108615    26,  /*   CONFLICT => ID */
   108616    26,  /*   DATABASE => ID */
   108617    26,  /*       DESC => ID */
   108618    26,  /*     DETACH => ID */
   108619    26,  /*       EACH => ID */
   108620    26,  /*       FAIL => ID */
   108621    26,  /*        FOR => ID */
   108622    26,  /*     IGNORE => ID */
   108623    26,  /*  INITIALLY => ID */
   108624    26,  /*    INSTEAD => ID */
   108625    26,  /*    LIKE_KW => ID */
   108626    26,  /*      MATCH => ID */
   108627    26,  /*         NO => ID */
   108628    26,  /*        KEY => ID */
   108629    26,  /*         OF => ID */
   108630    26,  /*     OFFSET => ID */
   108631    26,  /*     PRAGMA => ID */
   108632    26,  /*      RAISE => ID */
   108633    26,  /*    REPLACE => ID */
   108634    26,  /*   RESTRICT => ID */
   108635    26,  /*        ROW => ID */
   108636    26,  /*    TRIGGER => ID */
   108637    26,  /*     VACUUM => ID */
   108638    26,  /*       VIEW => ID */
   108639    26,  /*    VIRTUAL => ID */
   108640    26,  /*    REINDEX => ID */
   108641    26,  /*     RENAME => ID */
   108642    26,  /*   CTIME_KW => ID */
   108643 };
   108644 #endif /* YYFALLBACK */
   108645 
   108646 /* The following structure represents a single element of the
   108647 ** parser's stack.  Information stored includes:
   108648 **
   108649 **   +  The state number for the parser at this level of the stack.
   108650 **
   108651 **   +  The value of the token stored at this level of the stack.
   108652 **      (In other words, the "major" token.)
   108653 **
   108654 **   +  The semantic value stored at this level of the stack.  This is
   108655 **      the information used by the action routines in the grammar.
   108656 **      It is sometimes called the "minor" token.
   108657 */
   108658 struct yyStackEntry {
   108659   YYACTIONTYPE stateno;  /* The state-number */
   108660   YYCODETYPE major;      /* The major token value.  This is the code
   108661                          ** number for the token at this stack level */
   108662   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   108663                          ** is the value of the token  */
   108664 };
   108665 typedef struct yyStackEntry yyStackEntry;
   108666 
   108667 /* The state of the parser is completely contained in an instance of
   108668 ** the following structure */
   108669 struct yyParser {
   108670   int yyidx;                    /* Index of top element in stack */
   108671 #ifdef YYTRACKMAXSTACKDEPTH
   108672   int yyidxMax;                 /* Maximum value of yyidx */
   108673 #endif
   108674   int yyerrcnt;                 /* Shifts left before out of the error */
   108675   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   108676 #if YYSTACKDEPTH<=0
   108677   int yystksz;                  /* Current side of the stack */
   108678   yyStackEntry *yystack;        /* The parser's stack */
   108679 #else
   108680   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   108681 #endif
   108682 };
   108683 typedef struct yyParser yyParser;
   108684 
   108685 #ifndef NDEBUG
   108686 /* #include <stdio.h> */
   108687 static FILE *yyTraceFILE = 0;
   108688 static char *yyTracePrompt = 0;
   108689 #endif /* NDEBUG */
   108690 
   108691 #ifndef NDEBUG
   108692 /*
   108693 ** Turn parser tracing on by giving a stream to which to write the trace
   108694 ** and a prompt to preface each trace message.  Tracing is turned off
   108695 ** by making either argument NULL
   108696 **
   108697 ** Inputs:
   108698 ** <ul>
   108699 ** <li> A FILE* to which trace output should be written.
   108700 **      If NULL, then tracing is turned off.
   108701 ** <li> A prefix string written at the beginning of every
   108702 **      line of trace output.  If NULL, then tracing is
   108703 **      turned off.
   108704 ** </ul>
   108705 **
   108706 ** Outputs:
   108707 ** None.
   108708 */
   108709 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   108710   yyTraceFILE = TraceFILE;
   108711   yyTracePrompt = zTracePrompt;
   108712   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   108713   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   108714 }
   108715 #endif /* NDEBUG */
   108716 
   108717 #ifndef NDEBUG
   108718 /* For tracing shifts, the names of all terminals and nonterminals
   108719 ** are required.  The following table supplies these names */
   108720 static const char *const yyTokenName[] = {
   108721   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   108722   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   108723   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   108724   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   108725   "TABLE",         "CREATE",        "IF",            "NOT",
   108726   "EXISTS",        "TEMP",          "LP",            "RP",
   108727   "AS",            "COMMA",         "ID",            "INDEXED",
   108728   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
   108729   "ASC",           "ATTACH",        "BEFORE",        "BY",
   108730   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
   108731   "DATABASE",      "DESC",          "DETACH",        "EACH",
   108732   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
   108733   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
   108734   "KEY",           "OF",            "OFFSET",        "PRAGMA",
   108735   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
   108736   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
   108737   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
   108738   "OR",            "AND",           "IS",            "BETWEEN",
   108739   "IN",            "ISNULL",        "NOTNULL",       "NE",
   108740   "EQ",            "GT",            "LE",            "LT",
   108741   "GE",            "ESCAPE",        "BITAND",        "BITOR",
   108742   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
   108743   "STAR",          "SLASH",         "REM",           "CONCAT",
   108744   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
   108745   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
   108746   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
   108747   "ON",            "INSERT",        "DELETE",        "UPDATE",
   108748   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
   108749   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
   108750   "SELECT",        "DISTINCT",      "DOT",           "FROM",
   108751   "JOIN",          "USING",         "ORDER",         "GROUP",
   108752   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   108753   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
   108754   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
   108755   "THEN",          "ELSE",          "INDEX",         "ALTER",
   108756   "ADD",           "error",         "input",         "cmdlist",
   108757   "ecmd",          "explain",       "cmdx",          "cmd",
   108758   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
   108759   "create_table",  "create_table_args",  "createkw",      "temp",
   108760   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
   108761   "select",        "column",        "columnid",      "type",
   108762   "carglist",      "id",            "ids",           "typetoken",
   108763   "typename",      "signed",        "plus_num",      "minus_num",
   108764   "carg",          "ccons",         "term",          "expr",
   108765   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   108766   "refargs",       "defer_subclause",  "refarg",        "refact",
   108767   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
   108768   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
   108769   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
   108770   "distinct",      "selcollist",    "from",          "where_opt",
   108771   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
   108772   "sclp",          "as",            "seltablist",    "stl_prefix",
   108773   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
   108774   "joinop2",       "inscollist",    "sortlist",      "nexprlist",
   108775   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
   108776   "exprlist",      "likeop",        "between_op",    "in_op",
   108777   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
   108778   "collate",       "nmnum",         "number",        "trigger_decl",
   108779   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
   108780   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
   108781   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
   108782   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
   108783   "lp",            "anylist",
   108784 };
   108785 #endif /* NDEBUG */
   108786 
   108787 #ifndef NDEBUG
   108788 /* For tracing reduce actions, the names of all rules are required.
   108789 */
   108790 static const char *const yyRuleName[] = {
   108791  /*   0 */ "input ::= cmdlist",
   108792  /*   1 */ "cmdlist ::= cmdlist ecmd",
   108793  /*   2 */ "cmdlist ::= ecmd",
   108794  /*   3 */ "ecmd ::= SEMI",
   108795  /*   4 */ "ecmd ::= explain cmdx SEMI",
   108796  /*   5 */ "explain ::=",
   108797  /*   6 */ "explain ::= EXPLAIN",
   108798  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   108799  /*   8 */ "cmdx ::= cmd",
   108800  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   108801  /*  10 */ "trans_opt ::=",
   108802  /*  11 */ "trans_opt ::= TRANSACTION",
   108803  /*  12 */ "trans_opt ::= TRANSACTION nm",
   108804  /*  13 */ "transtype ::=",
   108805  /*  14 */ "transtype ::= DEFERRED",
   108806  /*  15 */ "transtype ::= IMMEDIATE",
   108807  /*  16 */ "transtype ::= EXCLUSIVE",
   108808  /*  17 */ "cmd ::= COMMIT trans_opt",
   108809  /*  18 */ "cmd ::= END trans_opt",
   108810  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   108811  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   108812  /*  21 */ "savepoint_opt ::=",
   108813  /*  22 */ "cmd ::= SAVEPOINT nm",
   108814  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   108815  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   108816  /*  25 */ "cmd ::= create_table create_table_args",
   108817  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   108818  /*  27 */ "createkw ::= CREATE",
   108819  /*  28 */ "ifnotexists ::=",
   108820  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   108821  /*  30 */ "temp ::= TEMP",
   108822  /*  31 */ "temp ::=",
   108823  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
   108824  /*  33 */ "create_table_args ::= AS select",
   108825  /*  34 */ "columnlist ::= columnlist COMMA column",
   108826  /*  35 */ "columnlist ::= column",
   108827  /*  36 */ "column ::= columnid type carglist",
   108828  /*  37 */ "columnid ::= nm",
   108829  /*  38 */ "id ::= ID",
   108830  /*  39 */ "id ::= INDEXED",
   108831  /*  40 */ "ids ::= ID|STRING",
   108832  /*  41 */ "nm ::= id",
   108833  /*  42 */ "nm ::= STRING",
   108834  /*  43 */ "nm ::= JOIN_KW",
   108835  /*  44 */ "type ::=",
   108836  /*  45 */ "type ::= typetoken",
   108837  /*  46 */ "typetoken ::= typename",
   108838  /*  47 */ "typetoken ::= typename LP signed RP",
   108839  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
   108840  /*  49 */ "typename ::= ids",
   108841  /*  50 */ "typename ::= typename ids",
   108842  /*  51 */ "signed ::= plus_num",
   108843  /*  52 */ "signed ::= minus_num",
   108844  /*  53 */ "carglist ::= carglist carg",
   108845  /*  54 */ "carglist ::=",
   108846  /*  55 */ "carg ::= CONSTRAINT nm ccons",
   108847  /*  56 */ "carg ::= ccons",
   108848  /*  57 */ "ccons ::= DEFAULT term",
   108849  /*  58 */ "ccons ::= DEFAULT LP expr RP",
   108850  /*  59 */ "ccons ::= DEFAULT PLUS term",
   108851  /*  60 */ "ccons ::= DEFAULT MINUS term",
   108852  /*  61 */ "ccons ::= DEFAULT id",
   108853  /*  62 */ "ccons ::= NULL onconf",
   108854  /*  63 */ "ccons ::= NOT NULL onconf",
   108855  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   108856  /*  65 */ "ccons ::= UNIQUE onconf",
   108857  /*  66 */ "ccons ::= CHECK LP expr RP",
   108858  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   108859  /*  68 */ "ccons ::= defer_subclause",
   108860  /*  69 */ "ccons ::= COLLATE ids",
   108861  /*  70 */ "autoinc ::=",
   108862  /*  71 */ "autoinc ::= AUTOINCR",
   108863  /*  72 */ "refargs ::=",
   108864  /*  73 */ "refargs ::= refargs refarg",
   108865  /*  74 */ "refarg ::= MATCH nm",
   108866  /*  75 */ "refarg ::= ON INSERT refact",
   108867  /*  76 */ "refarg ::= ON DELETE refact",
   108868  /*  77 */ "refarg ::= ON UPDATE refact",
   108869  /*  78 */ "refact ::= SET NULL",
   108870  /*  79 */ "refact ::= SET DEFAULT",
   108871  /*  80 */ "refact ::= CASCADE",
   108872  /*  81 */ "refact ::= RESTRICT",
   108873  /*  82 */ "refact ::= NO ACTION",
   108874  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   108875  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   108876  /*  85 */ "init_deferred_pred_opt ::=",
   108877  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   108878  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   108879  /*  88 */ "conslist_opt ::=",
   108880  /*  89 */ "conslist_opt ::= COMMA conslist",
   108881  /*  90 */ "conslist ::= conslist COMMA tcons",
   108882  /*  91 */ "conslist ::= conslist tcons",
   108883  /*  92 */ "conslist ::= tcons",
   108884  /*  93 */ "tcons ::= CONSTRAINT nm",
   108885  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   108886  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   108887  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
   108888  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   108889  /*  98 */ "defer_subclause_opt ::=",
   108890  /*  99 */ "defer_subclause_opt ::= defer_subclause",
   108891  /* 100 */ "onconf ::=",
   108892  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
   108893  /* 102 */ "orconf ::=",
   108894  /* 103 */ "orconf ::= OR resolvetype",
   108895  /* 104 */ "resolvetype ::= raisetype",
   108896  /* 105 */ "resolvetype ::= IGNORE",
   108897  /* 106 */ "resolvetype ::= REPLACE",
   108898  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
   108899  /* 108 */ "ifexists ::= IF EXISTS",
   108900  /* 109 */ "ifexists ::=",
   108901  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   108902  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
   108903  /* 112 */ "cmd ::= select",
   108904  /* 113 */ "select ::= oneselect",
   108905  /* 114 */ "select ::= select multiselect_op oneselect",
   108906  /* 115 */ "multiselect_op ::= UNION",
   108907  /* 116 */ "multiselect_op ::= UNION ALL",
   108908  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   108909  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   108910  /* 119 */ "distinct ::= DISTINCT",
   108911  /* 120 */ "distinct ::= ALL",
   108912  /* 121 */ "distinct ::=",
   108913  /* 122 */ "sclp ::= selcollist COMMA",
   108914  /* 123 */ "sclp ::=",
   108915  /* 124 */ "selcollist ::= sclp expr as",
   108916  /* 125 */ "selcollist ::= sclp STAR",
   108917  /* 126 */ "selcollist ::= sclp nm DOT STAR",
   108918  /* 127 */ "as ::= AS nm",
   108919  /* 128 */ "as ::= ids",
   108920  /* 129 */ "as ::=",
   108921  /* 130 */ "from ::=",
   108922  /* 131 */ "from ::= FROM seltablist",
   108923  /* 132 */ "stl_prefix ::= seltablist joinop",
   108924  /* 133 */ "stl_prefix ::=",
   108925  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   108926  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   108927  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   108928  /* 137 */ "dbnm ::=",
   108929  /* 138 */ "dbnm ::= DOT nm",
   108930  /* 139 */ "fullname ::= nm dbnm",
   108931  /* 140 */ "joinop ::= COMMA|JOIN",
   108932  /* 141 */ "joinop ::= JOIN_KW JOIN",
   108933  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
   108934  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
   108935  /* 144 */ "on_opt ::= ON expr",
   108936  /* 145 */ "on_opt ::=",
   108937  /* 146 */ "indexed_opt ::=",
   108938  /* 147 */ "indexed_opt ::= INDEXED BY nm",
   108939  /* 148 */ "indexed_opt ::= NOT INDEXED",
   108940  /* 149 */ "using_opt ::= USING LP inscollist RP",
   108941  /* 150 */ "using_opt ::=",
   108942  /* 151 */ "orderby_opt ::=",
   108943  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
   108944  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
   108945  /* 154 */ "sortlist ::= expr sortorder",
   108946  /* 155 */ "sortorder ::= ASC",
   108947  /* 156 */ "sortorder ::= DESC",
   108948  /* 157 */ "sortorder ::=",
   108949  /* 158 */ "groupby_opt ::=",
   108950  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
   108951  /* 160 */ "having_opt ::=",
   108952  /* 161 */ "having_opt ::= HAVING expr",
   108953  /* 162 */ "limit_opt ::=",
   108954  /* 163 */ "limit_opt ::= LIMIT expr",
   108955  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
   108956  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
   108957  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
   108958  /* 167 */ "where_opt ::=",
   108959  /* 168 */ "where_opt ::= WHERE expr",
   108960  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
   108961  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
   108962  /* 171 */ "setlist ::= nm EQ expr",
   108963  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
   108964  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
   108965  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   108966  /* 175 */ "insert_cmd ::= INSERT orconf",
   108967  /* 176 */ "insert_cmd ::= REPLACE",
   108968  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
   108969  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
   108970  /* 179 */ "inscollist_opt ::=",
   108971  /* 180 */ "inscollist_opt ::= LP inscollist RP",
   108972  /* 181 */ "inscollist ::= inscollist COMMA nm",
   108973  /* 182 */ "inscollist ::= nm",
   108974  /* 183 */ "expr ::= term",
   108975  /* 184 */ "expr ::= LP expr RP",
   108976  /* 185 */ "term ::= NULL",
   108977  /* 186 */ "expr ::= id",
   108978  /* 187 */ "expr ::= JOIN_KW",
   108979  /* 188 */ "expr ::= nm DOT nm",
   108980  /* 189 */ "expr ::= nm DOT nm DOT nm",
   108981  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
   108982  /* 191 */ "term ::= STRING",
   108983  /* 192 */ "expr ::= REGISTER",
   108984  /* 193 */ "expr ::= VARIABLE",
   108985  /* 194 */ "expr ::= expr COLLATE ids",
   108986  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
   108987  /* 196 */ "expr ::= ID LP distinct exprlist RP",
   108988  /* 197 */ "expr ::= ID LP STAR RP",
   108989  /* 198 */ "term ::= CTIME_KW",
   108990  /* 199 */ "expr ::= expr AND expr",
   108991  /* 200 */ "expr ::= expr OR expr",
   108992  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
   108993  /* 202 */ "expr ::= expr EQ|NE expr",
   108994  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   108995  /* 204 */ "expr ::= expr PLUS|MINUS expr",
   108996  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
   108997  /* 206 */ "expr ::= expr CONCAT expr",
   108998  /* 207 */ "likeop ::= LIKE_KW",
   108999  /* 208 */ "likeop ::= NOT LIKE_KW",
   109000  /* 209 */ "likeop ::= MATCH",
   109001  /* 210 */ "likeop ::= NOT MATCH",
   109002  /* 211 */ "expr ::= expr likeop expr",
   109003  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
   109004  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
   109005  /* 214 */ "expr ::= expr NOT NULL",
   109006  /* 215 */ "expr ::= expr IS expr",
   109007  /* 216 */ "expr ::= expr IS NOT expr",
   109008  /* 217 */ "expr ::= NOT expr",
   109009  /* 218 */ "expr ::= BITNOT expr",
   109010  /* 219 */ "expr ::= MINUS expr",
   109011  /* 220 */ "expr ::= PLUS expr",
   109012  /* 221 */ "between_op ::= BETWEEN",
   109013  /* 222 */ "between_op ::= NOT BETWEEN",
   109014  /* 223 */ "expr ::= expr between_op expr AND expr",
   109015  /* 224 */ "in_op ::= IN",
   109016  /* 225 */ "in_op ::= NOT IN",
   109017  /* 226 */ "expr ::= expr in_op LP exprlist RP",
   109018  /* 227 */ "expr ::= LP select RP",
   109019  /* 228 */ "expr ::= expr in_op LP select RP",
   109020  /* 229 */ "expr ::= expr in_op nm dbnm",
   109021  /* 230 */ "expr ::= EXISTS LP select RP",
   109022  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
   109023  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   109024  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
   109025  /* 234 */ "case_else ::= ELSE expr",
   109026  /* 235 */ "case_else ::=",
   109027  /* 236 */ "case_operand ::= expr",
   109028  /* 237 */ "case_operand ::=",
   109029  /* 238 */ "exprlist ::= nexprlist",
   109030  /* 239 */ "exprlist ::=",
   109031  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
   109032  /* 241 */ "nexprlist ::= expr",
   109033  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
   109034  /* 243 */ "uniqueflag ::= UNIQUE",
   109035  /* 244 */ "uniqueflag ::=",
   109036  /* 245 */ "idxlist_opt ::=",
   109037  /* 246 */ "idxlist_opt ::= LP idxlist RP",
   109038  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   109039  /* 248 */ "idxlist ::= nm collate sortorder",
   109040  /* 249 */ "collate ::=",
   109041  /* 250 */ "collate ::= COLLATE ids",
   109042  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
   109043  /* 252 */ "cmd ::= VACUUM",
   109044  /* 253 */ "cmd ::= VACUUM nm",
   109045  /* 254 */ "cmd ::= PRAGMA nm dbnm",
   109046  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   109047  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   109048  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   109049  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   109050  /* 259 */ "nmnum ::= plus_num",
   109051  /* 260 */ "nmnum ::= nm",
   109052  /* 261 */ "nmnum ::= ON",
   109053  /* 262 */ "nmnum ::= DELETE",
   109054  /* 263 */ "nmnum ::= DEFAULT",
   109055  /* 264 */ "plus_num ::= PLUS number",
   109056  /* 265 */ "plus_num ::= number",
   109057  /* 266 */ "minus_num ::= MINUS number",
   109058  /* 267 */ "number ::= INTEGER|FLOAT",
   109059  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   109060  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   109061  /* 270 */ "trigger_time ::= BEFORE",
   109062  /* 271 */ "trigger_time ::= AFTER",
   109063  /* 272 */ "trigger_time ::= INSTEAD OF",
   109064  /* 273 */ "trigger_time ::=",
   109065  /* 274 */ "trigger_event ::= DELETE|INSERT",
   109066  /* 275 */ "trigger_event ::= UPDATE",
   109067  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
   109068  /* 277 */ "foreach_clause ::=",
   109069  /* 278 */ "foreach_clause ::= FOR EACH ROW",
   109070  /* 279 */ "when_clause ::=",
   109071  /* 280 */ "when_clause ::= WHEN expr",
   109072  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   109073  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   109074  /* 283 */ "trnm ::= nm",
   109075  /* 284 */ "trnm ::= nm DOT nm",
   109076  /* 285 */ "tridxby ::=",
   109077  /* 286 */ "tridxby ::= INDEXED BY nm",
   109078  /* 287 */ "tridxby ::= NOT INDEXED",
   109079  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   109080  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
   109081  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   109082  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   109083  /* 292 */ "trigger_cmd ::= select",
   109084  /* 293 */ "expr ::= RAISE LP IGNORE RP",
   109085  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   109086  /* 295 */ "raisetype ::= ROLLBACK",
   109087  /* 296 */ "raisetype ::= ABORT",
   109088  /* 297 */ "raisetype ::= FAIL",
   109089  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
   109090  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   109091  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
   109092  /* 301 */ "key_opt ::=",
   109093  /* 302 */ "key_opt ::= KEY expr",
   109094  /* 303 */ "database_kw_opt ::= DATABASE",
   109095  /* 304 */ "database_kw_opt ::=",
   109096  /* 305 */ "cmd ::= REINDEX",
   109097  /* 306 */ "cmd ::= REINDEX nm dbnm",
   109098  /* 307 */ "cmd ::= ANALYZE",
   109099  /* 308 */ "cmd ::= ANALYZE nm dbnm",
   109100  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   109101  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   109102  /* 311 */ "add_column_fullname ::= fullname",
   109103  /* 312 */ "kwcolumn_opt ::=",
   109104  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
   109105  /* 314 */ "cmd ::= create_vtab",
   109106  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
   109107  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
   109108  /* 317 */ "vtabarglist ::= vtabarg",
   109109  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   109110  /* 319 */ "vtabarg ::=",
   109111  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
   109112  /* 321 */ "vtabargtoken ::= ANY",
   109113  /* 322 */ "vtabargtoken ::= lp anylist RP",
   109114  /* 323 */ "lp ::= LP",
   109115  /* 324 */ "anylist ::=",
   109116  /* 325 */ "anylist ::= anylist LP anylist RP",
   109117  /* 326 */ "anylist ::= anylist ANY",
   109118 };
   109119 #endif /* NDEBUG */
   109120 
   109121 
   109122 #if YYSTACKDEPTH<=0
   109123 /*
   109124 ** Try to increase the size of the parser stack.
   109125 */
   109126 static void yyGrowStack(yyParser *p){
   109127   int newSize;
   109128   yyStackEntry *pNew;
   109129 
   109130   newSize = p->yystksz*2 + 100;
   109131   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   109132   if( pNew ){
   109133     p->yystack = pNew;
   109134     p->yystksz = newSize;
   109135 #ifndef NDEBUG
   109136     if( yyTraceFILE ){
   109137       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   109138               yyTracePrompt, p->yystksz);
   109139     }
   109140 #endif
   109141   }
   109142 }
   109143 #endif
   109144 
   109145 /*
   109146 ** This function allocates a new parser.
   109147 ** The only argument is a pointer to a function which works like
   109148 ** malloc.
   109149 **
   109150 ** Inputs:
   109151 ** A pointer to the function used to allocate memory.
   109152 **
   109153 ** Outputs:
   109154 ** A pointer to a parser.  This pointer is used in subsequent calls
   109155 ** to sqlite3Parser and sqlite3ParserFree.
   109156 */
   109157 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   109158   yyParser *pParser;
   109159   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   109160   if( pParser ){
   109161     pParser->yyidx = -1;
   109162 #ifdef YYTRACKMAXSTACKDEPTH
   109163     pParser->yyidxMax = 0;
   109164 #endif
   109165 #if YYSTACKDEPTH<=0
   109166     pParser->yystack = NULL;
   109167     pParser->yystksz = 0;
   109168     yyGrowStack(pParser);
   109169 #endif
   109170   }
   109171   return pParser;
   109172 }
   109173 
   109174 /* The following function deletes the value associated with a
   109175 ** symbol.  The symbol can be either a terminal or nonterminal.
   109176 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   109177 ** the value.
   109178 */
   109179 static void yy_destructor(
   109180   yyParser *yypParser,    /* The parser */
   109181   YYCODETYPE yymajor,     /* Type code for object to destroy */
   109182   YYMINORTYPE *yypminor   /* The object to be destroyed */
   109183 ){
   109184   sqlite3ParserARG_FETCH;
   109185   switch( yymajor ){
   109186     /* Here is inserted the actions which take place when a
   109187     ** terminal or non-terminal is destroyed.  This can happen
   109188     ** when the symbol is popped from the stack during a
   109189     ** reduce or during error processing or when a parser is
   109190     ** being destroyed before it is finished parsing.
   109191     **
   109192     ** Note: during a reduce, the only symbols destroyed are those
   109193     ** which appear on the RHS of the rule, but which are not used
   109194     ** inside the C code.
   109195     */
   109196     case 160: /* select */
   109197     case 194: /* oneselect */
   109198 {
   109199 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
   109200 }
   109201       break;
   109202     case 174: /* term */
   109203     case 175: /* expr */
   109204 {
   109205 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
   109206 }
   109207       break;
   109208     case 179: /* idxlist_opt */
   109209     case 187: /* idxlist */
   109210     case 197: /* selcollist */
   109211     case 200: /* groupby_opt */
   109212     case 202: /* orderby_opt */
   109213     case 204: /* sclp */
   109214     case 214: /* sortlist */
   109215     case 215: /* nexprlist */
   109216     case 216: /* setlist */
   109217     case 220: /* exprlist */
   109218     case 225: /* case_exprlist */
   109219 {
   109220 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
   109221 }
   109222       break;
   109223     case 193: /* fullname */
   109224     case 198: /* from */
   109225     case 206: /* seltablist */
   109226     case 207: /* stl_prefix */
   109227 {
   109228 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
   109229 }
   109230       break;
   109231     case 199: /* where_opt */
   109232     case 201: /* having_opt */
   109233     case 210: /* on_opt */
   109234     case 224: /* case_operand */
   109235     case 226: /* case_else */
   109236     case 236: /* when_clause */
   109237     case 241: /* key_opt */
   109238 {
   109239 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
   109240 }
   109241       break;
   109242     case 211: /* using_opt */
   109243     case 213: /* inscollist */
   109244     case 218: /* inscollist_opt */
   109245 {
   109246 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
   109247 }
   109248       break;
   109249     case 219: /* valuelist */
   109250 {
   109251 
   109252   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
   109253   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
   109254 
   109255 }
   109256       break;
   109257     case 232: /* trigger_cmd_list */
   109258     case 237: /* trigger_cmd */
   109259 {
   109260 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
   109261 }
   109262       break;
   109263     case 234: /* trigger_event */
   109264 {
   109265 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
   109266 }
   109267       break;
   109268     default:  break;   /* If no destructor action specified: do nothing */
   109269   }
   109270 }
   109271 
   109272 /*
   109273 ** Pop the parser's stack once.
   109274 **
   109275 ** If there is a destructor routine associated with the token which
   109276 ** is popped from the stack, then call it.
   109277 **
   109278 ** Return the major token number for the symbol popped.
   109279 */
   109280 static int yy_pop_parser_stack(yyParser *pParser){
   109281   YYCODETYPE yymajor;
   109282   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   109283 
   109284   /* There is no mechanism by which the parser stack can be popped below
   109285   ** empty in SQLite.  */
   109286   if( NEVER(pParser->yyidx<0) ) return 0;
   109287 #ifndef NDEBUG
   109288   if( yyTraceFILE && pParser->yyidx>=0 ){
   109289     fprintf(yyTraceFILE,"%sPopping %s\n",
   109290       yyTracePrompt,
   109291       yyTokenName[yytos->major]);
   109292   }
   109293 #endif
   109294   yymajor = yytos->major;
   109295   yy_destructor(pParser, yymajor, &yytos->minor);
   109296   pParser->yyidx--;
   109297   return yymajor;
   109298 }
   109299 
   109300 /*
   109301 ** Deallocate and destroy a parser.  Destructors are all called for
   109302 ** all stack elements before shutting the parser down.
   109303 **
   109304 ** Inputs:
   109305 ** <ul>
   109306 ** <li>  A pointer to the parser.  This should be a pointer
   109307 **       obtained from sqlite3ParserAlloc.
   109308 ** <li>  A pointer to a function used to reclaim memory obtained
   109309 **       from malloc.
   109310 ** </ul>
   109311 */
   109312 SQLITE_PRIVATE void sqlite3ParserFree(
   109313   void *p,                    /* The parser to be deleted */
   109314   void (*freeProc)(void*)     /* Function used to reclaim memory */
   109315 ){
   109316   yyParser *pParser = (yyParser*)p;
   109317   /* In SQLite, we never try to destroy a parser that was not successfully
   109318   ** created in the first place. */
   109319   if( NEVER(pParser==0) ) return;
   109320   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   109321 #if YYSTACKDEPTH<=0
   109322   free(pParser->yystack);
   109323 #endif
   109324   (*freeProc)((void*)pParser);
   109325 }
   109326 
   109327 /*
   109328 ** Return the peak depth of the stack for a parser.
   109329 */
   109330 #ifdef YYTRACKMAXSTACKDEPTH
   109331 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   109332   yyParser *pParser = (yyParser*)p;
   109333   return pParser->yyidxMax;
   109334 }
   109335 #endif
   109336 
   109337 /*
   109338 ** Find the appropriate action for a parser given the terminal
   109339 ** look-ahead token iLookAhead.
   109340 **
   109341 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   109342 ** independent of the look-ahead.  If it is, return the action, otherwise
   109343 ** return YY_NO_ACTION.
   109344 */
   109345 static int yy_find_shift_action(
   109346   yyParser *pParser,        /* The parser */
   109347   YYCODETYPE iLookAhead     /* The look-ahead token */
   109348 ){
   109349   int i;
   109350   int stateno = pParser->yystack[pParser->yyidx].stateno;
   109351 
   109352   if( stateno>YY_SHIFT_COUNT
   109353    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   109354     return yy_default[stateno];
   109355   }
   109356   assert( iLookAhead!=YYNOCODE );
   109357   i += iLookAhead;
   109358   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   109359     if( iLookAhead>0 ){
   109360 #ifdef YYFALLBACK
   109361       YYCODETYPE iFallback;            /* Fallback token */
   109362       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   109363              && (iFallback = yyFallback[iLookAhead])!=0 ){
   109364 #ifndef NDEBUG
   109365         if( yyTraceFILE ){
   109366           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   109367              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   109368         }
   109369 #endif
   109370         return yy_find_shift_action(pParser, iFallback);
   109371       }
   109372 #endif
   109373 #ifdef YYWILDCARD
   109374       {
   109375         int j = i - iLookAhead + YYWILDCARD;
   109376         if(
   109377 #if YY_SHIFT_MIN+YYWILDCARD<0
   109378           j>=0 &&
   109379 #endif
   109380 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   109381           j<YY_ACTTAB_COUNT &&
   109382 #endif
   109383           yy_lookahead[j]==YYWILDCARD
   109384         ){
   109385 #ifndef NDEBUG
   109386           if( yyTraceFILE ){
   109387             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   109388                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   109389           }
   109390 #endif /* NDEBUG */
   109391           return yy_action[j];
   109392         }
   109393       }
   109394 #endif /* YYWILDCARD */
   109395     }
   109396     return yy_default[stateno];
   109397   }else{
   109398     return yy_action[i];
   109399   }
   109400 }
   109401 
   109402 /*
   109403 ** Find the appropriate action for a parser given the non-terminal
   109404 ** look-ahead token iLookAhead.
   109405 **
   109406 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   109407 ** independent of the look-ahead.  If it is, return the action, otherwise
   109408 ** return YY_NO_ACTION.
   109409 */
   109410 static int yy_find_reduce_action(
   109411   int stateno,              /* Current state number */
   109412   YYCODETYPE iLookAhead     /* The look-ahead token */
   109413 ){
   109414   int i;
   109415 #ifdef YYERRORSYMBOL
   109416   if( stateno>YY_REDUCE_COUNT ){
   109417     return yy_default[stateno];
   109418   }
   109419 #else
   109420   assert( stateno<=YY_REDUCE_COUNT );
   109421 #endif
   109422   i = yy_reduce_ofst[stateno];
   109423   assert( i!=YY_REDUCE_USE_DFLT );
   109424   assert( iLookAhead!=YYNOCODE );
   109425   i += iLookAhead;
   109426 #ifdef YYERRORSYMBOL
   109427   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   109428     return yy_default[stateno];
   109429   }
   109430 #else
   109431   assert( i>=0 && i<YY_ACTTAB_COUNT );
   109432   assert( yy_lookahead[i]==iLookAhead );
   109433 #endif
   109434   return yy_action[i];
   109435 }
   109436 
   109437 /*
   109438 ** The following routine is called if the stack overflows.
   109439 */
   109440 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   109441    sqlite3ParserARG_FETCH;
   109442    yypParser->yyidx--;
   109443 #ifndef NDEBUG
   109444    if( yyTraceFILE ){
   109445      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   109446    }
   109447 #endif
   109448    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   109449    /* Here code is inserted which will execute if the parser
   109450    ** stack every overflows */
   109451 
   109452   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   109453   sqlite3ErrorMsg(pParse, "parser stack overflow");
   109454    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   109455 }
   109456 
   109457 /*
   109458 ** Perform a shift action.
   109459 */
   109460 static void yy_shift(
   109461   yyParser *yypParser,          /* The parser to be shifted */
   109462   int yyNewState,               /* The new state to shift in */
   109463   int yyMajor,                  /* The major token to shift in */
   109464   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   109465 ){
   109466   yyStackEntry *yytos;
   109467   yypParser->yyidx++;
   109468 #ifdef YYTRACKMAXSTACKDEPTH
   109469   if( yypParser->yyidx>yypParser->yyidxMax ){
   109470     yypParser->yyidxMax = yypParser->yyidx;
   109471   }
   109472 #endif
   109473 #if YYSTACKDEPTH>0
   109474   if( yypParser->yyidx>=YYSTACKDEPTH ){
   109475     yyStackOverflow(yypParser, yypMinor);
   109476     return;
   109477   }
   109478 #else
   109479   if( yypParser->yyidx>=yypParser->yystksz ){
   109480     yyGrowStack(yypParser);
   109481     if( yypParser->yyidx>=yypParser->yystksz ){
   109482       yyStackOverflow(yypParser, yypMinor);
   109483       return;
   109484     }
   109485   }
   109486 #endif
   109487   yytos = &yypParser->yystack[yypParser->yyidx];
   109488   yytos->stateno = (YYACTIONTYPE)yyNewState;
   109489   yytos->major = (YYCODETYPE)yyMajor;
   109490   yytos->minor = *yypMinor;
   109491 #ifndef NDEBUG
   109492   if( yyTraceFILE && yypParser->yyidx>0 ){
   109493     int i;
   109494     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   109495     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   109496     for(i=1; i<=yypParser->yyidx; i++)
   109497       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   109498     fprintf(yyTraceFILE,"\n");
   109499   }
   109500 #endif
   109501 }
   109502 
   109503 /* The following table contains information about every rule that
   109504 ** is used during the reduce.
   109505 */
   109506 static const struct {
   109507   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   109508   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   109509 } yyRuleInfo[] = {
   109510   { 142, 1 },
   109511   { 143, 2 },
   109512   { 143, 1 },
   109513   { 144, 1 },
   109514   { 144, 3 },
   109515   { 145, 0 },
   109516   { 145, 1 },
   109517   { 145, 3 },
   109518   { 146, 1 },
   109519   { 147, 3 },
   109520   { 149, 0 },
   109521   { 149, 1 },
   109522   { 149, 2 },
   109523   { 148, 0 },
   109524   { 148, 1 },
   109525   { 148, 1 },
   109526   { 148, 1 },
   109527   { 147, 2 },
   109528   { 147, 2 },
   109529   { 147, 2 },
   109530   { 151, 1 },
   109531   { 151, 0 },
   109532   { 147, 2 },
   109533   { 147, 3 },
   109534   { 147, 5 },
   109535   { 147, 2 },
   109536   { 152, 6 },
   109537   { 154, 1 },
   109538   { 156, 0 },
   109539   { 156, 3 },
   109540   { 155, 1 },
   109541   { 155, 0 },
   109542   { 153, 4 },
   109543   { 153, 2 },
   109544   { 158, 3 },
   109545   { 158, 1 },
   109546   { 161, 3 },
   109547   { 162, 1 },
   109548   { 165, 1 },
   109549   { 165, 1 },
   109550   { 166, 1 },
   109551   { 150, 1 },
   109552   { 150, 1 },
   109553   { 150, 1 },
   109554   { 163, 0 },
   109555   { 163, 1 },
   109556   { 167, 1 },
   109557   { 167, 4 },
   109558   { 167, 6 },
   109559   { 168, 1 },
   109560   { 168, 2 },
   109561   { 169, 1 },
   109562   { 169, 1 },
   109563   { 164, 2 },
   109564   { 164, 0 },
   109565   { 172, 3 },
   109566   { 172, 1 },
   109567   { 173, 2 },
   109568   { 173, 4 },
   109569   { 173, 3 },
   109570   { 173, 3 },
   109571   { 173, 2 },
   109572   { 173, 2 },
   109573   { 173, 3 },
   109574   { 173, 5 },
   109575   { 173, 2 },
   109576   { 173, 4 },
   109577   { 173, 4 },
   109578   { 173, 1 },
   109579   { 173, 2 },
   109580   { 178, 0 },
   109581   { 178, 1 },
   109582   { 180, 0 },
   109583   { 180, 2 },
   109584   { 182, 2 },
   109585   { 182, 3 },
   109586   { 182, 3 },
   109587   { 182, 3 },
   109588   { 183, 2 },
   109589   { 183, 2 },
   109590   { 183, 1 },
   109591   { 183, 1 },
   109592   { 183, 2 },
   109593   { 181, 3 },
   109594   { 181, 2 },
   109595   { 184, 0 },
   109596   { 184, 2 },
   109597   { 184, 2 },
   109598   { 159, 0 },
   109599   { 159, 2 },
   109600   { 185, 3 },
   109601   { 185, 2 },
   109602   { 185, 1 },
   109603   { 186, 2 },
   109604   { 186, 7 },
   109605   { 186, 5 },
   109606   { 186, 5 },
   109607   { 186, 10 },
   109608   { 188, 0 },
   109609   { 188, 1 },
   109610   { 176, 0 },
   109611   { 176, 3 },
   109612   { 189, 0 },
   109613   { 189, 2 },
   109614   { 190, 1 },
   109615   { 190, 1 },
   109616   { 190, 1 },
   109617   { 147, 4 },
   109618   { 192, 2 },
   109619   { 192, 0 },
   109620   { 147, 8 },
   109621   { 147, 4 },
   109622   { 147, 1 },
   109623   { 160, 1 },
   109624   { 160, 3 },
   109625   { 195, 1 },
   109626   { 195, 2 },
   109627   { 195, 1 },
   109628   { 194, 9 },
   109629   { 196, 1 },
   109630   { 196, 1 },
   109631   { 196, 0 },
   109632   { 204, 2 },
   109633   { 204, 0 },
   109634   { 197, 3 },
   109635   { 197, 2 },
   109636   { 197, 4 },
   109637   { 205, 2 },
   109638   { 205, 1 },
   109639   { 205, 0 },
   109640   { 198, 0 },
   109641   { 198, 2 },
   109642   { 207, 2 },
   109643   { 207, 0 },
   109644   { 206, 7 },
   109645   { 206, 7 },
   109646   { 206, 7 },
   109647   { 157, 0 },
   109648   { 157, 2 },
   109649   { 193, 2 },
   109650   { 208, 1 },
   109651   { 208, 2 },
   109652   { 208, 3 },
   109653   { 208, 4 },
   109654   { 210, 2 },
   109655   { 210, 0 },
   109656   { 209, 0 },
   109657   { 209, 3 },
   109658   { 209, 2 },
   109659   { 211, 4 },
   109660   { 211, 0 },
   109661   { 202, 0 },
   109662   { 202, 3 },
   109663   { 214, 4 },
   109664   { 214, 2 },
   109665   { 177, 1 },
   109666   { 177, 1 },
   109667   { 177, 0 },
   109668   { 200, 0 },
   109669   { 200, 3 },
   109670   { 201, 0 },
   109671   { 201, 2 },
   109672   { 203, 0 },
   109673   { 203, 2 },
   109674   { 203, 4 },
   109675   { 203, 4 },
   109676   { 147, 5 },
   109677   { 199, 0 },
   109678   { 199, 2 },
   109679   { 147, 7 },
   109680   { 216, 5 },
   109681   { 216, 3 },
   109682   { 147, 5 },
   109683   { 147, 5 },
   109684   { 147, 6 },
   109685   { 217, 2 },
   109686   { 217, 1 },
   109687   { 219, 4 },
   109688   { 219, 5 },
   109689   { 218, 0 },
   109690   { 218, 3 },
   109691   { 213, 3 },
   109692   { 213, 1 },
   109693   { 175, 1 },
   109694   { 175, 3 },
   109695   { 174, 1 },
   109696   { 175, 1 },
   109697   { 175, 1 },
   109698   { 175, 3 },
   109699   { 175, 5 },
   109700   { 174, 1 },
   109701   { 174, 1 },
   109702   { 175, 1 },
   109703   { 175, 1 },
   109704   { 175, 3 },
   109705   { 175, 6 },
   109706   { 175, 5 },
   109707   { 175, 4 },
   109708   { 174, 1 },
   109709   { 175, 3 },
   109710   { 175, 3 },
   109711   { 175, 3 },
   109712   { 175, 3 },
   109713   { 175, 3 },
   109714   { 175, 3 },
   109715   { 175, 3 },
   109716   { 175, 3 },
   109717   { 221, 1 },
   109718   { 221, 2 },
   109719   { 221, 1 },
   109720   { 221, 2 },
   109721   { 175, 3 },
   109722   { 175, 5 },
   109723   { 175, 2 },
   109724   { 175, 3 },
   109725   { 175, 3 },
   109726   { 175, 4 },
   109727   { 175, 2 },
   109728   { 175, 2 },
   109729   { 175, 2 },
   109730   { 175, 2 },
   109731   { 222, 1 },
   109732   { 222, 2 },
   109733   { 175, 5 },
   109734   { 223, 1 },
   109735   { 223, 2 },
   109736   { 175, 5 },
   109737   { 175, 3 },
   109738   { 175, 5 },
   109739   { 175, 4 },
   109740   { 175, 4 },
   109741   { 175, 5 },
   109742   { 225, 5 },
   109743   { 225, 4 },
   109744   { 226, 2 },
   109745   { 226, 0 },
   109746   { 224, 1 },
   109747   { 224, 0 },
   109748   { 220, 1 },
   109749   { 220, 0 },
   109750   { 215, 3 },
   109751   { 215, 1 },
   109752   { 147, 11 },
   109753   { 227, 1 },
   109754   { 227, 0 },
   109755   { 179, 0 },
   109756   { 179, 3 },
   109757   { 187, 5 },
   109758   { 187, 3 },
   109759   { 228, 0 },
   109760   { 228, 2 },
   109761   { 147, 4 },
   109762   { 147, 1 },
   109763   { 147, 2 },
   109764   { 147, 3 },
   109765   { 147, 5 },
   109766   { 147, 6 },
   109767   { 147, 5 },
   109768   { 147, 6 },
   109769   { 229, 1 },
   109770   { 229, 1 },
   109771   { 229, 1 },
   109772   { 229, 1 },
   109773   { 229, 1 },
   109774   { 170, 2 },
   109775   { 170, 1 },
   109776   { 171, 2 },
   109777   { 230, 1 },
   109778   { 147, 5 },
   109779   { 231, 11 },
   109780   { 233, 1 },
   109781   { 233, 1 },
   109782   { 233, 2 },
   109783   { 233, 0 },
   109784   { 234, 1 },
   109785   { 234, 1 },
   109786   { 234, 3 },
   109787   { 235, 0 },
   109788   { 235, 3 },
   109789   { 236, 0 },
   109790   { 236, 2 },
   109791   { 232, 3 },
   109792   { 232, 2 },
   109793   { 238, 1 },
   109794   { 238, 3 },
   109795   { 239, 0 },
   109796   { 239, 3 },
   109797   { 239, 2 },
   109798   { 237, 7 },
   109799   { 237, 5 },
   109800   { 237, 5 },
   109801   { 237, 5 },
   109802   { 237, 1 },
   109803   { 175, 4 },
   109804   { 175, 6 },
   109805   { 191, 1 },
   109806   { 191, 1 },
   109807   { 191, 1 },
   109808   { 147, 4 },
   109809   { 147, 6 },
   109810   { 147, 3 },
   109811   { 241, 0 },
   109812   { 241, 2 },
   109813   { 240, 1 },
   109814   { 240, 0 },
   109815   { 147, 1 },
   109816   { 147, 3 },
   109817   { 147, 1 },
   109818   { 147, 3 },
   109819   { 147, 6 },
   109820   { 147, 6 },
   109821   { 242, 1 },
   109822   { 243, 0 },
   109823   { 243, 1 },
   109824   { 147, 1 },
   109825   { 147, 4 },
   109826   { 244, 8 },
   109827   { 245, 1 },
   109828   { 245, 3 },
   109829   { 246, 0 },
   109830   { 246, 2 },
   109831   { 247, 1 },
   109832   { 247, 3 },
   109833   { 248, 1 },
   109834   { 249, 0 },
   109835   { 249, 4 },
   109836   { 249, 2 },
   109837 };
   109838 
   109839 static void yy_accept(yyParser*);  /* Forward Declaration */
   109840 
   109841 /*
   109842 ** Perform a reduce action and the shift that must immediately
   109843 ** follow the reduce.
   109844 */
   109845 static void yy_reduce(
   109846   yyParser *yypParser,         /* The parser */
   109847   int yyruleno                 /* Number of the rule by which to reduce */
   109848 ){
   109849   int yygoto;                     /* The next state */
   109850   int yyact;                      /* The next action */
   109851   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   109852   yyStackEntry *yymsp;            /* The top of the parser's stack */
   109853   int yysize;                     /* Amount to pop the stack */
   109854   sqlite3ParserARG_FETCH;
   109855   yymsp = &yypParser->yystack[yypParser->yyidx];
   109856 #ifndef NDEBUG
   109857   if( yyTraceFILE && yyruleno>=0
   109858         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   109859     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   109860       yyRuleName[yyruleno]);
   109861   }
   109862 #endif /* NDEBUG */
   109863 
   109864   /* Silence complaints from purify about yygotominor being uninitialized
   109865   ** in some cases when it is copied into the stack after the following
   109866   ** switch.  yygotominor is uninitialized when a rule reduces that does
   109867   ** not set the value of its left-hand side nonterminal.  Leaving the
   109868   ** value of the nonterminal uninitialized is utterly harmless as long
   109869   ** as the value is never used.  So really the only thing this code
   109870   ** accomplishes is to quieten purify.
   109871   **
   109872   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   109873   ** without this code, their parser segfaults.  I'm not sure what there
   109874   ** parser is doing to make this happen.  This is the second bug report
   109875   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   109876   ** that it has not been previously stressed...  (SQLite ticket #2172)
   109877   */
   109878   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   109879   yygotominor = yyzerominor;
   109880 
   109881 
   109882   switch( yyruleno ){
   109883   /* Beginning here are the reduction cases.  A typical example
   109884   ** follows:
   109885   **   case 0:
   109886   **  #line <lineno> <grammarfile>
   109887   **     { ... }           // User supplied code
   109888   **  #line <lineno> <thisfile>
   109889   **     break;
   109890   */
   109891       case 5: /* explain ::= */
   109892 { sqlite3BeginParse(pParse, 0); }
   109893         break;
   109894       case 6: /* explain ::= EXPLAIN */
   109895 { sqlite3BeginParse(pParse, 1); }
   109896         break;
   109897       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   109898 { sqlite3BeginParse(pParse, 2); }
   109899         break;
   109900       case 8: /* cmdx ::= cmd */
   109901 { sqlite3FinishCoding(pParse); }
   109902         break;
   109903       case 9: /* cmd ::= BEGIN transtype trans_opt */
   109904 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
   109905         break;
   109906       case 13: /* transtype ::= */
   109907 {yygotominor.yy392 = TK_DEFERRED;}
   109908         break;
   109909       case 14: /* transtype ::= DEFERRED */
   109910       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   109911       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   109912       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   109913       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   109914 {yygotominor.yy392 = yymsp[0].major;}
   109915         break;
   109916       case 17: /* cmd ::= COMMIT trans_opt */
   109917       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   109918 {sqlite3CommitTransaction(pParse);}
   109919         break;
   109920       case 19: /* cmd ::= ROLLBACK trans_opt */
   109921 {sqlite3RollbackTransaction(pParse);}
   109922         break;
   109923       case 22: /* cmd ::= SAVEPOINT nm */
   109924 {
   109925   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   109926 }
   109927         break;
   109928       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   109929 {
   109930   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   109931 }
   109932         break;
   109933       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   109934 {
   109935   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   109936 }
   109937         break;
   109938       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   109939 {
   109940    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
   109941 }
   109942         break;
   109943       case 27: /* createkw ::= CREATE */
   109944 {
   109945   pParse->db->lookaside.bEnabled = 0;
   109946   yygotominor.yy0 = yymsp[0].minor.yy0;
   109947 }
   109948         break;
   109949       case 28: /* ifnotexists ::= */
   109950       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   109951       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
   109952       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
   109953       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
   109954       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
   109955       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
   109956       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
   109957       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
   109958       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
   109959       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
   109960       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
   109961 {yygotominor.yy392 = 0;}
   109962         break;
   109963       case 29: /* ifnotexists ::= IF NOT EXISTS */
   109964       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   109965       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
   109966       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
   109967       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
   109968       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
   109969       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
   109970       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
   109971 {yygotominor.yy392 = 1;}
   109972         break;
   109973       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
   109974 {
   109975   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
   109976 }
   109977         break;
   109978       case 33: /* create_table_args ::= AS select */
   109979 {
   109980   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
   109981   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
   109982 }
   109983         break;
   109984       case 36: /* column ::= columnid type carglist */
   109985 {
   109986   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   109987   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   109988 }
   109989         break;
   109990       case 37: /* columnid ::= nm */
   109991 {
   109992   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   109993   yygotominor.yy0 = yymsp[0].minor.yy0;
   109994 }
   109995         break;
   109996       case 38: /* id ::= ID */
   109997       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
   109998       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
   109999       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
   110000       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
   110001       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
   110002       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
   110003       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
   110004       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
   110005       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
   110006       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
   110007       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
   110008       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
   110009       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
   110010       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
   110011       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
   110012       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
   110013       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
   110014       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
   110015       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
   110016       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
   110017       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
   110018       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
   110019 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   110020         break;
   110021       case 45: /* type ::= typetoken */
   110022 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   110023         break;
   110024       case 47: /* typetoken ::= typename LP signed RP */
   110025 {
   110026   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   110027   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   110028 }
   110029         break;
   110030       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
   110031 {
   110032   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   110033   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   110034 }
   110035         break;
   110036       case 50: /* typename ::= typename ids */
   110037 {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);}
   110038         break;
   110039       case 57: /* ccons ::= DEFAULT term */
   110040       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
   110041 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
   110042         break;
   110043       case 58: /* ccons ::= DEFAULT LP expr RP */
   110044 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
   110045         break;
   110046       case 60: /* ccons ::= DEFAULT MINUS term */
   110047 {
   110048   ExprSpan v;
   110049   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
   110050   v.zStart = yymsp[-1].minor.yy0.z;
   110051   v.zEnd = yymsp[0].minor.yy342.zEnd;
   110052   sqlite3AddDefaultValue(pParse,&v);
   110053 }
   110054         break;
   110055       case 61: /* ccons ::= DEFAULT id */
   110056 {
   110057   ExprSpan v;
   110058   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   110059   sqlite3AddDefaultValue(pParse,&v);
   110060 }
   110061         break;
   110062       case 63: /* ccons ::= NOT NULL onconf */
   110063 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
   110064         break;
   110065       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   110066 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
   110067         break;
   110068       case 65: /* ccons ::= UNIQUE onconf */
   110069 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
   110070         break;
   110071       case 66: /* ccons ::= CHECK LP expr RP */
   110072 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
   110073         break;
   110074       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   110075 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
   110076         break;
   110077       case 68: /* ccons ::= defer_subclause */
   110078 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
   110079         break;
   110080       case 69: /* ccons ::= COLLATE ids */
   110081 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   110082         break;
   110083       case 72: /* refargs ::= */
   110084 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
   110085         break;
   110086       case 73: /* refargs ::= refargs refarg */
   110087 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
   110088         break;
   110089       case 74: /* refarg ::= MATCH nm */
   110090       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
   110091 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
   110092         break;
   110093       case 76: /* refarg ::= ON DELETE refact */
   110094 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
   110095         break;
   110096       case 77: /* refarg ::= ON UPDATE refact */
   110097 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
   110098         break;
   110099       case 78: /* refact ::= SET NULL */
   110100 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
   110101         break;
   110102       case 79: /* refact ::= SET DEFAULT */
   110103 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
   110104         break;
   110105       case 80: /* refact ::= CASCADE */
   110106 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
   110107         break;
   110108       case 81: /* refact ::= RESTRICT */
   110109 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
   110110         break;
   110111       case 82: /* refact ::= NO ACTION */
   110112 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
   110113         break;
   110114       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   110115       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
   110116       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
   110117       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
   110118 {yygotominor.yy392 = yymsp[0].minor.yy392;}
   110119         break;
   110120       case 88: /* conslist_opt ::= */
   110121 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   110122         break;
   110123       case 89: /* conslist_opt ::= COMMA conslist */
   110124 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   110125         break;
   110126       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   110127 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
   110128         break;
   110129       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
   110130 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
   110131         break;
   110132       case 96: /* tcons ::= CHECK LP expr RP onconf */
   110133 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
   110134         break;
   110135       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   110136 {
   110137     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
   110138     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
   110139 }
   110140         break;
   110141       case 100: /* onconf ::= */
   110142 {yygotominor.yy392 = OE_Default;}
   110143         break;
   110144       case 102: /* orconf ::= */
   110145 {yygotominor.yy258 = OE_Default;}
   110146         break;
   110147       case 103: /* orconf ::= OR resolvetype */
   110148 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
   110149         break;
   110150       case 105: /* resolvetype ::= IGNORE */
   110151 {yygotominor.yy392 = OE_Ignore;}
   110152         break;
   110153       case 106: /* resolvetype ::= REPLACE */
   110154 {yygotominor.yy392 = OE_Replace;}
   110155         break;
   110156       case 107: /* cmd ::= DROP TABLE ifexists fullname */
   110157 {
   110158   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
   110159 }
   110160         break;
   110161       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   110162 {
   110163   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);
   110164 }
   110165         break;
   110166       case 111: /* cmd ::= DROP VIEW ifexists fullname */
   110167 {
   110168   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
   110169 }
   110170         break;
   110171       case 112: /* cmd ::= select */
   110172 {
   110173   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
   110174   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
   110175   sqlite3ExplainBegin(pParse->pVdbe);
   110176   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
   110177   sqlite3ExplainFinish(pParse->pVdbe);
   110178   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
   110179 }
   110180         break;
   110181       case 113: /* select ::= oneselect */
   110182 {yygotominor.yy159 = yymsp[0].minor.yy159;}
   110183         break;
   110184       case 114: /* select ::= select multiselect_op oneselect */
   110185 {
   110186   if( yymsp[0].minor.yy159 ){
   110187     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
   110188     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
   110189   }else{
   110190     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
   110191   }
   110192   yygotominor.yy159 = yymsp[0].minor.yy159;
   110193 }
   110194         break;
   110195       case 116: /* multiselect_op ::= UNION ALL */
   110196 {yygotominor.yy392 = TK_ALL;}
   110197         break;
   110198       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   110199 {
   110200   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);
   110201 }
   110202         break;
   110203       case 122: /* sclp ::= selcollist COMMA */
   110204       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
   110205 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
   110206         break;
   110207       case 123: /* sclp ::= */
   110208       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
   110209       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
   110210       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
   110211       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
   110212 {yygotominor.yy442 = 0;}
   110213         break;
   110214       case 124: /* selcollist ::= sclp expr as */
   110215 {
   110216    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
   110217    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
   110218    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
   110219 }
   110220         break;
   110221       case 125: /* selcollist ::= sclp STAR */
   110222 {
   110223   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   110224   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
   110225 }
   110226         break;
   110227       case 126: /* selcollist ::= sclp nm DOT STAR */
   110228 {
   110229   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   110230   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110231   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   110232   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
   110233 }
   110234         break;
   110235       case 129: /* as ::= */
   110236 {yygotominor.yy0.n = 0;}
   110237         break;
   110238       case 130: /* from ::= */
   110239 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
   110240         break;
   110241       case 131: /* from ::= FROM seltablist */
   110242 {
   110243   yygotominor.yy347 = yymsp[0].minor.yy347;
   110244   sqlite3SrcListShiftJoinType(yygotominor.yy347);
   110245 }
   110246         break;
   110247       case 132: /* stl_prefix ::= seltablist joinop */
   110248 {
   110249    yygotominor.yy347 = yymsp[-1].minor.yy347;
   110250    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
   110251 }
   110252         break;
   110253       case 133: /* stl_prefix ::= */
   110254 {yygotominor.yy347 = 0;}
   110255         break;
   110256       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   110257 {
   110258   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);
   110259   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
   110260 }
   110261         break;
   110262       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   110263 {
   110264     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);
   110265   }
   110266         break;
   110267       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   110268 {
   110269     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
   110270       yygotominor.yy347 = yymsp[-4].minor.yy347;
   110271     }else{
   110272       Select *pSubquery;
   110273       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
   110274       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
   110275       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
   110276     }
   110277   }
   110278         break;
   110279       case 137: /* dbnm ::= */
   110280       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
   110281 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   110282         break;
   110283       case 139: /* fullname ::= nm dbnm */
   110284 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   110285         break;
   110286       case 140: /* joinop ::= COMMA|JOIN */
   110287 { yygotominor.yy392 = JT_INNER; }
   110288         break;
   110289       case 141: /* joinop ::= JOIN_KW JOIN */
   110290 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   110291         break;
   110292       case 142: /* joinop ::= JOIN_KW nm JOIN */
   110293 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   110294         break;
   110295       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
   110296 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   110297         break;
   110298       case 144: /* on_opt ::= ON expr */
   110299       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
   110300       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
   110301       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
   110302       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
   110303 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
   110304         break;
   110305       case 145: /* on_opt ::= */
   110306       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
   110307       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
   110308       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
   110309       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
   110310 {yygotominor.yy122 = 0;}
   110311         break;
   110312       case 148: /* indexed_opt ::= NOT INDEXED */
   110313 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   110314         break;
   110315       case 149: /* using_opt ::= USING LP inscollist RP */
   110316       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
   110317 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
   110318         break;
   110319       case 150: /* using_opt ::= */
   110320       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
   110321 {yygotominor.yy180 = 0;}
   110322         break;
   110323       case 152: /* orderby_opt ::= ORDER BY sortlist */
   110324       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
   110325       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
   110326 {yygotominor.yy442 = yymsp[0].minor.yy442;}
   110327         break;
   110328       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
   110329 {
   110330   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
   110331   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110332 }
   110333         break;
   110334       case 154: /* sortlist ::= expr sortorder */
   110335 {
   110336   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
   110337   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
   110338 }
   110339         break;
   110340       case 155: /* sortorder ::= ASC */
   110341       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
   110342 {yygotominor.yy392 = SQLITE_SO_ASC;}
   110343         break;
   110344       case 156: /* sortorder ::= DESC */
   110345 {yygotominor.yy392 = SQLITE_SO_DESC;}
   110346         break;
   110347       case 162: /* limit_opt ::= */
   110348 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
   110349         break;
   110350       case 163: /* limit_opt ::= LIMIT expr */
   110351 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
   110352         break;
   110353       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
   110354 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
   110355         break;
   110356       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
   110357 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
   110358         break;
   110359       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
   110360 {
   110361   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
   110362   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
   110363 }
   110364         break;
   110365       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
   110366 {
   110367   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
   110368   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
   110369   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
   110370 }
   110371         break;
   110372       case 170: /* setlist ::= setlist COMMA nm EQ expr */
   110373 {
   110374   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
   110375   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110376 }
   110377         break;
   110378       case 171: /* setlist ::= nm EQ expr */
   110379 {
   110380   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
   110381   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110382 }
   110383         break;
   110384       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
   110385 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
   110386         break;
   110387       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
   110388 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
   110389         break;
   110390       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   110391 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
   110392         break;
   110393       case 175: /* insert_cmd ::= INSERT orconf */
   110394 {yygotominor.yy258 = yymsp[0].minor.yy258;}
   110395         break;
   110396       case 176: /* insert_cmd ::= REPLACE */
   110397 {yygotominor.yy258 = OE_Replace;}
   110398         break;
   110399       case 177: /* valuelist ::= VALUES LP nexprlist RP */
   110400 {
   110401   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
   110402   yygotominor.yy487.pSelect = 0;
   110403 }
   110404         break;
   110405       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
   110406 {
   110407   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
   110408   if( yymsp[-4].minor.yy487.pList ){
   110409     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
   110410     yymsp[-4].minor.yy487.pList = 0;
   110411   }
   110412   yygotominor.yy487.pList = 0;
   110413   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
   110414     sqlite3SelectDelete(pParse->db, pRight);
   110415     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
   110416     yygotominor.yy487.pSelect = 0;
   110417   }else{
   110418     pRight->op = TK_ALL;
   110419     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
   110420     pRight->selFlags |= SF_Values;
   110421     pRight->pPrior->selFlags |= SF_Values;
   110422     yygotominor.yy487.pSelect = pRight;
   110423   }
   110424 }
   110425         break;
   110426       case 181: /* inscollist ::= inscollist COMMA nm */
   110427 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
   110428         break;
   110429       case 182: /* inscollist ::= nm */
   110430 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   110431         break;
   110432       case 183: /* expr ::= term */
   110433 {yygotominor.yy342 = yymsp[0].minor.yy342;}
   110434         break;
   110435       case 184: /* expr ::= LP expr RP */
   110436 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   110437         break;
   110438       case 185: /* term ::= NULL */
   110439       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
   110440       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
   110441 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   110442         break;
   110443       case 186: /* expr ::= id */
   110444       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
   110445 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
   110446         break;
   110447       case 188: /* expr ::= nm DOT nm */
   110448 {
   110449   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110450   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   110451   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   110452   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   110453 }
   110454         break;
   110455       case 189: /* expr ::= nm DOT nm DOT nm */
   110456 {
   110457   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   110458   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   110459   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   110460   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   110461   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   110462   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   110463 }
   110464         break;
   110465       case 192: /* expr ::= REGISTER */
   110466 {
   110467   /* When doing a nested parse, one can include terms in an expression
   110468   ** that look like this:   #1 #2 ...  These terms refer to registers
   110469   ** in the virtual machine.  #N is the N-th register. */
   110470   if( pParse->nested==0 ){
   110471     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   110472     yygotominor.yy342.pExpr = 0;
   110473   }else{
   110474     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   110475     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
   110476   }
   110477   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110478 }
   110479         break;
   110480       case 193: /* expr ::= VARIABLE */
   110481 {
   110482   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   110483   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
   110484   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110485 }
   110486         break;
   110487       case 194: /* expr ::= expr COLLATE ids */
   110488 {
   110489   yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
   110490   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
   110491   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110492 }
   110493         break;
   110494       case 195: /* expr ::= CAST LP expr AS typetoken RP */
   110495 {
   110496   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
   110497   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   110498 }
   110499         break;
   110500       case 196: /* expr ::= ID LP distinct exprlist RP */
   110501 {
   110502   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   110503     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   110504   }
   110505   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
   110506   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   110507   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
   110508     yygotominor.yy342.pExpr->flags |= EP_Distinct;
   110509   }
   110510 }
   110511         break;
   110512       case 197: /* expr ::= ID LP STAR RP */
   110513 {
   110514   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   110515   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   110516 }
   110517         break;
   110518       case 198: /* term ::= CTIME_KW */
   110519 {
   110520   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
   110521   ** treated as functions that return constants */
   110522   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
   110523   if( yygotominor.yy342.pExpr ){
   110524     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
   110525   }
   110526   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   110527 }
   110528         break;
   110529       case 199: /* expr ::= expr AND expr */
   110530       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
   110531       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
   110532       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
   110533       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
   110534       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
   110535       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
   110536       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
   110537 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
   110538         break;
   110539       case 207: /* likeop ::= LIKE_KW */
   110540       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
   110541 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
   110542         break;
   110543       case 208: /* likeop ::= NOT LIKE_KW */
   110544       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
   110545 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
   110546         break;
   110547       case 211: /* expr ::= expr likeop expr */
   110548 {
   110549   ExprList *pList;
   110550   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
   110551   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
   110552   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
   110553   if( yymsp[-1].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110554   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
   110555   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110556   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
   110557 }
   110558         break;
   110559       case 212: /* expr ::= expr likeop expr ESCAPE expr */
   110560 {
   110561   ExprList *pList;
   110562   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110563   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
   110564   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
   110565   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
   110566   if( yymsp[-3].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110567   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110568   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110569   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
   110570 }
   110571         break;
   110572       case 213: /* expr ::= expr ISNULL|NOTNULL */
   110573 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
   110574         break;
   110575       case 214: /* expr ::= expr NOT NULL */
   110576 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
   110577         break;
   110578       case 215: /* expr ::= expr IS expr */
   110579 {
   110580   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
   110581   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
   110582 }
   110583         break;
   110584       case 216: /* expr ::= expr IS NOT expr */
   110585 {
   110586   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
   110587   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
   110588 }
   110589         break;
   110590       case 217: /* expr ::= NOT expr */
   110591       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
   110592 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110593         break;
   110594       case 219: /* expr ::= MINUS expr */
   110595 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110596         break;
   110597       case 220: /* expr ::= PLUS expr */
   110598 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
   110599         break;
   110600       case 223: /* expr ::= expr between_op expr AND expr */
   110601 {
   110602   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110603   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
   110604   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110605   if( yygotominor.yy342.pExpr ){
   110606     yygotominor.yy342.pExpr->x.pList = pList;
   110607   }else{
   110608     sqlite3ExprListDelete(pParse->db, pList);
   110609   }
   110610   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110611   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110612   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
   110613 }
   110614         break;
   110615       case 226: /* expr ::= expr in_op LP exprlist RP */
   110616 {
   110617     if( yymsp[-1].minor.yy442==0 ){
   110618       /* Expressions of the form
   110619       **
   110620       **      expr1 IN ()
   110621       **      expr1 NOT IN ()
   110622       **
   110623       ** simplify to constants 0 (false) and 1 (true), respectively,
   110624       ** regardless of the value of expr1.
   110625       */
   110626       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
   110627       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
   110628     }else{
   110629       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110630       if( yygotominor.yy342.pExpr ){
   110631         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
   110632         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110633       }else{
   110634         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
   110635       }
   110636       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110637     }
   110638     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110639     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110640   }
   110641         break;
   110642       case 227: /* expr ::= LP select RP */
   110643 {
   110644     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   110645     if( yygotominor.yy342.pExpr ){
   110646       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
   110647       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110648       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110649     }else{
   110650       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110651     }
   110652     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
   110653     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110654   }
   110655         break;
   110656       case 228: /* expr ::= expr in_op LP select RP */
   110657 {
   110658     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
   110659     if( yygotominor.yy342.pExpr ){
   110660       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
   110661       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110662       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110663     }else{
   110664       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110665     }
   110666     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110667     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
   110668     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110669   }
   110670         break;
   110671       case 229: /* expr ::= expr in_op nm dbnm */
   110672 {
   110673     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   110674     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
   110675     if( yygotominor.yy342.pExpr ){
   110676       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   110677       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
   110678       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110679     }else{
   110680       sqlite3SrcListDelete(pParse->db, pSrc);
   110681     }
   110682     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
   110683     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
   110684     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];
   110685   }
   110686         break;
   110687       case 230: /* expr ::= EXISTS LP select RP */
   110688 {
   110689     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   110690     if( p ){
   110691       p->x.pSelect = yymsp[-1].minor.yy159;
   110692       ExprSetProperty(p, EP_xIsSelect);
   110693       sqlite3ExprSetHeight(pParse, p);
   110694     }else{
   110695       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
   110696     }
   110697     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
   110698     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110699   }
   110700         break;
   110701       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
   110702 {
   110703   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
   110704   if( yygotominor.yy342.pExpr ){
   110705     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
   110706     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
   110707   }else{
   110708     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
   110709   }
   110710   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
   110711   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110712 }
   110713         break;
   110714       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   110715 {
   110716   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
   110717   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
   110718 }
   110719         break;
   110720       case 233: /* case_exprlist ::= WHEN expr THEN expr */
   110721 {
   110722   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
   110723   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
   110724 }
   110725         break;
   110726       case 240: /* nexprlist ::= nexprlist COMMA expr */
   110727 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
   110728         break;
   110729       case 241: /* nexprlist ::= expr */
   110730 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
   110731         break;
   110732       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
   110733 {
   110734   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
   110735                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
   110736                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
   110737 }
   110738         break;
   110739       case 243: /* uniqueflag ::= UNIQUE */
   110740       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
   110741 {yygotominor.yy392 = OE_Abort;}
   110742         break;
   110743       case 244: /* uniqueflag ::= */
   110744 {yygotominor.yy392 = OE_None;}
   110745         break;
   110746       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
   110747 {
   110748   Expr *p = 0;
   110749   if( yymsp[-1].minor.yy0.n>0 ){
   110750     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
   110751     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   110752   }
   110753   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
   110754   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
   110755   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
   110756   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110757 }
   110758         break;
   110759       case 248: /* idxlist ::= nm collate sortorder */
   110760 {
   110761   Expr *p = 0;
   110762   if( yymsp[-1].minor.yy0.n>0 ){
   110763     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
   110764     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   110765   }
   110766   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
   110767   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
   110768   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
   110769   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
   110770 }
   110771         break;
   110772       case 249: /* collate ::= */
   110773 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   110774         break;
   110775       case 251: /* cmd ::= DROP INDEX ifexists fullname */
   110776 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
   110777         break;
   110778       case 252: /* cmd ::= VACUUM */
   110779       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
   110780 {sqlite3Vacuum(pParse);}
   110781         break;
   110782       case 254: /* cmd ::= PRAGMA nm dbnm */
   110783 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   110784         break;
   110785       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   110786 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   110787         break;
   110788       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   110789 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   110790         break;
   110791       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   110792 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   110793         break;
   110794       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   110795 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   110796         break;
   110797       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   110798 {
   110799   Token all;
   110800   all.z = yymsp[-3].minor.yy0.z;
   110801   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   110802   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
   110803 }
   110804         break;
   110805       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   110806 {
   110807   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);
   110808   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   110809 }
   110810         break;
   110811       case 270: /* trigger_time ::= BEFORE */
   110812       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
   110813 { yygotominor.yy392 = TK_BEFORE; }
   110814         break;
   110815       case 271: /* trigger_time ::= AFTER */
   110816 { yygotominor.yy392 = TK_AFTER;  }
   110817         break;
   110818       case 272: /* trigger_time ::= INSTEAD OF */
   110819 { yygotominor.yy392 = TK_INSTEAD;}
   110820         break;
   110821       case 274: /* trigger_event ::= DELETE|INSERT */
   110822       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
   110823 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
   110824         break;
   110825       case 276: /* trigger_event ::= UPDATE OF inscollist */
   110826 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
   110827         break;
   110828       case 279: /* when_clause ::= */
   110829       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
   110830 { yygotominor.yy122 = 0; }
   110831         break;
   110832       case 280: /* when_clause ::= WHEN expr */
   110833       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
   110834 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
   110835         break;
   110836       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   110837 {
   110838   assert( yymsp[-2].minor.yy327!=0 );
   110839   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
   110840   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
   110841   yygotominor.yy327 = yymsp[-2].minor.yy327;
   110842 }
   110843         break;
   110844       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
   110845 {
   110846   assert( yymsp[-1].minor.yy327!=0 );
   110847   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
   110848   yygotominor.yy327 = yymsp[-1].minor.yy327;
   110849 }
   110850         break;
   110851       case 284: /* trnm ::= nm DOT nm */
   110852 {
   110853   yygotominor.yy0 = yymsp[0].minor.yy0;
   110854   sqlite3ErrorMsg(pParse,
   110855         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   110856         "statements within triggers");
   110857 }
   110858         break;
   110859       case 286: /* tridxby ::= INDEXED BY nm */
   110860 {
   110861   sqlite3ErrorMsg(pParse,
   110862         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   110863         "within triggers");
   110864 }
   110865         break;
   110866       case 287: /* tridxby ::= NOT INDEXED */
   110867 {
   110868   sqlite3ErrorMsg(pParse,
   110869         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   110870         "within triggers");
   110871 }
   110872         break;
   110873       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   110874 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
   110875         break;
   110876       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
   110877 {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);}
   110878         break;
   110879       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   110880 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
   110881         break;
   110882       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   110883 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
   110884         break;
   110885       case 292: /* trigger_cmd ::= select */
   110886 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
   110887         break;
   110888       case 293: /* expr ::= RAISE LP IGNORE RP */
   110889 {
   110890   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   110891   if( yygotominor.yy342.pExpr ){
   110892     yygotominor.yy342.pExpr->affinity = OE_Ignore;
   110893   }
   110894   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
   110895   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110896 }
   110897         break;
   110898       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
   110899 {
   110900   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   110901   if( yygotominor.yy342.pExpr ) {
   110902     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
   110903   }
   110904   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
   110905   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   110906 }
   110907         break;
   110908       case 295: /* raisetype ::= ROLLBACK */
   110909 {yygotominor.yy392 = OE_Rollback;}
   110910         break;
   110911       case 297: /* raisetype ::= FAIL */
   110912 {yygotominor.yy392 = OE_Fail;}
   110913         break;
   110914       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
   110915 {
   110916   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
   110917 }
   110918         break;
   110919       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   110920 {
   110921   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
   110922 }
   110923         break;
   110924       case 300: /* cmd ::= DETACH database_kw_opt expr */
   110925 {
   110926   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
   110927 }
   110928         break;
   110929       case 305: /* cmd ::= REINDEX */
   110930 {sqlite3Reindex(pParse, 0, 0);}
   110931         break;
   110932       case 306: /* cmd ::= REINDEX nm dbnm */
   110933 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   110934         break;
   110935       case 307: /* cmd ::= ANALYZE */
   110936 {sqlite3Analyze(pParse, 0, 0);}
   110937         break;
   110938       case 308: /* cmd ::= ANALYZE nm dbnm */
   110939 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   110940         break;
   110941       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   110942 {
   110943   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
   110944 }
   110945         break;
   110946       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   110947 {
   110948   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   110949 }
   110950         break;
   110951       case 311: /* add_column_fullname ::= fullname */
   110952 {
   110953   pParse->db->lookaside.bEnabled = 0;
   110954   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
   110955 }
   110956         break;
   110957       case 314: /* cmd ::= create_vtab */
   110958 {sqlite3VtabFinishParse(pParse,0);}
   110959         break;
   110960       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
   110961 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   110962         break;
   110963       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
   110964 {
   110965     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
   110966 }
   110967         break;
   110968       case 319: /* vtabarg ::= */
   110969 {sqlite3VtabArgInit(pParse);}
   110970         break;
   110971       case 321: /* vtabargtoken ::= ANY */
   110972       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
   110973       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
   110974 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   110975         break;
   110976       default:
   110977       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   110978       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   110979       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   110980       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   110981       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   110982       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   110983       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   110984       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   110985       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   110986       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   110987       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   110988       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
   110989       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
   110990       /* (44) type ::= */ yytestcase(yyruleno==44);
   110991       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
   110992       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
   110993       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
   110994       /* (54) carglist ::= */ yytestcase(yyruleno==54);
   110995       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
   110996       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
   110997       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
   110998       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
   110999       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
   111000       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
   111001       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
   111002       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
   111003       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
   111004       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
   111005       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
   111006       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
   111007       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
   111008       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
   111009       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
   111010       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
   111011       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
   111012       /* (324) anylist ::= */ yytestcase(yyruleno==324);
   111013       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
   111014       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
   111015         break;
   111016   };
   111017   yygoto = yyRuleInfo[yyruleno].lhs;
   111018   yysize = yyRuleInfo[yyruleno].nrhs;
   111019   yypParser->yyidx -= yysize;
   111020   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   111021   if( yyact < YYNSTATE ){
   111022 #ifdef NDEBUG
   111023     /* If we are not debugging and the reduce action popped at least
   111024     ** one element off the stack, then we can push the new element back
   111025     ** onto the stack here, and skip the stack overflow test in yy_shift().
   111026     ** That gives a significant speed improvement. */
   111027     if( yysize ){
   111028       yypParser->yyidx++;
   111029       yymsp -= yysize-1;
   111030       yymsp->stateno = (YYACTIONTYPE)yyact;
   111031       yymsp->major = (YYCODETYPE)yygoto;
   111032       yymsp->minor = yygotominor;
   111033     }else
   111034 #endif
   111035     {
   111036       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   111037     }
   111038   }else{
   111039     assert( yyact == YYNSTATE + YYNRULE + 1 );
   111040     yy_accept(yypParser);
   111041   }
   111042 }
   111043 
   111044 /*
   111045 ** The following code executes when the parse fails
   111046 */
   111047 #ifndef YYNOERRORRECOVERY
   111048 static void yy_parse_failed(
   111049   yyParser *yypParser           /* The parser */
   111050 ){
   111051   sqlite3ParserARG_FETCH;
   111052 #ifndef NDEBUG
   111053   if( yyTraceFILE ){
   111054     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   111055   }
   111056 #endif
   111057   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   111058   /* Here code is inserted which will be executed whenever the
   111059   ** parser fails */
   111060   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111061 }
   111062 #endif /* YYNOERRORRECOVERY */
   111063 
   111064 /*
   111065 ** The following code executes when a syntax error first occurs.
   111066 */
   111067 static void yy_syntax_error(
   111068   yyParser *yypParser,           /* The parser */
   111069   int yymajor,                   /* The major type of the error token */
   111070   YYMINORTYPE yyminor            /* The minor type of the error token */
   111071 ){
   111072   sqlite3ParserARG_FETCH;
   111073 #define TOKEN (yyminor.yy0)
   111074 
   111075   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   111076   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   111077   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   111078   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111079 }
   111080 
   111081 /*
   111082 ** The following is executed when the parser accepts
   111083 */
   111084 static void yy_accept(
   111085   yyParser *yypParser           /* The parser */
   111086 ){
   111087   sqlite3ParserARG_FETCH;
   111088 #ifndef NDEBUG
   111089   if( yyTraceFILE ){
   111090     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   111091   }
   111092 #endif
   111093   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   111094   /* Here code is inserted which will be executed whenever the
   111095   ** parser accepts */
   111096   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   111097 }
   111098 
   111099 /* The main parser program.
   111100 ** The first argument is a pointer to a structure obtained from
   111101 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   111102 ** The second argument is the major token number.  The third is
   111103 ** the minor token.  The fourth optional argument is whatever the
   111104 ** user wants (and specified in the grammar) and is available for
   111105 ** use by the action routines.
   111106 **
   111107 ** Inputs:
   111108 ** <ul>
   111109 ** <li> A pointer to the parser (an opaque structure.)
   111110 ** <li> The major token number.
   111111 ** <li> The minor token number.
   111112 ** <li> An option argument of a grammar-specified type.
   111113 ** </ul>
   111114 **
   111115 ** Outputs:
   111116 ** None.
   111117 */
   111118 SQLITE_PRIVATE void sqlite3Parser(
   111119   void *yyp,                   /* The parser */
   111120   int yymajor,                 /* The major token code number */
   111121   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   111122   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   111123 ){
   111124   YYMINORTYPE yyminorunion;
   111125   int yyact;            /* The parser action. */
   111126 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   111127   int yyendofinput;     /* True if we are at the end of input */
   111128 #endif
   111129 #ifdef YYERRORSYMBOL
   111130   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   111131 #endif
   111132   yyParser *yypParser;  /* The parser */
   111133 
   111134   /* (re)initialize the parser, if necessary */
   111135   yypParser = (yyParser*)yyp;
   111136   if( yypParser->yyidx<0 ){
   111137 #if YYSTACKDEPTH<=0
   111138     if( yypParser->yystksz <=0 ){
   111139       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   111140       yyminorunion = yyzerominor;
   111141       yyStackOverflow(yypParser, &yyminorunion);
   111142       return;
   111143     }
   111144 #endif
   111145     yypParser->yyidx = 0;
   111146     yypParser->yyerrcnt = -1;
   111147     yypParser->yystack[0].stateno = 0;
   111148     yypParser->yystack[0].major = 0;
   111149   }
   111150   yyminorunion.yy0 = yyminor;
   111151 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
   111152   yyendofinput = (yymajor==0);
   111153 #endif
   111154   sqlite3ParserARG_STORE;
   111155 
   111156 #ifndef NDEBUG
   111157   if( yyTraceFILE ){
   111158     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   111159   }
   111160 #endif
   111161 
   111162   do{
   111163     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   111164     if( yyact<YYNSTATE ){
   111165       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   111166       yypParser->yyerrcnt--;
   111167       yymajor = YYNOCODE;
   111168     }else if( yyact < YYNSTATE + YYNRULE ){
   111169       yy_reduce(yypParser,yyact-YYNSTATE);
   111170     }else{
   111171       assert( yyact == YY_ERROR_ACTION );
   111172 #ifdef YYERRORSYMBOL
   111173       int yymx;
   111174 #endif
   111175 #ifndef NDEBUG
   111176       if( yyTraceFILE ){
   111177         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   111178       }
   111179 #endif
   111180 #ifdef YYERRORSYMBOL
   111181       /* A syntax error has occurred.
   111182       ** The response to an error depends upon whether or not the
   111183       ** grammar defines an error token "ERROR".
   111184       **
   111185       ** This is what we do if the grammar does define ERROR:
   111186       **
   111187       **  * Call the %syntax_error function.
   111188       **
   111189       **  * Begin popping the stack until we enter a state where
   111190       **    it is legal to shift the error symbol, then shift
   111191       **    the error symbol.
   111192       **
   111193       **  * Set the error count to three.
   111194       **
   111195       **  * Begin accepting and shifting new tokens.  No new error
   111196       **    processing will occur until three tokens have been
   111197       **    shifted successfully.
   111198       **
   111199       */
   111200       if( yypParser->yyerrcnt<0 ){
   111201         yy_syntax_error(yypParser,yymajor,yyminorunion);
   111202       }
   111203       yymx = yypParser->yystack[yypParser->yyidx].major;
   111204       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   111205 #ifndef NDEBUG
   111206         if( yyTraceFILE ){
   111207           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   111208              yyTracePrompt,yyTokenName[yymajor]);
   111209         }
   111210 #endif
   111211         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   111212         yymajor = YYNOCODE;
   111213       }else{
   111214          while(
   111215           yypParser->yyidx >= 0 &&
   111216           yymx != YYERRORSYMBOL &&
   111217           (yyact = yy_find_reduce_action(
   111218                         yypParser->yystack[yypParser->yyidx].stateno,
   111219                         YYERRORSYMBOL)) >= YYNSTATE
   111220         ){
   111221           yy_pop_parser_stack(yypParser);
   111222         }
   111223         if( yypParser->yyidx < 0 || yymajor==0 ){
   111224           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111225           yy_parse_failed(yypParser);
   111226           yymajor = YYNOCODE;
   111227         }else if( yymx!=YYERRORSYMBOL ){
   111228           YYMINORTYPE u2;
   111229           u2.YYERRSYMDT = 0;
   111230           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   111231         }
   111232       }
   111233       yypParser->yyerrcnt = 3;
   111234       yyerrorhit = 1;
   111235 #elif defined(YYNOERRORRECOVERY)
   111236       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   111237       ** do any kind of error recovery.  Instead, simply invoke the syntax
   111238       ** error routine and continue going as if nothing had happened.
   111239       **
   111240       ** Applications can set this macro (for example inside %include) if
   111241       ** they intend to abandon the parse upon the first syntax error seen.
   111242       */
   111243       yy_syntax_error(yypParser,yymajor,yyminorunion);
   111244       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111245       yymajor = YYNOCODE;
   111246 
   111247 #else  /* YYERRORSYMBOL is not defined */
   111248       /* This is what we do if the grammar does not define ERROR:
   111249       **
   111250       **  * Report an error message, and throw away the input token.
   111251       **
   111252       **  * If the input token is $, then fail the parse.
   111253       **
   111254       ** As before, subsequent error messages are suppressed until
   111255       ** three input tokens have been successfully shifted.
   111256       */
   111257       if( yypParser->yyerrcnt<=0 ){
   111258         yy_syntax_error(yypParser,yymajor,yyminorunion);
   111259       }
   111260       yypParser->yyerrcnt = 3;
   111261       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   111262       if( yyendofinput ){
   111263         yy_parse_failed(yypParser);
   111264       }
   111265       yymajor = YYNOCODE;
   111266 #endif
   111267     }
   111268   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   111269   return;
   111270 }
   111271 
   111272 /************** End of parse.c ***********************************************/
   111273 /************** Begin file tokenize.c ****************************************/
   111274 /*
   111275 ** 2001 September 15
   111276 **
   111277 ** The author disclaims copyright to this source code.  In place of
   111278 ** a legal notice, here is a blessing:
   111279 **
   111280 **    May you do good and not evil.
   111281 **    May you find forgiveness for yourself and forgive others.
   111282 **    May you share freely, never taking more than you give.
   111283 **
   111284 *************************************************************************
   111285 ** An tokenizer for SQL
   111286 **
   111287 ** This file contains C code that splits an SQL input string up into
   111288 ** individual tokens and sends those tokens one-by-one over to the
   111289 ** parser for analysis.
   111290 */
   111291 /* #include <stdlib.h> */
   111292 
   111293 /*
   111294 ** The charMap() macro maps alphabetic characters into their
   111295 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   111296 ** an upper-to-lower case map.  On EBCDIC machines we also need
   111297 ** to adjust the encoding.  Only alphabetic characters and underscores
   111298 ** need to be translated.
   111299 */
   111300 #ifdef SQLITE_ASCII
   111301 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   111302 #endif
   111303 #ifdef SQLITE_EBCDIC
   111304 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   111305 const unsigned char ebcdicToAscii[] = {
   111306 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   111307    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   111308    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   111309    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   111310    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   111311    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   111312    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   111313    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   111314    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   111315    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   111316    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   111317    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   111318    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   111319    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   111320    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   111321    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   111322    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   111323 };
   111324 #endif
   111325 
   111326 /*
   111327 ** The sqlite3KeywordCode function looks up an identifier to determine if
   111328 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   111329 ** returned.  If the input is not a keyword, TK_ID is returned.
   111330 **
   111331 ** The implementation of this routine was generated by a program,
   111332 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   111333 ** The output of the mkkeywordhash.c program is written into a file
   111334 ** named keywordhash.h and then included into this source file by
   111335 ** the #include below.
   111336 */
   111337 /************** Include keywordhash.h in the middle of tokenize.c ************/
   111338 /************** Begin file keywordhash.h *************************************/
   111339 /***** This file contains automatically generated code ******
   111340 **
   111341 ** The code in this file has been automatically generated by
   111342 **
   111343 **   sqlite/tool/mkkeywordhash.c
   111344 **
   111345 ** The code in this file implements a function that determines whether
   111346 ** or not a given identifier is really an SQL keyword.  The same thing
   111347 ** might be implemented more directly using a hand-written hash table.
   111348 ** But by using this automatically generated code, the size of the code
   111349 ** is substantially reduced.  This is important for embedded applications
   111350 ** on platforms with limited memory.
   111351 */
   111352 /* Hash score: 175 */
   111353 static int keywordCode(const char *z, int n){
   111354   /* zText[] encodes 811 bytes of keywords in 541 bytes */
   111355   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   111356   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   111357   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   111358   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
   111359   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
   111360   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
   111361   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
   111362   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
   111363   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
   111364   /*   INITIALLY                                                          */
   111365   static const char zText[540] = {
   111366     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   111367     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   111368     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   111369     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   111370     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   111371     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   111372     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   111373     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   111374     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   111375     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   111376     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
   111377     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
   111378     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
   111379     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
   111380     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
   111381     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
   111382     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
   111383     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
   111384     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
   111385     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
   111386     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
   111387     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
   111388     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
   111389     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
   111390     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
   111391     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
   111392     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
   111393     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
   111394     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
   111395     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
   111396   };
   111397   static const unsigned char aHash[127] = {
   111398       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
   111399       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
   111400      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
   111401        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
   111402        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
   111403       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
   111404       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
   111405       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
   111406       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
   111407       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
   111408   };
   111409   static const unsigned char aNext[121] = {
   111410        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   111411        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   111412        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   111413        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
   111414        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
   111415       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
   111416       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
   111417        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
   111418      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
   111419       35,  64,   0,   0,
   111420   };
   111421   static const unsigned char aLen[121] = {
   111422        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   111423        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   111424       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   111425        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
   111426        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
   111427        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
   111428        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
   111429        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
   111430        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
   111431        6,   4,   9,   3,
   111432   };
   111433   static const unsigned short int aOffset[121] = {
   111434        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   111435       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   111436       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   111437      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
   111438      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
   111439      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
   111440      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
   111441      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
   111442      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
   111443      521, 527, 531, 536,
   111444   };
   111445   static const unsigned char aCode[121] = {
   111446     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   111447     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   111448     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   111449     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   111450     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   111451     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   111452     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   111453     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   111454     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   111455     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
   111456     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
   111457     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
   111458     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
   111459     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
   111460     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
   111461     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
   111462     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
   111463     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
   111464     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
   111465     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
   111466     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
   111467     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
   111468     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
   111469     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
   111470     TK_ALL,
   111471   };
   111472   int h, i;
   111473   if( n<2 ) return TK_ID;
   111474   h = ((charMap(z[0])*4) ^
   111475       (charMap(z[n-1])*3) ^
   111476       n) % 127;
   111477   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   111478     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   111479       testcase( i==0 ); /* REINDEX */
   111480       testcase( i==1 ); /* INDEXED */
   111481       testcase( i==2 ); /* INDEX */
   111482       testcase( i==3 ); /* DESC */
   111483       testcase( i==4 ); /* ESCAPE */
   111484       testcase( i==5 ); /* EACH */
   111485       testcase( i==6 ); /* CHECK */
   111486       testcase( i==7 ); /* KEY */
   111487       testcase( i==8 ); /* BEFORE */
   111488       testcase( i==9 ); /* FOREIGN */
   111489       testcase( i==10 ); /* FOR */
   111490       testcase( i==11 ); /* IGNORE */
   111491       testcase( i==12 ); /* REGEXP */
   111492       testcase( i==13 ); /* EXPLAIN */
   111493       testcase( i==14 ); /* INSTEAD */
   111494       testcase( i==15 ); /* ADD */
   111495       testcase( i==16 ); /* DATABASE */
   111496       testcase( i==17 ); /* AS */
   111497       testcase( i==18 ); /* SELECT */
   111498       testcase( i==19 ); /* TABLE */
   111499       testcase( i==20 ); /* LEFT */
   111500       testcase( i==21 ); /* THEN */
   111501       testcase( i==22 ); /* END */
   111502       testcase( i==23 ); /* DEFERRABLE */
   111503       testcase( i==24 ); /* ELSE */
   111504       testcase( i==25 ); /* EXCEPT */
   111505       testcase( i==26 ); /* TRANSACTION */
   111506       testcase( i==27 ); /* ACTION */
   111507       testcase( i==28 ); /* ON */
   111508       testcase( i==29 ); /* NATURAL */
   111509       testcase( i==30 ); /* ALTER */
   111510       testcase( i==31 ); /* RAISE */
   111511       testcase( i==32 ); /* EXCLUSIVE */
   111512       testcase( i==33 ); /* EXISTS */
   111513       testcase( i==34 ); /* SAVEPOINT */
   111514       testcase( i==35 ); /* INTERSECT */
   111515       testcase( i==36 ); /* TRIGGER */
   111516       testcase( i==37 ); /* REFERENCES */
   111517       testcase( i==38 ); /* CONSTRAINT */
   111518       testcase( i==39 ); /* INTO */
   111519       testcase( i==40 ); /* OFFSET */
   111520       testcase( i==41 ); /* OF */
   111521       testcase( i==42 ); /* SET */
   111522       testcase( i==43 ); /* TEMPORARY */
   111523       testcase( i==44 ); /* TEMP */
   111524       testcase( i==45 ); /* OR */
   111525       testcase( i==46 ); /* UNIQUE */
   111526       testcase( i==47 ); /* QUERY */
   111527       testcase( i==48 ); /* ATTACH */
   111528       testcase( i==49 ); /* HAVING */
   111529       testcase( i==50 ); /* GROUP */
   111530       testcase( i==51 ); /* UPDATE */
   111531       testcase( i==52 ); /* BEGIN */
   111532       testcase( i==53 ); /* INNER */
   111533       testcase( i==54 ); /* RELEASE */
   111534       testcase( i==55 ); /* BETWEEN */
   111535       testcase( i==56 ); /* NOTNULL */
   111536       testcase( i==57 ); /* NOT */
   111537       testcase( i==58 ); /* NO */
   111538       testcase( i==59 ); /* NULL */
   111539       testcase( i==60 ); /* LIKE */
   111540       testcase( i==61 ); /* CASCADE */
   111541       testcase( i==62 ); /* ASC */
   111542       testcase( i==63 ); /* DELETE */
   111543       testcase( i==64 ); /* CASE */
   111544       testcase( i==65 ); /* COLLATE */
   111545       testcase( i==66 ); /* CREATE */
   111546       testcase( i==67 ); /* CURRENT_DATE */
   111547       testcase( i==68 ); /* DETACH */
   111548       testcase( i==69 ); /* IMMEDIATE */
   111549       testcase( i==70 ); /* JOIN */
   111550       testcase( i==71 ); /* INSERT */
   111551       testcase( i==72 ); /* MATCH */
   111552       testcase( i==73 ); /* PLAN */
   111553       testcase( i==74 ); /* ANALYZE */
   111554       testcase( i==75 ); /* PRAGMA */
   111555       testcase( i==76 ); /* ABORT */
   111556       testcase( i==77 ); /* VALUES */
   111557       testcase( i==78 ); /* VIRTUAL */
   111558       testcase( i==79 ); /* LIMIT */
   111559       testcase( i==80 ); /* WHEN */
   111560       testcase( i==81 ); /* WHERE */
   111561       testcase( i==82 ); /* RENAME */
   111562       testcase( i==83 ); /* AFTER */
   111563       testcase( i==84 ); /* REPLACE */
   111564       testcase( i==85 ); /* AND */
   111565       testcase( i==86 ); /* DEFAULT */
   111566       testcase( i==87 ); /* AUTOINCREMENT */
   111567       testcase( i==88 ); /* TO */
   111568       testcase( i==89 ); /* IN */
   111569       testcase( i==90 ); /* CAST */
   111570       testcase( i==91 ); /* COLUMN */
   111571       testcase( i==92 ); /* COMMIT */
   111572       testcase( i==93 ); /* CONFLICT */
   111573       testcase( i==94 ); /* CROSS */
   111574       testcase( i==95 ); /* CURRENT_TIMESTAMP */
   111575       testcase( i==96 ); /* CURRENT_TIME */
   111576       testcase( i==97 ); /* PRIMARY */
   111577       testcase( i==98 ); /* DEFERRED */
   111578       testcase( i==99 ); /* DISTINCT */
   111579       testcase( i==100 ); /* IS */
   111580       testcase( i==101 ); /* DROP */
   111581       testcase( i==102 ); /* FAIL */
   111582       testcase( i==103 ); /* FROM */
   111583       testcase( i==104 ); /* FULL */
   111584       testcase( i==105 ); /* GLOB */
   111585       testcase( i==106 ); /* BY */
   111586       testcase( i==107 ); /* IF */
   111587       testcase( i==108 ); /* ISNULL */
   111588       testcase( i==109 ); /* ORDER */
   111589       testcase( i==110 ); /* RESTRICT */
   111590       testcase( i==111 ); /* OUTER */
   111591       testcase( i==112 ); /* RIGHT */
   111592       testcase( i==113 ); /* ROLLBACK */
   111593       testcase( i==114 ); /* ROW */
   111594       testcase( i==115 ); /* UNION */
   111595       testcase( i==116 ); /* USING */
   111596       testcase( i==117 ); /* VACUUM */
   111597       testcase( i==118 ); /* VIEW */
   111598       testcase( i==119 ); /* INITIALLY */
   111599       testcase( i==120 ); /* ALL */
   111600       return aCode[i];
   111601     }
   111602   }
   111603   return TK_ID;
   111604 }
   111605 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   111606   return keywordCode((char*)z, n);
   111607 }
   111608 #define SQLITE_N_KEYWORD 121
   111609 
   111610 /************** End of keywordhash.h *****************************************/
   111611 /************** Continuing where we left off in tokenize.c *******************/
   111612 
   111613 
   111614 /*
   111615 ** If X is a character that can be used in an identifier then
   111616 ** IdChar(X) will be true.  Otherwise it is false.
   111617 **
   111618 ** For ASCII, any character with the high-order bit set is
   111619 ** allowed in an identifier.  For 7-bit characters,
   111620 ** sqlite3IsIdChar[X] must be 1.
   111621 **
   111622 ** For EBCDIC, the rules are more complex but have the same
   111623 ** end result.
   111624 **
   111625 ** Ticket #1066.  the SQL standard does not allow '$' in the
   111626 ** middle of identfiers.  But many SQL implementations do.
   111627 ** SQLite will allow '$' in identifiers for compatibility.
   111628 ** But the feature is undocumented.
   111629 */
   111630 #ifdef SQLITE_ASCII
   111631 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   111632 #endif
   111633 #ifdef SQLITE_EBCDIC
   111634 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   111635 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   111636     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   111637     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   111638     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   111639     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   111640     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   111641     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   111642     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   111643     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   111644     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   111645     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   111646     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   111647     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   111648 };
   111649 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   111650 #endif
   111651 
   111652 
   111653 /*
   111654 ** Return the length of the token that begins at z[0].
   111655 ** Store the token type in *tokenType before returning.
   111656 */
   111657 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   111658   int i, c;
   111659   switch( *z ){
   111660     case ' ': case '\t': case '\n': case '\f': case '\r': {
   111661       testcase( z[0]==' ' );
   111662       testcase( z[0]=='\t' );
   111663       testcase( z[0]=='\n' );
   111664       testcase( z[0]=='\f' );
   111665       testcase( z[0]=='\r' );
   111666       for(i=1; sqlite3Isspace(z[i]); i++){}
   111667       *tokenType = TK_SPACE;
   111668       return i;
   111669     }
   111670     case '-': {
   111671       if( z[1]=='-' ){
   111672         /* IMP: R-50417-27976 -- syntax diagram for comments */
   111673         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   111674         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   111675         return i;
   111676       }
   111677       *tokenType = TK_MINUS;
   111678       return 1;
   111679     }
   111680     case '(': {
   111681       *tokenType = TK_LP;
   111682       return 1;
   111683     }
   111684     case ')': {
   111685       *tokenType = TK_RP;
   111686       return 1;
   111687     }
   111688     case ';': {
   111689       *tokenType = TK_SEMI;
   111690       return 1;
   111691     }
   111692     case '+': {
   111693       *tokenType = TK_PLUS;
   111694       return 1;
   111695     }
   111696     case '*': {
   111697       *tokenType = TK_STAR;
   111698       return 1;
   111699     }
   111700     case '/': {
   111701       if( z[1]!='*' || z[2]==0 ){
   111702         *tokenType = TK_SLASH;
   111703         return 1;
   111704       }
   111705       /* IMP: R-50417-27976 -- syntax diagram for comments */
   111706       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   111707       if( c ) i++;
   111708       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   111709       return i;
   111710     }
   111711     case '%': {
   111712       *tokenType = TK_REM;
   111713       return 1;
   111714     }
   111715     case '=': {
   111716       *tokenType = TK_EQ;
   111717       return 1 + (z[1]=='=');
   111718     }
   111719     case '<': {
   111720       if( (c=z[1])=='=' ){
   111721         *tokenType = TK_LE;
   111722         return 2;
   111723       }else if( c=='>' ){
   111724         *tokenType = TK_NE;
   111725         return 2;
   111726       }else if( c=='<' ){
   111727         *tokenType = TK_LSHIFT;
   111728         return 2;
   111729       }else{
   111730         *tokenType = TK_LT;
   111731         return 1;
   111732       }
   111733     }
   111734     case '>': {
   111735       if( (c=z[1])=='=' ){
   111736         *tokenType = TK_GE;
   111737         return 2;
   111738       }else if( c=='>' ){
   111739         *tokenType = TK_RSHIFT;
   111740         return 2;
   111741       }else{
   111742         *tokenType = TK_GT;
   111743         return 1;
   111744       }
   111745     }
   111746     case '!': {
   111747       if( z[1]!='=' ){
   111748         *tokenType = TK_ILLEGAL;
   111749         return 2;
   111750       }else{
   111751         *tokenType = TK_NE;
   111752         return 2;
   111753       }
   111754     }
   111755     case '|': {
   111756       if( z[1]!='|' ){
   111757         *tokenType = TK_BITOR;
   111758         return 1;
   111759       }else{
   111760         *tokenType = TK_CONCAT;
   111761         return 2;
   111762       }
   111763     }
   111764     case ',': {
   111765       *tokenType = TK_COMMA;
   111766       return 1;
   111767     }
   111768     case '&': {
   111769       *tokenType = TK_BITAND;
   111770       return 1;
   111771     }
   111772     case '~': {
   111773       *tokenType = TK_BITNOT;
   111774       return 1;
   111775     }
   111776     case '`':
   111777     case '\'':
   111778     case '"': {
   111779       int delim = z[0];
   111780       testcase( delim=='`' );
   111781       testcase( delim=='\'' );
   111782       testcase( delim=='"' );
   111783       for(i=1; (c=z[i])!=0; i++){
   111784         if( c==delim ){
   111785           if( z[i+1]==delim ){
   111786             i++;
   111787           }else{
   111788             break;
   111789           }
   111790         }
   111791       }
   111792       if( c=='\'' ){
   111793         *tokenType = TK_STRING;
   111794         return i+1;
   111795       }else if( c!=0 ){
   111796         *tokenType = TK_ID;
   111797         return i+1;
   111798       }else{
   111799         *tokenType = TK_ILLEGAL;
   111800         return i;
   111801       }
   111802     }
   111803     case '.': {
   111804 #ifndef SQLITE_OMIT_FLOATING_POINT
   111805       if( !sqlite3Isdigit(z[1]) )
   111806 #endif
   111807       {
   111808         *tokenType = TK_DOT;
   111809         return 1;
   111810       }
   111811       /* If the next character is a digit, this is a floating point
   111812       ** number that begins with ".".  Fall thru into the next case */
   111813     }
   111814     case '0': case '1': case '2': case '3': case '4':
   111815     case '5': case '6': case '7': case '8': case '9': {
   111816       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   111817       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   111818       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   111819       testcase( z[0]=='9' );
   111820       *tokenType = TK_INTEGER;
   111821       for(i=0; sqlite3Isdigit(z[i]); i++){}
   111822 #ifndef SQLITE_OMIT_FLOATING_POINT
   111823       if( z[i]=='.' ){
   111824         i++;
   111825         while( sqlite3Isdigit(z[i]) ){ i++; }
   111826         *tokenType = TK_FLOAT;
   111827       }
   111828       if( (z[i]=='e' || z[i]=='E') &&
   111829            ( sqlite3Isdigit(z[i+1])
   111830             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   111831            )
   111832       ){
   111833         i += 2;
   111834         while( sqlite3Isdigit(z[i]) ){ i++; }
   111835         *tokenType = TK_FLOAT;
   111836       }
   111837 #endif
   111838       while( IdChar(z[i]) ){
   111839         *tokenType = TK_ILLEGAL;
   111840         i++;
   111841       }
   111842       return i;
   111843     }
   111844     case '[': {
   111845       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   111846       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   111847       return i;
   111848     }
   111849     case '?': {
   111850       *tokenType = TK_VARIABLE;
   111851       for(i=1; sqlite3Isdigit(z[i]); i++){}
   111852       return i;
   111853     }
   111854     case '#': {
   111855       for(i=1; sqlite3Isdigit(z[i]); i++){}
   111856       if( i>1 ){
   111857         /* Parameters of the form #NNN (where NNN is a number) are used
   111858         ** internally by sqlite3NestedParse.  */
   111859         *tokenType = TK_REGISTER;
   111860         return i;
   111861       }
   111862       /* Fall through into the next case if the '#' is not followed by
   111863       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
   111864     }
   111865 #ifndef SQLITE_OMIT_TCL_VARIABLE
   111866     case '$':
   111867 #endif
   111868     case '@':  /* For compatibility with MS SQL Server */
   111869     case ':': {
   111870       int n = 0;
   111871       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
   111872       *tokenType = TK_VARIABLE;
   111873       for(i=1; (c=z[i])!=0; i++){
   111874         if( IdChar(c) ){
   111875           n++;
   111876 #ifndef SQLITE_OMIT_TCL_VARIABLE
   111877         }else if( c=='(' && n>0 ){
   111878           do{
   111879             i++;
   111880           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   111881           if( c==')' ){
   111882             i++;
   111883           }else{
   111884             *tokenType = TK_ILLEGAL;
   111885           }
   111886           break;
   111887         }else if( c==':' && z[i+1]==':' ){
   111888           i++;
   111889 #endif
   111890         }else{
   111891           break;
   111892         }
   111893       }
   111894       if( n==0 ) *tokenType = TK_ILLEGAL;
   111895       return i;
   111896     }
   111897 #ifndef SQLITE_OMIT_BLOB_LITERAL
   111898     case 'x': case 'X': {
   111899       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   111900       if( z[1]=='\'' ){
   111901         *tokenType = TK_BLOB;
   111902         for(i=2; sqlite3Isxdigit(z[i]); i++){}
   111903         if( z[i]!='\'' || i%2 ){
   111904           *tokenType = TK_ILLEGAL;
   111905           while( z[i] && z[i]!='\'' ){ i++; }
   111906         }
   111907         if( z[i] ) i++;
   111908         return i;
   111909       }
   111910       /* Otherwise fall through to the next case */
   111911     }
   111912 #endif
   111913     default: {
   111914       if( !IdChar(*z) ){
   111915         break;
   111916       }
   111917       for(i=1; IdChar(z[i]); i++){}
   111918       *tokenType = keywordCode((char*)z, i);
   111919       return i;
   111920     }
   111921   }
   111922   *tokenType = TK_ILLEGAL;
   111923   return 1;
   111924 }
   111925 
   111926 /*
   111927 ** Run the parser on the given SQL string.  The parser structure is
   111928 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   111929 ** then an and attempt is made to write an error message into
   111930 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   111931 ** error message.
   111932 */
   111933 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   111934   int nErr = 0;                   /* Number of errors encountered */
   111935   int i;                          /* Loop counter */
   111936   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   111937   int tokenType;                  /* type of the next token */
   111938   int lastTokenParsed = -1;       /* type of the previous token */
   111939   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   111940   sqlite3 *db = pParse->db;       /* The database connection */
   111941   int mxSqlLen;                   /* Max length of an SQL string */
   111942 
   111943 
   111944   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   111945   if( db->activeVdbeCnt==0 ){
   111946     db->u1.isInterrupted = 0;
   111947   }
   111948   pParse->rc = SQLITE_OK;
   111949   pParse->zTail = zSql;
   111950   i = 0;
   111951   assert( pzErrMsg!=0 );
   111952   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   111953   if( pEngine==0 ){
   111954     db->mallocFailed = 1;
   111955     return SQLITE_NOMEM;
   111956   }
   111957   assert( pParse->pNewTable==0 );
   111958   assert( pParse->pNewTrigger==0 );
   111959   assert( pParse->nVar==0 );
   111960   assert( pParse->nzVar==0 );
   111961   assert( pParse->azVar==0 );
   111962   enableLookaside = db->lookaside.bEnabled;
   111963   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   111964   while( !db->mallocFailed && zSql[i]!=0 ){
   111965     assert( i>=0 );
   111966     pParse->sLastToken.z = &zSql[i];
   111967     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   111968     i += pParse->sLastToken.n;
   111969     if( i>mxSqlLen ){
   111970       pParse->rc = SQLITE_TOOBIG;
   111971       break;
   111972     }
   111973     switch( tokenType ){
   111974       case TK_SPACE: {
   111975         if( db->u1.isInterrupted ){
   111976           sqlite3ErrorMsg(pParse, "interrupt");
   111977           pParse->rc = SQLITE_INTERRUPT;
   111978           goto abort_parse;
   111979         }
   111980         break;
   111981       }
   111982       case TK_ILLEGAL: {
   111983         sqlite3DbFree(db, *pzErrMsg);
   111984         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   111985                         &pParse->sLastToken);
   111986         nErr++;
   111987         goto abort_parse;
   111988       }
   111989       case TK_SEMI: {
   111990         pParse->zTail = &zSql[i];
   111991         /* Fall thru into the default case */
   111992       }
   111993       default: {
   111994         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   111995         lastTokenParsed = tokenType;
   111996         if( pParse->rc!=SQLITE_OK ){
   111997           goto abort_parse;
   111998         }
   111999         break;
   112000       }
   112001     }
   112002   }
   112003 abort_parse:
   112004   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   112005     if( lastTokenParsed!=TK_SEMI ){
   112006       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   112007       pParse->zTail = &zSql[i];
   112008     }
   112009     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   112010   }
   112011 #ifdef YYTRACKMAXSTACKDEPTH
   112012   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   112013       sqlite3ParserStackPeak(pEngine)
   112014   );
   112015 #endif /* YYDEBUG */
   112016   sqlite3ParserFree(pEngine, sqlite3_free);
   112017   db->lookaside.bEnabled = enableLookaside;
   112018   if( db->mallocFailed ){
   112019     pParse->rc = SQLITE_NOMEM;
   112020   }
   112021   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   112022     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   112023   }
   112024   assert( pzErrMsg!=0 );
   112025   if( pParse->zErrMsg ){
   112026     *pzErrMsg = pParse->zErrMsg;
   112027     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   112028     pParse->zErrMsg = 0;
   112029     nErr++;
   112030   }
   112031   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   112032     sqlite3VdbeDelete(pParse->pVdbe);
   112033     pParse->pVdbe = 0;
   112034   }
   112035 #ifndef SQLITE_OMIT_SHARED_CACHE
   112036   if( pParse->nested==0 ){
   112037     sqlite3DbFree(db, pParse->aTableLock);
   112038     pParse->aTableLock = 0;
   112039     pParse->nTableLock = 0;
   112040   }
   112041 #endif
   112042 #ifndef SQLITE_OMIT_VIRTUALTABLE
   112043   sqlite3_free(pParse->apVtabLock);
   112044 #endif
   112045 
   112046   if( !IN_DECLARE_VTAB ){
   112047     /* If the pParse->declareVtab flag is set, do not delete any table
   112048     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   112049     ** will take responsibility for freeing the Table structure.
   112050     */
   112051     sqlite3DeleteTable(db, pParse->pNewTable);
   112052   }
   112053 
   112054   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   112055   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
   112056   sqlite3DbFree(db, pParse->azVar);
   112057   sqlite3DbFree(db, pParse->aAlias);
   112058   while( pParse->pAinc ){
   112059     AutoincInfo *p = pParse->pAinc;
   112060     pParse->pAinc = p->pNext;
   112061     sqlite3DbFree(db, p);
   112062   }
   112063   while( pParse->pZombieTab ){
   112064     Table *p = pParse->pZombieTab;
   112065     pParse->pZombieTab = p->pNextZombie;
   112066     sqlite3DeleteTable(db, p);
   112067   }
   112068   if( nErr>0 && pParse->rc==SQLITE_OK ){
   112069     pParse->rc = SQLITE_ERROR;
   112070   }
   112071   return nErr;
   112072 }
   112073 
   112074 /************** End of tokenize.c ********************************************/
   112075 /************** Begin file complete.c ****************************************/
   112076 /*
   112077 ** 2001 September 15
   112078 **
   112079 ** The author disclaims copyright to this source code.  In place of
   112080 ** a legal notice, here is a blessing:
   112081 **
   112082 **    May you do good and not evil.
   112083 **    May you find forgiveness for yourself and forgive others.
   112084 **    May you share freely, never taking more than you give.
   112085 **
   112086 *************************************************************************
   112087 ** An tokenizer for SQL
   112088 **
   112089 ** This file contains C code that implements the sqlite3_complete() API.
   112090 ** This code used to be part of the tokenizer.c source file.  But by
   112091 ** separating it out, the code will be automatically omitted from
   112092 ** static links that do not use it.
   112093 */
   112094 #ifndef SQLITE_OMIT_COMPLETE
   112095 
   112096 /*
   112097 ** This is defined in tokenize.c.  We just have to import the definition.
   112098 */
   112099 #ifndef SQLITE_AMALGAMATION
   112100 #ifdef SQLITE_ASCII
   112101 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   112102 #endif
   112103 #ifdef SQLITE_EBCDIC
   112104 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   112105 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   112106 #endif
   112107 #endif /* SQLITE_AMALGAMATION */
   112108 
   112109 
   112110 /*
   112111 ** Token types used by the sqlite3_complete() routine.  See the header
   112112 ** comments on that procedure for additional information.
   112113 */
   112114 #define tkSEMI    0
   112115 #define tkWS      1
   112116 #define tkOTHER   2
   112117 #ifndef SQLITE_OMIT_TRIGGER
   112118 #define tkEXPLAIN 3
   112119 #define tkCREATE  4
   112120 #define tkTEMP    5
   112121 #define tkTRIGGER 6
   112122 #define tkEND     7
   112123 #endif
   112124 
   112125 /*
   112126 ** Return TRUE if the given SQL string ends in a semicolon.
   112127 **
   112128 ** Special handling is require for CREATE TRIGGER statements.
   112129 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   112130 ** must end with ";END;".
   112131 **
   112132 ** This implementation uses a state machine with 8 states:
   112133 **
   112134 **   (0) INVALID   We have not yet seen a non-whitespace character.
   112135 **
   112136 **   (1) START     At the beginning or end of an SQL statement.  This routine
   112137 **                 returns 1 if it ends in the START state and 0 if it ends
   112138 **                 in any other state.
   112139 **
   112140 **   (2) NORMAL    We are in the middle of statement which ends with a single
   112141 **                 semicolon.
   112142 **
   112143 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   112144 **                 a statement.
   112145 **
   112146 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   112147 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   112148 **                 TEMP or TEMPORARY
   112149 **
   112150 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   112151 **                 ended by a semicolon, the keyword END, and another semicolon.
   112152 **
   112153 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   112154 **                 the end of a trigger definition.
   112155 **
   112156 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   112157 **                 of a trigger difinition.
   112158 **
   112159 ** Transitions between states above are determined by tokens extracted
   112160 ** from the input.  The following tokens are significant:
   112161 **
   112162 **   (0) tkSEMI      A semicolon.
   112163 **   (1) tkWS        Whitespace.
   112164 **   (2) tkOTHER     Any other SQL token.
   112165 **   (3) tkEXPLAIN   The "explain" keyword.
   112166 **   (4) tkCREATE    The "create" keyword.
   112167 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   112168 **   (6) tkTRIGGER   The "trigger" keyword.
   112169 **   (7) tkEND       The "end" keyword.
   112170 **
   112171 ** Whitespace never causes a state transition and is always ignored.
   112172 ** This means that a SQL string of all whitespace is invalid.
   112173 **
   112174 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   112175 ** to recognize the end of a trigger can be omitted.  All we have to do
   112176 ** is look for a semicolon that is not part of an string or comment.
   112177 */
   112178 SQLITE_API int sqlite3_complete(const char *zSql){
   112179   u8 state = 0;   /* Current state, using numbers defined in header comment */
   112180   u8 token;       /* Value of the next token */
   112181 
   112182 #ifndef SQLITE_OMIT_TRIGGER
   112183   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   112184   ** statement.  This is the normal case.
   112185   */
   112186   static const u8 trans[8][8] = {
   112187                      /* Token:                                                */
   112188      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   112189      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   112190      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   112191      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   112192      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   112193      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   112194      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   112195      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   112196      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   112197   };
   112198 #else
   112199   /* If triggers are not supported by this compile then the statement machine
   112200   ** used to detect the end of a statement is much simplier
   112201   */
   112202   static const u8 trans[3][3] = {
   112203                      /* Token:           */
   112204      /* State:       **  SEMI  WS  OTHER */
   112205      /* 0 INVALID: */ {    1,  0,     2, },
   112206      /* 1   START: */ {    1,  1,     2, },
   112207      /* 2  NORMAL: */ {    1,  2,     2, },
   112208   };
   112209 #endif /* SQLITE_OMIT_TRIGGER */
   112210 
   112211   while( *zSql ){
   112212     switch( *zSql ){
   112213       case ';': {  /* A semicolon */
   112214         token = tkSEMI;
   112215         break;
   112216       }
   112217       case ' ':
   112218       case '\r':
   112219       case '\t':
   112220       case '\n':
   112221       case '\f': {  /* White space is ignored */
   112222         token = tkWS;
   112223         break;
   112224       }
   112225       case '/': {   /* C-style comments */
   112226         if( zSql[1]!='*' ){
   112227           token = tkOTHER;
   112228           break;
   112229         }
   112230         zSql += 2;
   112231         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   112232         if( zSql[0]==0 ) return 0;
   112233         zSql++;
   112234         token = tkWS;
   112235         break;
   112236       }
   112237       case '-': {   /* SQL-style comments from "--" to end of line */
   112238         if( zSql[1]!='-' ){
   112239           token = tkOTHER;
   112240           break;
   112241         }
   112242         while( *zSql && *zSql!='\n' ){ zSql++; }
   112243         if( *zSql==0 ) return state==1;
   112244         token = tkWS;
   112245         break;
   112246       }
   112247       case '[': {   /* Microsoft-style identifiers in [...] */
   112248         zSql++;
   112249         while( *zSql && *zSql!=']' ){ zSql++; }
   112250         if( *zSql==0 ) return 0;
   112251         token = tkOTHER;
   112252         break;
   112253       }
   112254       case '`':     /* Grave-accent quoted symbols used by MySQL */
   112255       case '"':     /* single- and double-quoted strings */
   112256       case '\'': {
   112257         int c = *zSql;
   112258         zSql++;
   112259         while( *zSql && *zSql!=c ){ zSql++; }
   112260         if( *zSql==0 ) return 0;
   112261         token = tkOTHER;
   112262         break;
   112263       }
   112264       default: {
   112265 #ifdef SQLITE_EBCDIC
   112266         unsigned char c;
   112267 #endif
   112268         if( IdChar((u8)*zSql) ){
   112269           /* Keywords and unquoted identifiers */
   112270           int nId;
   112271           for(nId=1; IdChar(zSql[nId]); nId++){}
   112272 #ifdef SQLITE_OMIT_TRIGGER
   112273           token = tkOTHER;
   112274 #else
   112275           switch( *zSql ){
   112276             case 'c': case 'C': {
   112277               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   112278                 token = tkCREATE;
   112279               }else{
   112280                 token = tkOTHER;
   112281               }
   112282               break;
   112283             }
   112284             case 't': case 'T': {
   112285               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   112286                 token = tkTRIGGER;
   112287               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   112288                 token = tkTEMP;
   112289               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   112290                 token = tkTEMP;
   112291               }else{
   112292                 token = tkOTHER;
   112293               }
   112294               break;
   112295             }
   112296             case 'e':  case 'E': {
   112297               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   112298                 token = tkEND;
   112299               }else
   112300 #ifndef SQLITE_OMIT_EXPLAIN
   112301               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   112302                 token = tkEXPLAIN;
   112303               }else
   112304 #endif
   112305               {
   112306                 token = tkOTHER;
   112307               }
   112308               break;
   112309             }
   112310             default: {
   112311               token = tkOTHER;
   112312               break;
   112313             }
   112314           }
   112315 #endif /* SQLITE_OMIT_TRIGGER */
   112316           zSql += nId-1;
   112317         }else{
   112318           /* Operators and special symbols */
   112319           token = tkOTHER;
   112320         }
   112321         break;
   112322       }
   112323     }
   112324     state = trans[state][token];
   112325     zSql++;
   112326   }
   112327   return state==1;
   112328 }
   112329 
   112330 #ifndef SQLITE_OMIT_UTF16
   112331 /*
   112332 ** This routine is the same as the sqlite3_complete() routine described
   112333 ** above, except that the parameter is required to be UTF-16 encoded, not
   112334 ** UTF-8.
   112335 */
   112336 SQLITE_API int sqlite3_complete16(const void *zSql){
   112337   sqlite3_value *pVal;
   112338   char const *zSql8;
   112339   int rc = SQLITE_NOMEM;
   112340 
   112341 #ifndef SQLITE_OMIT_AUTOINIT
   112342   rc = sqlite3_initialize();
   112343   if( rc ) return rc;
   112344 #endif
   112345   pVal = sqlite3ValueNew(0);
   112346   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   112347   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   112348   if( zSql8 ){
   112349     rc = sqlite3_complete(zSql8);
   112350   }else{
   112351     rc = SQLITE_NOMEM;
   112352   }
   112353   sqlite3ValueFree(pVal);
   112354   return sqlite3ApiExit(0, rc);
   112355 }
   112356 #endif /* SQLITE_OMIT_UTF16 */
   112357 #endif /* SQLITE_OMIT_COMPLETE */
   112358 
   112359 /************** End of complete.c ********************************************/
   112360 /************** Begin file main.c ********************************************/
   112361 /*
   112362 ** 2001 September 15
   112363 **
   112364 ** The author disclaims copyright to this source code.  In place of
   112365 ** a legal notice, here is a blessing:
   112366 **
   112367 **    May you do good and not evil.
   112368 **    May you find forgiveness for yourself and forgive others.
   112369 **    May you share freely, never taking more than you give.
   112370 **
   112371 *************************************************************************
   112372 ** Main file for the SQLite library.  The routines in this file
   112373 ** implement the programmer interface to the library.  Routines in
   112374 ** other files are for internal use by SQLite and should not be
   112375 ** accessed by users of the library.
   112376 */
   112377 
   112378 #ifdef SQLITE_ENABLE_FTS3
   112379 /************** Include fts3.h in the middle of main.c ***********************/
   112380 /************** Begin file fts3.h ********************************************/
   112381 /*
   112382 ** 2006 Oct 10
   112383 **
   112384 ** The author disclaims copyright to this source code.  In place of
   112385 ** a legal notice, here is a blessing:
   112386 **
   112387 **    May you do good and not evil.
   112388 **    May you find forgiveness for yourself and forgive others.
   112389 **    May you share freely, never taking more than you give.
   112390 **
   112391 ******************************************************************************
   112392 **
   112393 ** This header file is used by programs that want to link against the
   112394 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   112395 */
   112396 
   112397 #if 0
   112398 extern "C" {
   112399 #endif  /* __cplusplus */
   112400 
   112401 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs); // Android Change
   112402 
   112403 #if 0
   112404 }  /* extern "C" */
   112405 #endif  /* __cplusplus */
   112406 
   112407 /************** End of fts3.h ************************************************/
   112408 /************** Continuing where we left off in main.c ***********************/
   112409 #endif
   112410 #ifdef SQLITE_ENABLE_RTREE
   112411 /************** Include rtree.h in the middle of main.c **********************/
   112412 /************** Begin file rtree.h *******************************************/
   112413 /*
   112414 ** 2008 May 26
   112415 **
   112416 ** The author disclaims copyright to this source code.  In place of
   112417 ** a legal notice, here is a blessing:
   112418 **
   112419 **    May you do good and not evil.
   112420 **    May you find forgiveness for yourself and forgive others.
   112421 **    May you share freely, never taking more than you give.
   112422 **
   112423 ******************************************************************************
   112424 **
   112425 ** This header file is used by programs that want to link against the
   112426 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   112427 */
   112428 
   112429 #if 0
   112430 extern "C" {
   112431 #endif  /* __cplusplus */
   112432 
   112433 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   112434 
   112435 #if 0
   112436 }  /* extern "C" */
   112437 #endif  /* __cplusplus */
   112438 
   112439 /************** End of rtree.h ***********************************************/
   112440 /************** Continuing where we left off in main.c ***********************/
   112441 #endif
   112442 #ifdef SQLITE_ENABLE_ICU
   112443 /************** Include sqliteicu.h in the middle of main.c ******************/
   112444 /************** Begin file sqliteicu.h ***************************************/
   112445 /*
   112446 ** 2008 May 26
   112447 **
   112448 ** The author disclaims copyright to this source code.  In place of
   112449 ** a legal notice, here is a blessing:
   112450 **
   112451 **    May you do good and not evil.
   112452 **    May you find forgiveness for yourself and forgive others.
   112453 **    May you share freely, never taking more than you give.
   112454 **
   112455 ******************************************************************************
   112456 **
   112457 ** This header file is used by programs that want to link against the
   112458 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   112459 */
   112460 
   112461 #if 0
   112462 extern "C" {
   112463 #endif  /* __cplusplus */
   112464 
   112465 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   112466 
   112467 #if 0
   112468 }  /* extern "C" */
   112469 #endif  /* __cplusplus */
   112470 
   112471 
   112472 /************** End of sqliteicu.h *******************************************/
   112473 /************** Continuing where we left off in main.c ***********************/
   112474 #endif
   112475 
   112476 #ifndef SQLITE_AMALGAMATION
   112477 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   112478 ** contains the text of SQLITE_VERSION macro.
   112479 */
   112480 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   112481 #endif
   112482 
   112483 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   112484 ** a pointer to the to the sqlite3_version[] string constant.
   112485 */
   112486 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   112487 
   112488 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
   112489 ** pointer to a string constant whose value is the same as the
   112490 ** SQLITE_SOURCE_ID C preprocessor macro.
   112491 */
   112492 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   112493 
   112494 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   112495 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   112496 */
   112497 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   112498 
   112499 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
   112500 ** zero if and only if SQLite was compiled with mutexing code omitted due to
   112501 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   112502 */
   112503 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   112504 
   112505 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   112506 /*
   112507 ** If the following function pointer is not NULL and if
   112508 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   112509 ** I/O active are written using this function.  These messages
   112510 ** are intended for debugging activity only.
   112511 */
   112512 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   112513 #endif
   112514 
   112515 /*
   112516 ** If the following global variable points to a string which is the
   112517 ** name of a directory, then that directory will be used to store
   112518 ** temporary files.
   112519 **
   112520 ** See also the "PRAGMA temp_store_directory" SQL command.
   112521 */
   112522 SQLITE_API char *sqlite3_temp_directory = 0;
   112523 
   112524 /*
   112525 ** Initialize SQLite.
   112526 **
   112527 ** This routine must be called to initialize the memory allocation,
   112528 ** VFS, and mutex subsystems prior to doing any serious work with
   112529 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   112530 ** this routine will be called automatically by key routines such as
   112531 ** sqlite3_open().
   112532 **
   112533 ** This routine is a no-op except on its very first call for the process,
   112534 ** or for the first call after a call to sqlite3_shutdown.
   112535 **
   112536 ** The first thread to call this routine runs the initialization to
   112537 ** completion.  If subsequent threads call this routine before the first
   112538 ** thread has finished the initialization process, then the subsequent
   112539 ** threads must block until the first thread finishes with the initialization.
   112540 **
   112541 ** The first thread might call this routine recursively.  Recursive
   112542 ** calls to this routine should not block, of course.  Otherwise the
   112543 ** initialization process would never complete.
   112544 **
   112545 ** Let X be the first thread to enter this routine.  Let Y be some other
   112546 ** thread.  Then while the initial invocation of this routine by X is
   112547 ** incomplete, it is required that:
   112548 **
   112549 **    *  Calls to this routine from Y must block until the outer-most
   112550 **       call by X completes.
   112551 **
   112552 **    *  Recursive calls to this routine from thread X return immediately
   112553 **       without blocking.
   112554 */
   112555 SQLITE_API int sqlite3_initialize(void){
   112556   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
   112557   int rc;                                      /* Result code */
   112558 
   112559 #ifdef SQLITE_OMIT_WSD
   112560   rc = sqlite3_wsd_init(4096, 24);
   112561   if( rc!=SQLITE_OK ){
   112562     return rc;
   112563   }
   112564 #endif
   112565 
   112566   /* If SQLite is already completely initialized, then this call
   112567   ** to sqlite3_initialize() should be a no-op.  But the initialization
   112568   ** must be complete.  So isInit must not be set until the very end
   112569   ** of this routine.
   112570   */
   112571   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   112572 
   112573   /* Make sure the mutex subsystem is initialized.  If unable to
   112574   ** initialize the mutex subsystem, return early with the error.
   112575   ** If the system is so sick that we are unable to allocate a mutex,
   112576   ** there is not much SQLite is going to be able to do.
   112577   **
   112578   ** The mutex subsystem must take care of serializing its own
   112579   ** initialization.
   112580   */
   112581   rc = sqlite3MutexInit();
   112582   if( rc ) return rc;
   112583 
   112584   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   112585   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   112586   ** MutexAlloc() is called for a static mutex prior to initializing the
   112587   ** malloc subsystem - this implies that the allocation of a static
   112588   ** mutex must not require support from the malloc subsystem.
   112589   */
   112590   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
   112591   sqlite3_mutex_enter(pMaster);
   112592   sqlite3GlobalConfig.isMutexInit = 1;
   112593   if( !sqlite3GlobalConfig.isMallocInit ){
   112594     rc = sqlite3MallocInit();
   112595   }
   112596   if( rc==SQLITE_OK ){
   112597     sqlite3GlobalConfig.isMallocInit = 1;
   112598     if( !sqlite3GlobalConfig.pInitMutex ){
   112599       sqlite3GlobalConfig.pInitMutex =
   112600            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   112601       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   112602         rc = SQLITE_NOMEM;
   112603       }
   112604     }
   112605   }
   112606   if( rc==SQLITE_OK ){
   112607     sqlite3GlobalConfig.nRefInitMutex++;
   112608   }
   112609   sqlite3_mutex_leave(pMaster);
   112610 
   112611   /* If rc is not SQLITE_OK at this point, then either the malloc
   112612   ** subsystem could not be initialized or the system failed to allocate
   112613   ** the pInitMutex mutex. Return an error in either case.  */
   112614   if( rc!=SQLITE_OK ){
   112615     return rc;
   112616   }
   112617 
   112618   /* Do the rest of the initialization under the recursive mutex so
   112619   ** that we will be able to handle recursive calls into
   112620   ** sqlite3_initialize().  The recursive calls normally come through
   112621   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   112622   ** recursive calls might also be possible.
   112623   **
   112624   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   112625   ** to the xInit method, so the xInit method need not be threadsafe.
   112626   **
   112627   ** The following mutex is what serializes access to the appdef pcache xInit
   112628   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   112629   ** call to sqlite3PcacheInitialize().
   112630   */
   112631   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   112632   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   112633     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   112634     sqlite3GlobalConfig.inProgress = 1;
   112635     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   112636     sqlite3RegisterGlobalFunctions();
   112637     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   112638       rc = sqlite3PcacheInitialize();
   112639     }
   112640     if( rc==SQLITE_OK ){
   112641       sqlite3GlobalConfig.isPCacheInit = 1;
   112642       rc = sqlite3OsInit();
   112643     }
   112644     if( rc==SQLITE_OK ){
   112645       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   112646           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   112647       sqlite3GlobalConfig.isInit = 1;
   112648     }
   112649     sqlite3GlobalConfig.inProgress = 0;
   112650   }
   112651   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   112652 
   112653   /* Go back under the static mutex and clean up the recursive
   112654   ** mutex to prevent a resource leak.
   112655   */
   112656   sqlite3_mutex_enter(pMaster);
   112657   sqlite3GlobalConfig.nRefInitMutex--;
   112658   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   112659     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   112660     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   112661     sqlite3GlobalConfig.pInitMutex = 0;
   112662   }
   112663   sqlite3_mutex_leave(pMaster);
   112664 
   112665   /* The following is just a sanity check to make sure SQLite has
   112666   ** been compiled correctly.  It is important to run this code, but
   112667   ** we don't want to run it too often and soak up CPU cycles for no
   112668   ** reason.  So we run it once during initialization.
   112669   */
   112670 #ifndef NDEBUG
   112671 #ifndef SQLITE_OMIT_FLOATING_POINT
   112672   /* This section of code's only "output" is via assert() statements. */
   112673   if ( rc==SQLITE_OK ){
   112674     u64 x = (((u64)1)<<63)-1;
   112675     double y;
   112676     assert(sizeof(x)==8);
   112677     assert(sizeof(x)==sizeof(y));
   112678     memcpy(&y, &x, 8);
   112679     assert( sqlite3IsNaN(y) );
   112680   }
   112681 #endif
   112682 #endif
   112683 
   112684   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   112685   ** compile-time option.
   112686   */
   112687 #ifdef SQLITE_EXTRA_INIT
   112688   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
   112689     int SQLITE_EXTRA_INIT(const char*);
   112690     rc = SQLITE_EXTRA_INIT(0);
   112691   }
   112692 #endif
   112693 
   112694   return rc;
   112695 }
   112696 
   112697 /*
   112698 ** Undo the effects of sqlite3_initialize().  Must not be called while
   112699 ** there are outstanding database connections or memory allocations or
   112700 ** while any part of SQLite is otherwise in use in any thread.  This
   112701 ** routine is not threadsafe.  But it is safe to invoke this routine
   112702 ** on when SQLite is already shut down.  If SQLite is already shut down
   112703 ** when this routine is invoked, then this routine is a harmless no-op.
   112704 */
   112705 SQLITE_API int sqlite3_shutdown(void){
   112706   if( sqlite3GlobalConfig.isInit ){
   112707 #ifdef SQLITE_EXTRA_SHUTDOWN
   112708     void SQLITE_EXTRA_SHUTDOWN(void);
   112709     SQLITE_EXTRA_SHUTDOWN();
   112710 #endif
   112711     sqlite3_os_end();
   112712     sqlite3_reset_auto_extension();
   112713     sqlite3GlobalConfig.isInit = 0;
   112714   }
   112715   if( sqlite3GlobalConfig.isPCacheInit ){
   112716     sqlite3PcacheShutdown();
   112717     sqlite3GlobalConfig.isPCacheInit = 0;
   112718   }
   112719   if( sqlite3GlobalConfig.isMallocInit ){
   112720     sqlite3MallocEnd();
   112721     sqlite3GlobalConfig.isMallocInit = 0;
   112722   }
   112723   if( sqlite3GlobalConfig.isMutexInit ){
   112724     sqlite3MutexEnd();
   112725     sqlite3GlobalConfig.isMutexInit = 0;
   112726   }
   112727 
   112728   return SQLITE_OK;
   112729 }
   112730 
   112731 /*
   112732 ** This API allows applications to modify the global configuration of
   112733 ** the SQLite library at run-time.
   112734 **
   112735 ** This routine should only be called when there are no outstanding
   112736 ** database connections or memory allocations.  This routine is not
   112737 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   112738 ** behavior.
   112739 */
   112740 SQLITE_API int sqlite3_config(int op, ...){
   112741   va_list ap;
   112742   int rc = SQLITE_OK;
   112743 
   112744   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   112745   ** the SQLite library is in use. */
   112746   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   112747 
   112748   va_start(ap, op);
   112749   switch( op ){
   112750 
   112751     /* Mutex configuration options are only available in a threadsafe
   112752     ** compile.
   112753     */
   112754 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   112755     case SQLITE_CONFIG_SINGLETHREAD: {
   112756       /* Disable all mutexing */
   112757       sqlite3GlobalConfig.bCoreMutex = 0;
   112758       sqlite3GlobalConfig.bFullMutex = 0;
   112759       break;
   112760     }
   112761     case SQLITE_CONFIG_MULTITHREAD: {
   112762       /* Disable mutexing of database connections */
   112763       /* Enable mutexing of core data structures */
   112764       sqlite3GlobalConfig.bCoreMutex = 1;
   112765       sqlite3GlobalConfig.bFullMutex = 0;
   112766       break;
   112767     }
   112768     case SQLITE_CONFIG_SERIALIZED: {
   112769       /* Enable all mutexing */
   112770       sqlite3GlobalConfig.bCoreMutex = 1;
   112771       sqlite3GlobalConfig.bFullMutex = 1;
   112772       break;
   112773     }
   112774     case SQLITE_CONFIG_MUTEX: {
   112775       /* Specify an alternative mutex implementation */
   112776       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   112777       break;
   112778     }
   112779     case SQLITE_CONFIG_GETMUTEX: {
   112780       /* Retrieve the current mutex implementation */
   112781       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   112782       break;
   112783     }
   112784 #endif
   112785 
   112786 
   112787     case SQLITE_CONFIG_MALLOC: {
   112788       /* Specify an alternative malloc implementation */
   112789       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   112790       break;
   112791     }
   112792     case SQLITE_CONFIG_GETMALLOC: {
   112793       /* Retrieve the current malloc() implementation */
   112794       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   112795       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   112796       break;
   112797     }
   112798     case SQLITE_CONFIG_MEMSTATUS: {
   112799       /* Enable or disable the malloc status collection */
   112800       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   112801       break;
   112802     }
   112803     case SQLITE_CONFIG_SCRATCH: {
   112804       /* Designate a buffer for scratch memory space */
   112805       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   112806       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   112807       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   112808       break;
   112809     }
   112810     case SQLITE_CONFIG_PAGECACHE: {
   112811       /* Designate a buffer for page cache memory space */
   112812       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   112813       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   112814       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   112815       break;
   112816     }
   112817 
   112818     case SQLITE_CONFIG_PCACHE: {
   112819       /* no-op */
   112820       break;
   112821     }
   112822     case SQLITE_CONFIG_GETPCACHE: {
   112823       /* now an error */
   112824       rc = SQLITE_ERROR;
   112825       break;
   112826     }
   112827 
   112828     case SQLITE_CONFIG_PCACHE2: {
   112829       /* Specify an alternative page cache implementation */
   112830       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
   112831       break;
   112832     }
   112833     case SQLITE_CONFIG_GETPCACHE2: {
   112834       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   112835         sqlite3PCacheSetDefault();
   112836       }
   112837       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   112838       break;
   112839     }
   112840 
   112841 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   112842     case SQLITE_CONFIG_HEAP: {
   112843       /* Designate a buffer for heap memory space */
   112844       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   112845       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   112846       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   112847 
   112848       if( sqlite3GlobalConfig.mnReq<1 ){
   112849         sqlite3GlobalConfig.mnReq = 1;
   112850       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
   112851         /* cap min request size at 2^12 */
   112852         sqlite3GlobalConfig.mnReq = (1<<12);
   112853       }
   112854 
   112855       if( sqlite3GlobalConfig.pHeap==0 ){
   112856         /* If the heap pointer is NULL, then restore the malloc implementation
   112857         ** back to NULL pointers too.  This will cause the malloc to go
   112858         ** back to its default implementation when sqlite3_initialize() is
   112859         ** run.
   112860         */
   112861         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   112862       }else{
   112863         /* The heap pointer is not NULL, then install one of the
   112864         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
   112865         ** ENABLE_MEMSYS5 is defined, return an error.
   112866         */
   112867 #ifdef SQLITE_ENABLE_MEMSYS3
   112868         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   112869 #endif
   112870 #ifdef SQLITE_ENABLE_MEMSYS5
   112871         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   112872 #endif
   112873       }
   112874       break;
   112875     }
   112876 #endif
   112877 
   112878     case SQLITE_CONFIG_LOOKASIDE: {
   112879       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   112880       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   112881       break;
   112882     }
   112883 
   112884     /* Record a pointer to the logger funcction and its first argument.
   112885     ** The default is NULL.  Logging is disabled if the function pointer is
   112886     ** NULL.
   112887     */
   112888     case SQLITE_CONFIG_LOG: {
   112889       /* MSVC is picky about pulling func ptrs from va lists.
   112890       ** http://support.microsoft.com/kb/47961
   112891       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   112892       */
   112893       typedef void(*LOGFUNC_t)(void*,int,const char*);
   112894       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   112895       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   112896       break;
   112897     }
   112898 
   112899     case SQLITE_CONFIG_URI: {
   112900       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
   112901       break;
   112902     }
   112903 
   112904     default: {
   112905       rc = SQLITE_ERROR;
   112906       break;
   112907     }
   112908   }
   112909   va_end(ap);
   112910   return rc;
   112911 }
   112912 
   112913 /*
   112914 ** Set up the lookaside buffers for a database connection.
   112915 ** Return SQLITE_OK on success.
   112916 ** If lookaside is already active, return SQLITE_BUSY.
   112917 **
   112918 ** The sz parameter is the number of bytes in each lookaside slot.
   112919 ** The cnt parameter is the number of slots.  If pStart is NULL the
   112920 ** space for the lookaside memory is obtained from sqlite3_malloc().
   112921 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   112922 ** the lookaside memory.
   112923 */
   112924 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   112925   void *pStart;
   112926   if( db->lookaside.nOut ){
   112927     return SQLITE_BUSY;
   112928   }
   112929   /* Free any existing lookaside buffer for this handle before
   112930   ** allocating a new one so we don't have to have space for
   112931   ** both at the same time.
   112932   */
   112933   if( db->lookaside.bMalloced ){
   112934     sqlite3_free(db->lookaside.pStart);
   112935   }
   112936   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
   112937   ** than a pointer to be useful.
   112938   */
   112939   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   112940   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   112941   if( cnt<0 ) cnt = 0;
   112942   if( sz==0 || cnt==0 ){
   112943     sz = 0;
   112944     pStart = 0;
   112945   }else if( pBuf==0 ){
   112946     sqlite3BeginBenignMalloc();
   112947     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   112948     sqlite3EndBenignMalloc();
   112949     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   112950   }else{
   112951     pStart = pBuf;
   112952   }
   112953   db->lookaside.pStart = pStart;
   112954   db->lookaside.pFree = 0;
   112955   db->lookaside.sz = (u16)sz;
   112956   if( pStart ){
   112957     int i;
   112958     LookasideSlot *p;
   112959     assert( sz > (int)sizeof(LookasideSlot*) );
   112960     p = (LookasideSlot*)pStart;
   112961     for(i=cnt-1; i>=0; i--){
   112962       p->pNext = db->lookaside.pFree;
   112963       db->lookaside.pFree = p;
   112964       p = (LookasideSlot*)&((u8*)p)[sz];
   112965     }
   112966     db->lookaside.pEnd = p;
   112967     db->lookaside.bEnabled = 1;
   112968     db->lookaside.bMalloced = pBuf==0 ?1:0;
   112969   }else{
   112970     db->lookaside.pEnd = 0;
   112971     db->lookaside.bEnabled = 0;
   112972     db->lookaside.bMalloced = 0;
   112973   }
   112974   return SQLITE_OK;
   112975 }
   112976 
   112977 /*
   112978 ** Return the mutex associated with a database connection.
   112979 */
   112980 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   112981   return db->mutex;
   112982 }
   112983 
   112984 /*
   112985 ** Free up as much memory as we can from the given database
   112986 ** connection.
   112987 */
   112988 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
   112989   int i;
   112990   sqlite3_mutex_enter(db->mutex);
   112991   sqlite3BtreeEnterAll(db);
   112992   for(i=0; i<db->nDb; i++){
   112993     Btree *pBt = db->aDb[i].pBt;
   112994     if( pBt ){
   112995       Pager *pPager = sqlite3BtreePager(pBt);
   112996       sqlite3PagerShrink(pPager);
   112997     }
   112998   }
   112999   sqlite3BtreeLeaveAll(db);
   113000   sqlite3_mutex_leave(db->mutex);
   113001   return SQLITE_OK;
   113002 }
   113003 
   113004 /*
   113005 ** Configuration settings for an individual database connection
   113006 */
   113007 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   113008   va_list ap;
   113009   int rc;
   113010   va_start(ap, op);
   113011   switch( op ){
   113012     case SQLITE_DBCONFIG_LOOKASIDE: {
   113013       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
   113014       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   113015       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   113016       rc = setupLookaside(db, pBuf, sz, cnt);
   113017       break;
   113018     }
   113019     default: {
   113020       static const struct {
   113021         int op;      /* The opcode */
   113022         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
   113023       } aFlagOp[] = {
   113024         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
   113025         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
   113026       };
   113027       unsigned int i;
   113028       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   113029       for(i=0; i<ArraySize(aFlagOp); i++){
   113030         if( aFlagOp[i].op==op ){
   113031           int onoff = va_arg(ap, int);
   113032           int *pRes = va_arg(ap, int*);
   113033           int oldFlags = db->flags;
   113034           if( onoff>0 ){
   113035             db->flags |= aFlagOp[i].mask;
   113036           }else if( onoff==0 ){
   113037             db->flags &= ~aFlagOp[i].mask;
   113038           }
   113039           if( oldFlags!=db->flags ){
   113040             sqlite3ExpirePreparedStatements(db);
   113041           }
   113042           if( pRes ){
   113043             *pRes = (db->flags & aFlagOp[i].mask)!=0;
   113044           }
   113045           rc = SQLITE_OK;
   113046           break;
   113047         }
   113048       }
   113049       break;
   113050     }
   113051   }
   113052   va_end(ap);
   113053   return rc;
   113054 }
   113055 
   113056 
   113057 /*
   113058 ** Return true if the buffer z[0..n-1] contains all spaces.
   113059 */
   113060 static int allSpaces(const char *z, int n){
   113061   while( n>0 && z[n-1]==' ' ){ n--; }
   113062   return n==0;
   113063 }
   113064 
   113065 /*
   113066 ** This is the default collating function named "BINARY" which is always
   113067 ** available.
   113068 **
   113069 ** If the padFlag argument is not NULL then space padding at the end
   113070 ** of strings is ignored.  This implements the RTRIM collation.
   113071 */
   113072 static int binCollFunc(
   113073   void *padFlag,
   113074   int nKey1, const void *pKey1,
   113075   int nKey2, const void *pKey2
   113076 ){
   113077   int rc, n;
   113078   n = nKey1<nKey2 ? nKey1 : nKey2;
   113079   rc = memcmp(pKey1, pKey2, n);
   113080   if( rc==0 ){
   113081     if( padFlag
   113082      && allSpaces(((char*)pKey1)+n, nKey1-n)
   113083      && allSpaces(((char*)pKey2)+n, nKey2-n)
   113084     ){
   113085       /* Leave rc unchanged at 0 */
   113086     }else{
   113087       rc = nKey1 - nKey2;
   113088     }
   113089   }
   113090   return rc;
   113091 }
   113092 
   113093 /*
   113094 ** Another built-in collating sequence: NOCASE.
   113095 **
   113096 ** This collating sequence is intended to be used for "case independant
   113097 ** comparison". SQLite's knowledge of upper and lower case equivalents
   113098 ** extends only to the 26 characters used in the English language.
   113099 **
   113100 ** At the moment there is only a UTF-8 implementation.
   113101 */
   113102 static int nocaseCollatingFunc(
   113103   void *NotUsed,
   113104   int nKey1, const void *pKey1,
   113105   int nKey2, const void *pKey2
   113106 ){
   113107   int r = sqlite3StrNICmp(
   113108       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   113109   UNUSED_PARAMETER(NotUsed);
   113110   if( 0==r ){
   113111     r = nKey1-nKey2;
   113112   }
   113113   return r;
   113114 }
   113115 
   113116 /*
   113117 ** Return the ROWID of the most recent insert
   113118 */
   113119 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   113120   return db->lastRowid;
   113121 }
   113122 
   113123 /*
   113124 ** Return the number of changes in the most recent call to sqlite3_exec().
   113125 */
   113126 SQLITE_API int sqlite3_changes(sqlite3 *db){
   113127   return db->nChange;
   113128 }
   113129 
   113130 /*
   113131 ** Return the number of changes since the database handle was opened.
   113132 */
   113133 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   113134   return db->nTotalChange;
   113135 }
   113136 
   113137 /*
   113138 ** Close all open savepoints. This function only manipulates fields of the
   113139 ** database handle object, it does not close any savepoints that may be open
   113140 ** at the b-tree/pager level.
   113141 */
   113142 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   113143   while( db->pSavepoint ){
   113144     Savepoint *pTmp = db->pSavepoint;
   113145     db->pSavepoint = pTmp->pNext;
   113146     sqlite3DbFree(db, pTmp);
   113147   }
   113148   db->nSavepoint = 0;
   113149   db->nStatement = 0;
   113150   db->isTransactionSavepoint = 0;
   113151 }
   113152 
   113153 /*
   113154 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   113155 ** if this is not the last copy of the function, do not invoke it. Multiple
   113156 ** copies of a single function are created when create_function() is called
   113157 ** with SQLITE_ANY as the encoding.
   113158 */
   113159 static void functionDestroy(sqlite3 *db, FuncDef *p){
   113160   FuncDestructor *pDestructor = p->pDestructor;
   113161   if( pDestructor ){
   113162     pDestructor->nRef--;
   113163     if( pDestructor->nRef==0 ){
   113164       pDestructor->xDestroy(pDestructor->pUserData);
   113165       sqlite3DbFree(db, pDestructor);
   113166     }
   113167   }
   113168 }
   113169 
   113170 /*
   113171 ** Close an existing SQLite database
   113172 */
   113173 SQLITE_API int sqlite3_close(sqlite3 *db){
   113174   HashElem *i;                    /* Hash table iterator */
   113175   int j;
   113176 
   113177   if( !db ){
   113178     return SQLITE_OK;
   113179   }
   113180   if( !sqlite3SafetyCheckSickOrOk(db) ){
   113181     return SQLITE_MISUSE_BKPT;
   113182   }
   113183   sqlite3_mutex_enter(db->mutex);
   113184 
   113185   /* Force xDestroy calls on all virtual tables */
   113186   sqlite3ResetInternalSchema(db, -1);
   113187 
   113188   /* If a transaction is open, the ResetInternalSchema() call above
   113189   ** will not have called the xDisconnect() method on any virtual
   113190   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   113191   ** call will do so. We need to do this before the check for active
   113192   ** SQL statements below, as the v-table implementation may be storing
   113193   ** some prepared statements internally.
   113194   */
   113195   sqlite3VtabRollback(db);
   113196 
   113197   /* If there are any outstanding VMs, return SQLITE_BUSY. */
   113198   if( db->pVdbe ){
   113199     sqlite3Error(db, SQLITE_BUSY,
   113200         "unable to close due to unfinalised statements");
   113201     sqlite3_mutex_leave(db->mutex);
   113202     return SQLITE_BUSY;
   113203   }
   113204   assert( sqlite3SafetyCheckSickOrOk(db) );
   113205 
   113206   for(j=0; j<db->nDb; j++){
   113207     Btree *pBt = db->aDb[j].pBt;
   113208     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
   113209       sqlite3Error(db, SQLITE_BUSY,
   113210           "unable to close due to unfinished backup operation");
   113211       sqlite3_mutex_leave(db->mutex);
   113212       return SQLITE_BUSY;
   113213     }
   113214   }
   113215 
   113216   /* Free any outstanding Savepoint structures. */
   113217   sqlite3CloseSavepoints(db);
   113218 
   113219   for(j=0; j<db->nDb; j++){
   113220     struct Db *pDb = &db->aDb[j];
   113221     if( pDb->pBt ){
   113222       sqlite3BtreeClose(pDb->pBt);
   113223       pDb->pBt = 0;
   113224       if( j!=1 ){
   113225         pDb->pSchema = 0;
   113226       }
   113227     }
   113228   }
   113229   sqlite3ResetInternalSchema(db, -1);
   113230 
   113231   /* Tell the code in notify.c that the connection no longer holds any
   113232   ** locks and does not require any further unlock-notify callbacks.
   113233   */
   113234   sqlite3ConnectionClosed(db);
   113235 
   113236   assert( db->nDb<=2 );
   113237   assert( db->aDb==db->aDbStatic );
   113238   for(j=0; j<ArraySize(db->aFunc.a); j++){
   113239     FuncDef *pNext, *pHash, *p;
   113240     for(p=db->aFunc.a[j]; p; p=pHash){
   113241       pHash = p->pHash;
   113242       while( p ){
   113243         functionDestroy(db, p);
   113244         pNext = p->pNext;
   113245         sqlite3DbFree(db, p);
   113246         p = pNext;
   113247       }
   113248     }
   113249   }
   113250   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   113251     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   113252     /* Invoke any destructors registered for collation sequence user data. */
   113253     for(j=0; j<3; j++){
   113254       if( pColl[j].xDel ){
   113255         pColl[j].xDel(pColl[j].pUser);
   113256       }
   113257     }
   113258     sqlite3DbFree(db, pColl);
   113259   }
   113260   sqlite3HashClear(&db->aCollSeq);
   113261 #ifndef SQLITE_OMIT_VIRTUALTABLE
   113262   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   113263     Module *pMod = (Module *)sqliteHashData(i);
   113264     if( pMod->xDestroy ){
   113265       pMod->xDestroy(pMod->pAux);
   113266     }
   113267     sqlite3DbFree(db, pMod);
   113268   }
   113269   sqlite3HashClear(&db->aModule);
   113270 #endif
   113271 
   113272   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   113273   if( db->pErr ){
   113274     sqlite3ValueFree(db->pErr);
   113275   }
   113276   sqlite3CloseExtensions(db);
   113277 
   113278   db->magic = SQLITE_MAGIC_ERROR;
   113279 
   113280   /* The temp-database schema is allocated differently from the other schema
   113281   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   113282   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   113283   ** the same sqliteMalloc() as the one that allocates the database
   113284   ** structure?
   113285   */
   113286   sqlite3DbFree(db, db->aDb[1].pSchema);
   113287   sqlite3_mutex_leave(db->mutex);
   113288   db->magic = SQLITE_MAGIC_CLOSED;
   113289   sqlite3_mutex_free(db->mutex);
   113290   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   113291   if( db->lookaside.bMalloced ){
   113292     sqlite3_free(db->lookaside.pStart);
   113293   }
   113294   sqlite3_free(db);
   113295   return SQLITE_OK;
   113296 }
   113297 
   113298 /*
   113299 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
   113300 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
   113301 ** breaker") and made to return tripCode if there are any further
   113302 ** attempts to use that cursor.
   113303 */
   113304 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   113305   int i;
   113306   int inTrans = 0;
   113307   assert( sqlite3_mutex_held(db->mutex) );
   113308   sqlite3BeginBenignMalloc();
   113309   for(i=0; i<db->nDb; i++){
   113310     Btree *p = db->aDb[i].pBt;
   113311     if( p ){
   113312       if( sqlite3BtreeIsInTrans(p) ){
   113313         inTrans = 1;
   113314       }
   113315       sqlite3BtreeRollback(p, tripCode);
   113316       db->aDb[i].inTrans = 0;
   113317     }
   113318   }
   113319   sqlite3VtabRollback(db);
   113320   sqlite3EndBenignMalloc();
   113321 
   113322   if( db->flags&SQLITE_InternChanges ){
   113323     sqlite3ExpirePreparedStatements(db);
   113324     sqlite3ResetInternalSchema(db, -1);
   113325   }
   113326 
   113327   /* Any deferred constraint violations have now been resolved. */
   113328   db->nDeferredCons = 0;
   113329 
   113330   /* If one has been configured, invoke the rollback-hook callback */
   113331   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   113332     db->xRollbackCallback(db->pRollbackArg);
   113333   }
   113334 }
   113335 
   113336 /*
   113337 ** Return a static string that describes the kind of error specified in the
   113338 ** argument.
   113339 */
   113340 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   113341   static const char* const aMsg[] = {
   113342     /* SQLITE_OK          */ "not an error",
   113343     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   113344     /* SQLITE_INTERNAL    */ 0,
   113345     /* SQLITE_PERM        */ "access permission denied",
   113346     /* SQLITE_ABORT       */ "callback requested query abort",
   113347     /* SQLITE_BUSY        */ "database is locked",
   113348     /* SQLITE_LOCKED      */ "database table is locked",
   113349     /* SQLITE_NOMEM       */ "out of memory",
   113350     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   113351     /* SQLITE_INTERRUPT   */ "interrupted",
   113352     /* SQLITE_IOERR       */ "disk I/O error",
   113353     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   113354     /* SQLITE_NOTFOUND    */ "unknown operation",
   113355     /* SQLITE_FULL        */ "database or disk is full",
   113356     /* SQLITE_CANTOPEN    */ "unable to open database file",
   113357     /* SQLITE_PROTOCOL    */ "locking protocol",
   113358     /* SQLITE_EMPTY       */ "table contains no data",
   113359     /* SQLITE_SCHEMA      */ "database schema has changed",
   113360     /* SQLITE_TOOBIG      */ "string or blob too big",
   113361     /* SQLITE_CONSTRAINT  */ "constraint failed",
   113362     /* SQLITE_MISMATCH    */ "datatype mismatch",
   113363     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   113364     /* SQLITE_NOLFS       */ "large file support is disabled",
   113365     /* SQLITE_AUTH        */ "authorization denied",
   113366     /* SQLITE_FORMAT      */ "auxiliary database format error",
   113367     /* SQLITE_RANGE       */ "bind or column index out of range",
   113368     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   113369   };
   113370   const char *zErr = "unknown error";
   113371   switch( rc ){
   113372     case SQLITE_ABORT_ROLLBACK: {
   113373       zErr = "abort due to ROLLBACK";
   113374       break;
   113375     }
   113376     default: {
   113377       rc &= 0xff;
   113378       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
   113379         zErr = aMsg[rc];
   113380       }
   113381       break;
   113382     }
   113383   }
   113384   return zErr;
   113385 }
   113386 
   113387 /*
   113388 ** This routine implements a busy callback that sleeps and tries
   113389 ** again until a timeout value is reached.  The timeout value is
   113390 ** an integer number of milliseconds passed in as the first
   113391 ** argument.
   113392 */
   113393 static int sqliteDefaultBusyCallback(
   113394  void *ptr,               /* Database connection */
   113395  int count                /* Number of times table has been busy */
   113396 ){
   113397 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   113398   static const u8 delays[] =
   113399      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   113400   static const u8 totals[] =
   113401      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   113402 # define NDELAY ArraySize(delays)
   113403   sqlite3 *db = (sqlite3 *)ptr;
   113404   int timeout = db->busyTimeout;
   113405   int delay, prior;
   113406 
   113407   assert( count>=0 );
   113408   if( count < NDELAY ){
   113409     delay = delays[count];
   113410     prior = totals[count];
   113411   }else{
   113412     delay = delays[NDELAY-1];
   113413     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   113414   }
   113415   if( prior + delay > timeout ){
   113416     delay = timeout - prior;
   113417     if( delay<=0 ) return 0;
   113418   }
   113419   sqlite3OsSleep(db->pVfs, delay*1000);
   113420   return 1;
   113421 #else
   113422   sqlite3 *db = (sqlite3 *)ptr;
   113423   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   113424   if( (count+1)*1000 > timeout ){
   113425     return 0;
   113426   }
   113427   sqlite3OsSleep(db->pVfs, 1000000);
   113428   return 1;
   113429 #endif
   113430 }
   113431 
   113432 /*
   113433 ** Invoke the given busy handler.
   113434 **
   113435 ** This routine is called when an operation failed with a lock.
   113436 ** If this routine returns non-zero, the lock is retried.  If it
   113437 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   113438 */
   113439 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   113440   int rc;
   113441   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   113442   rc = p->xFunc(p->pArg, p->nBusy);
   113443   if( rc==0 ){
   113444     p->nBusy = -1;
   113445   }else{
   113446     p->nBusy++;
   113447   }
   113448   return rc;
   113449 }
   113450 
   113451 /*
   113452 ** This routine sets the busy callback for an Sqlite database to the
   113453 ** given callback function with the given argument.
   113454 */
   113455 SQLITE_API int sqlite3_busy_handler(
   113456   sqlite3 *db,
   113457   int (*xBusy)(void*,int),
   113458   void *pArg
   113459 ){
   113460   sqlite3_mutex_enter(db->mutex);
   113461   db->busyHandler.xFunc = xBusy;
   113462   db->busyHandler.pArg = pArg;
   113463   db->busyHandler.nBusy = 0;
   113464   sqlite3_mutex_leave(db->mutex);
   113465   return SQLITE_OK;
   113466 }
   113467 
   113468 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   113469 /*
   113470 ** This routine sets the progress callback for an Sqlite database to the
   113471 ** given callback function with the given argument. The progress callback will
   113472 ** be invoked every nOps opcodes.
   113473 */
   113474 SQLITE_API void sqlite3_progress_handler(
   113475   sqlite3 *db,
   113476   int nOps,
   113477   int (*xProgress)(void*),
   113478   void *pArg
   113479 ){
   113480   sqlite3_mutex_enter(db->mutex);
   113481   if( nOps>0 ){
   113482     db->xProgress = xProgress;
   113483     db->nProgressOps = nOps;
   113484     db->pProgressArg = pArg;
   113485   }else{
   113486     db->xProgress = 0;
   113487     db->nProgressOps = 0;
   113488     db->pProgressArg = 0;
   113489   }
   113490   sqlite3_mutex_leave(db->mutex);
   113491 }
   113492 #endif
   113493 
   113494 
   113495 /*
   113496 ** This routine installs a default busy handler that waits for the
   113497 ** specified number of milliseconds before returning 0.
   113498 */
   113499 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   113500   if( ms>0 ){
   113501     db->busyTimeout = ms;
   113502     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   113503   }else{
   113504     sqlite3_busy_handler(db, 0, 0);
   113505   }
   113506   return SQLITE_OK;
   113507 }
   113508 
   113509 /*
   113510 ** Cause any pending operation to stop at its earliest opportunity.
   113511 */
   113512 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   113513   db->u1.isInterrupted = 1;
   113514 }
   113515 
   113516 
   113517 /*
   113518 ** This function is exactly the same as sqlite3_create_function(), except
   113519 ** that it is designed to be called by internal code. The difference is
   113520 ** that if a malloc() fails in sqlite3_create_function(), an error code
   113521 ** is returned and the mallocFailed flag cleared.
   113522 */
   113523 SQLITE_PRIVATE int sqlite3CreateFunc(
   113524   sqlite3 *db,
   113525   const char *zFunctionName,
   113526   int nArg,
   113527   int enc,
   113528   void *pUserData,
   113529   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113530   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113531   void (*xFinal)(sqlite3_context*),
   113532   FuncDestructor *pDestructor
   113533 ){
   113534   FuncDef *p;
   113535   int nName;
   113536 
   113537   assert( sqlite3_mutex_held(db->mutex) );
   113538   if( zFunctionName==0 ||
   113539       (xFunc && (xFinal || xStep)) ||
   113540       (!xFunc && (xFinal && !xStep)) ||
   113541       (!xFunc && (!xFinal && xStep)) ||
   113542       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   113543       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   113544     return SQLITE_MISUSE_BKPT;
   113545   }
   113546 
   113547 #ifndef SQLITE_OMIT_UTF16
   113548   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   113549   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   113550   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   113551   **
   113552   ** If SQLITE_ANY is specified, add three versions of the function
   113553   ** to the hash table.
   113554   */
   113555   if( enc==SQLITE_UTF16 ){
   113556     enc = SQLITE_UTF16NATIVE;
   113557   }else if( enc==SQLITE_ANY ){
   113558     int rc;
   113559     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
   113560          pUserData, xFunc, xStep, xFinal, pDestructor);
   113561     if( rc==SQLITE_OK ){
   113562       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
   113563           pUserData, xFunc, xStep, xFinal, pDestructor);
   113564     }
   113565     if( rc!=SQLITE_OK ){
   113566       return rc;
   113567     }
   113568     enc = SQLITE_UTF16BE;
   113569   }
   113570 #else
   113571   enc = SQLITE_UTF8;
   113572 #endif
   113573 
   113574   /* Check if an existing function is being overridden or deleted. If so,
   113575   ** and there are active VMs, then return SQLITE_BUSY. If a function
   113576   ** is being overridden/deleted but there are no active VMs, allow the
   113577   ** operation to continue but invalidate all precompiled statements.
   113578   */
   113579   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   113580   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
   113581     if( db->activeVdbeCnt ){
   113582       sqlite3Error(db, SQLITE_BUSY,
   113583         "unable to delete/modify user-function due to active statements");
   113584       assert( !db->mallocFailed );
   113585       return SQLITE_BUSY;
   113586     }else{
   113587       sqlite3ExpirePreparedStatements(db);
   113588     }
   113589   }
   113590 
   113591   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   113592   assert(p || db->mallocFailed);
   113593   if( !p ){
   113594     return SQLITE_NOMEM;
   113595   }
   113596 
   113597   /* If an older version of the function with a configured destructor is
   113598   ** being replaced invoke the destructor function here. */
   113599   functionDestroy(db, p);
   113600 
   113601   if( pDestructor ){
   113602     pDestructor->nRef++;
   113603   }
   113604   p->pDestructor = pDestructor;
   113605   p->flags = 0;
   113606   p->xFunc = xFunc;
   113607   p->xStep = xStep;
   113608   p->xFinalize = xFinal;
   113609   p->pUserData = pUserData;
   113610   p->nArg = (u16)nArg;
   113611   return SQLITE_OK;
   113612 }
   113613 
   113614 /*
   113615 ** Create new user functions.
   113616 */
   113617 SQLITE_API int sqlite3_create_function(
   113618   sqlite3 *db,
   113619   const char *zFunc,
   113620   int nArg,
   113621   int enc,
   113622   void *p,
   113623   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113624   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113625   void (*xFinal)(sqlite3_context*)
   113626 ){
   113627   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   113628                                     xFinal, 0);
   113629 }
   113630 
   113631 SQLITE_API int sqlite3_create_function_v2(
   113632   sqlite3 *db,
   113633   const char *zFunc,
   113634   int nArg,
   113635   int enc,
   113636   void *p,
   113637   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   113638   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   113639   void (*xFinal)(sqlite3_context*),
   113640   void (*xDestroy)(void *)
   113641 ){
   113642   int rc = SQLITE_ERROR;
   113643   FuncDestructor *pArg = 0;
   113644   sqlite3_mutex_enter(db->mutex);
   113645   if( xDestroy ){
   113646     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   113647     if( !pArg ){
   113648       xDestroy(p);
   113649       goto out;
   113650     }
   113651     pArg->xDestroy = xDestroy;
   113652     pArg->pUserData = p;
   113653   }
   113654   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   113655   if( pArg && pArg->nRef==0 ){
   113656     assert( rc!=SQLITE_OK );
   113657     xDestroy(p);
   113658     sqlite3DbFree(db, pArg);
   113659   }
   113660 
   113661  out:
   113662   rc = sqlite3ApiExit(db, rc);
   113663   sqlite3_mutex_leave(db->mutex);
   113664   return rc;
   113665 }
   113666 
   113667 #ifndef SQLITE_OMIT_UTF16
   113668 SQLITE_API int sqlite3_create_function16(
   113669   sqlite3 *db,
   113670   const void *zFunctionName,
   113671   int nArg,
   113672   int eTextRep,
   113673   void *p,
   113674   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   113675   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   113676   void (*xFinal)(sqlite3_context*)
   113677 ){
   113678   int rc;
   113679   char *zFunc8;
   113680   sqlite3_mutex_enter(db->mutex);
   113681   assert( !db->mallocFailed );
   113682   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   113683   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   113684   sqlite3DbFree(db, zFunc8);
   113685   rc = sqlite3ApiExit(db, rc);
   113686   sqlite3_mutex_leave(db->mutex);
   113687   return rc;
   113688 }
   113689 #endif
   113690 
   113691 
   113692 /*
   113693 ** Declare that a function has been overloaded by a virtual table.
   113694 **
   113695 ** If the function already exists as a regular global function, then
   113696 ** this routine is a no-op.  If the function does not exist, then create
   113697 ** a new one that always throws a run-time error.
   113698 **
   113699 ** When virtual tables intend to provide an overloaded function, they
   113700 ** should call this routine to make sure the global function exists.
   113701 ** A global function must exist in order for name resolution to work
   113702 ** properly.
   113703 */
   113704 SQLITE_API int sqlite3_overload_function(
   113705   sqlite3 *db,
   113706   const char *zName,
   113707   int nArg
   113708 ){
   113709   int nName = sqlite3Strlen30(zName);
   113710   int rc = SQLITE_OK;
   113711   sqlite3_mutex_enter(db->mutex);
   113712   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   113713     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   113714                            0, sqlite3InvalidFunction, 0, 0, 0);
   113715   }
   113716   rc = sqlite3ApiExit(db, rc);
   113717   sqlite3_mutex_leave(db->mutex);
   113718   return rc;
   113719 }
   113720 
   113721 #ifndef SQLITE_OMIT_TRACE
   113722 /*
   113723 ** Register a trace function.  The pArg from the previously registered trace
   113724 ** is returned.
   113725 **
   113726 ** A NULL trace function means that no tracing is executes.  A non-NULL
   113727 ** trace is a pointer to a function that is invoked at the start of each
   113728 ** SQL statement.
   113729 */
   113730 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   113731   void *pOld;
   113732   sqlite3_mutex_enter(db->mutex);
   113733   pOld = db->pTraceArg;
   113734   db->xTrace = xTrace;
   113735   db->pTraceArg = pArg;
   113736   sqlite3_mutex_leave(db->mutex);
   113737   return pOld;
   113738 }
   113739 /*
   113740 ** Register a profile function.  The pArg from the previously registered
   113741 ** profile function is returned.
   113742 **
   113743 ** A NULL profile function means that no profiling is executes.  A non-NULL
   113744 ** profile is a pointer to a function that is invoked at the conclusion of
   113745 ** each SQL statement that is run.
   113746 */
   113747 SQLITE_API void *sqlite3_profile(
   113748   sqlite3 *db,
   113749   void (*xProfile)(void*,const char*,sqlite_uint64),
   113750   void *pArg
   113751 ){
   113752   void *pOld;
   113753   sqlite3_mutex_enter(db->mutex);
   113754   pOld = db->pProfileArg;
   113755   db->xProfile = xProfile;
   113756   db->pProfileArg = pArg;
   113757   sqlite3_mutex_leave(db->mutex);
   113758   return pOld;
   113759 }
   113760 #endif /* SQLITE_OMIT_TRACE */
   113761 
   113762 /*
   113763 ** Register a function to be invoked when a transaction commits.
   113764 ** If the invoked function returns non-zero, then the commit becomes a
   113765 ** rollback.
   113766 */
   113767 SQLITE_API void *sqlite3_commit_hook(
   113768   sqlite3 *db,              /* Attach the hook to this database */
   113769   int (*xCallback)(void*),  /* Function to invoke on each commit */
   113770   void *pArg                /* Argument to the function */
   113771 ){
   113772   void *pOld;
   113773   sqlite3_mutex_enter(db->mutex);
   113774   pOld = db->pCommitArg;
   113775   db->xCommitCallback = xCallback;
   113776   db->pCommitArg = pArg;
   113777   sqlite3_mutex_leave(db->mutex);
   113778   return pOld;
   113779 }
   113780 
   113781 /*
   113782 ** Register a callback to be invoked each time a row is updated,
   113783 ** inserted or deleted using this database connection.
   113784 */
   113785 SQLITE_API void *sqlite3_update_hook(
   113786   sqlite3 *db,              /* Attach the hook to this database */
   113787   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   113788   void *pArg                /* Argument to the function */
   113789 ){
   113790   void *pRet;
   113791   sqlite3_mutex_enter(db->mutex);
   113792   pRet = db->pUpdateArg;
   113793   db->xUpdateCallback = xCallback;
   113794   db->pUpdateArg = pArg;
   113795   sqlite3_mutex_leave(db->mutex);
   113796   return pRet;
   113797 }
   113798 
   113799 /*
   113800 ** Register a callback to be invoked each time a transaction is rolled
   113801 ** back by this database connection.
   113802 */
   113803 SQLITE_API void *sqlite3_rollback_hook(
   113804   sqlite3 *db,              /* Attach the hook to this database */
   113805   void (*xCallback)(void*), /* Callback function */
   113806   void *pArg                /* Argument to the function */
   113807 ){
   113808   void *pRet;
   113809   sqlite3_mutex_enter(db->mutex);
   113810   pRet = db->pRollbackArg;
   113811   db->xRollbackCallback = xCallback;
   113812   db->pRollbackArg = pArg;
   113813   sqlite3_mutex_leave(db->mutex);
   113814   return pRet;
   113815 }
   113816 
   113817 #ifndef SQLITE_OMIT_WAL
   113818 /*
   113819 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   113820 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   113821 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   113822 ** wal_autocheckpoint()).
   113823 */
   113824 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   113825   void *pClientData,     /* Argument */
   113826   sqlite3 *db,           /* Connection */
   113827   const char *zDb,       /* Database */
   113828   int nFrame             /* Size of WAL */
   113829 ){
   113830   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   113831     sqlite3BeginBenignMalloc();
   113832     sqlite3_wal_checkpoint(db, zDb);
   113833     sqlite3EndBenignMalloc();
   113834   }
   113835   return SQLITE_OK;
   113836 }
   113837 #endif /* SQLITE_OMIT_WAL */
   113838 
   113839 /*
   113840 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   113841 ** a database after committing a transaction if there are nFrame or
   113842 ** more frames in the log file. Passing zero or a negative value as the
   113843 ** nFrame parameter disables automatic checkpoints entirely.
   113844 **
   113845 ** The callback registered by this function replaces any existing callback
   113846 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   113847 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   113848 ** configured by this function.
   113849 */
   113850 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   113851 #ifdef SQLITE_OMIT_WAL
   113852   UNUSED_PARAMETER(db);
   113853   UNUSED_PARAMETER(nFrame);
   113854 #else
   113855   if( nFrame>0 ){
   113856     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   113857   }else{
   113858     sqlite3_wal_hook(db, 0, 0);
   113859   }
   113860 #endif
   113861   return SQLITE_OK;
   113862 }
   113863 
   113864 /*
   113865 ** Register a callback to be invoked each time a transaction is written
   113866 ** into the write-ahead-log by this database connection.
   113867 */
   113868 SQLITE_API void *sqlite3_wal_hook(
   113869   sqlite3 *db,                    /* Attach the hook to this db handle */
   113870   int(*xCallback)(void *, sqlite3*, const char*, int),
   113871   void *pArg                      /* First argument passed to xCallback() */
   113872 ){
   113873 #ifndef SQLITE_OMIT_WAL
   113874   void *pRet;
   113875   sqlite3_mutex_enter(db->mutex);
   113876   pRet = db->pWalArg;
   113877   db->xWalCallback = xCallback;
   113878   db->pWalArg = pArg;
   113879   sqlite3_mutex_leave(db->mutex);
   113880   return pRet;
   113881 #else
   113882   return 0;
   113883 #endif
   113884 }
   113885 
   113886 /*
   113887 ** Checkpoint database zDb.
   113888 */
   113889 SQLITE_API int sqlite3_wal_checkpoint_v2(
   113890   sqlite3 *db,                    /* Database handle */
   113891   const char *zDb,                /* Name of attached database (or NULL) */
   113892   int eMode,                      /* SQLITE_CHECKPOINT_* value */
   113893   int *pnLog,                     /* OUT: Size of WAL log in frames */
   113894   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
   113895 ){
   113896 #ifdef SQLITE_OMIT_WAL
   113897   return SQLITE_OK;
   113898 #else
   113899   int rc;                         /* Return code */
   113900   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   113901 
   113902   /* Initialize the output variables to -1 in case an error occurs. */
   113903   if( pnLog ) *pnLog = -1;
   113904   if( pnCkpt ) *pnCkpt = -1;
   113905 
   113906   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
   113907   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
   113908   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
   113909   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
   113910     return SQLITE_MISUSE;
   113911   }
   113912 
   113913   sqlite3_mutex_enter(db->mutex);
   113914   if( zDb && zDb[0] ){
   113915     iDb = sqlite3FindDbName(db, zDb);
   113916   }
   113917   if( iDb<0 ){
   113918     rc = SQLITE_ERROR;
   113919     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   113920   }else{
   113921     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
   113922     sqlite3Error(db, rc, 0);
   113923   }
   113924   rc = sqlite3ApiExit(db, rc);
   113925   sqlite3_mutex_leave(db->mutex);
   113926   return rc;
   113927 #endif
   113928 }
   113929 
   113930 
   113931 /*
   113932 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   113933 ** to contains a zero-length string, all attached databases are
   113934 ** checkpointed.
   113935 */
   113936 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   113937   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
   113938 }
   113939 
   113940 #ifndef SQLITE_OMIT_WAL
   113941 /*
   113942 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   113943 ** not currently open in WAL mode.
   113944 **
   113945 ** If a transaction is open on the database being checkpointed, this
   113946 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   113947 ** an error occurs while running the checkpoint, an SQLite error code is
   113948 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   113949 **
   113950 ** The mutex on database handle db should be held by the caller. The mutex
   113951 ** associated with the specific b-tree being checkpointed is taken by
   113952 ** this function while the checkpoint is running.
   113953 **
   113954 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   113955 ** checkpointed. If an error is encountered it is returned immediately -
   113956 ** no attempt is made to checkpoint any remaining databases.
   113957 **
   113958 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
   113959 */
   113960 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
   113961   int rc = SQLITE_OK;             /* Return code */
   113962   int i;                          /* Used to iterate through attached dbs */
   113963   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
   113964 
   113965   assert( sqlite3_mutex_held(db->mutex) );
   113966   assert( !pnLog || *pnLog==-1 );
   113967   assert( !pnCkpt || *pnCkpt==-1 );
   113968 
   113969   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   113970     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   113971       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
   113972       pnLog = 0;
   113973       pnCkpt = 0;
   113974       if( rc==SQLITE_BUSY ){
   113975         bBusy = 1;
   113976         rc = SQLITE_OK;
   113977       }
   113978     }
   113979   }
   113980 
   113981   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
   113982 }
   113983 #endif /* SQLITE_OMIT_WAL */
   113984 
   113985 /*
   113986 ** This function returns true if main-memory should be used instead of
   113987 ** a temporary file for transient pager files and statement journals.
   113988 ** The value returned depends on the value of db->temp_store (runtime
   113989 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   113990 ** following table describes the relationship between these two values
   113991 ** and this functions return value.
   113992 **
   113993 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   113994 **   -----------------     --------------     ------------------------------
   113995 **   0                     any                file      (return 0)
   113996 **   1                     1                  file      (return 0)
   113997 **   1                     2                  memory    (return 1)
   113998 **   1                     0                  file      (return 0)
   113999 **   2                     1                  file      (return 0)
   114000 **   2                     2                  memory    (return 1)
   114001 **   2                     0                  memory    (return 1)
   114002 **   3                     any                memory    (return 1)
   114003 */
   114004 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   114005 #if SQLITE_TEMP_STORE==1
   114006   return ( db->temp_store==2 );
   114007 #endif
   114008 #if SQLITE_TEMP_STORE==2
   114009   return ( db->temp_store!=1 );
   114010 #endif
   114011 #if SQLITE_TEMP_STORE==3
   114012   return 1;
   114013 #endif
   114014 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   114015   return 0;
   114016 #endif
   114017 }
   114018 
   114019 /*
   114020 ** Return UTF-8 encoded English language explanation of the most recent
   114021 ** error.
   114022 */
   114023 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   114024   const char *z;
   114025   if( !db ){
   114026     return sqlite3ErrStr(SQLITE_NOMEM);
   114027   }
   114028   if( !sqlite3SafetyCheckSickOrOk(db) ){
   114029     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   114030   }
   114031   sqlite3_mutex_enter(db->mutex);
   114032   if( db->mallocFailed ){
   114033     z = sqlite3ErrStr(SQLITE_NOMEM);
   114034   }else{
   114035     z = (char*)sqlite3_value_text(db->pErr);
   114036     assert( !db->mallocFailed );
   114037     if( z==0 ){
   114038       z = sqlite3ErrStr(db->errCode);
   114039     }
   114040   }
   114041   sqlite3_mutex_leave(db->mutex);
   114042   return z;
   114043 }
   114044 
   114045 #ifndef SQLITE_OMIT_UTF16
   114046 /*
   114047 ** Return UTF-16 encoded English language explanation of the most recent
   114048 ** error.
   114049 */
   114050 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   114051   static const u16 outOfMem[] = {
   114052     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   114053   };
   114054   static const u16 misuse[] = {
   114055     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   114056     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   114057     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   114058     'o', 'u', 't', ' ',
   114059     'o', 'f', ' ',
   114060     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   114061   };
   114062 
   114063   const void *z;
   114064   if( !db ){
   114065     return (void *)outOfMem;
   114066   }
   114067   if( !sqlite3SafetyCheckSickOrOk(db) ){
   114068     return (void *)misuse;
   114069   }
   114070   sqlite3_mutex_enter(db->mutex);
   114071   if( db->mallocFailed ){
   114072     z = (void *)outOfMem;
   114073   }else{
   114074     z = sqlite3_value_text16(db->pErr);
   114075     if( z==0 ){
   114076       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
   114077            SQLITE_UTF8, SQLITE_STATIC);
   114078       z = sqlite3_value_text16(db->pErr);
   114079     }
   114080     /* A malloc() may have failed within the call to sqlite3_value_text16()
   114081     ** above. If this is the case, then the db->mallocFailed flag needs to
   114082     ** be cleared before returning. Do this directly, instead of via
   114083     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   114084     */
   114085     db->mallocFailed = 0;
   114086   }
   114087   sqlite3_mutex_leave(db->mutex);
   114088   return z;
   114089 }
   114090 #endif /* SQLITE_OMIT_UTF16 */
   114091 
   114092 /*
   114093 ** Return the most recent error code generated by an SQLite routine. If NULL is
   114094 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   114095 */
   114096 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   114097   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   114098     return SQLITE_MISUSE_BKPT;
   114099   }
   114100   if( !db || db->mallocFailed ){
   114101     return SQLITE_NOMEM;
   114102   }
   114103   return db->errCode & db->errMask;
   114104 }
   114105 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   114106   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   114107     return SQLITE_MISUSE_BKPT;
   114108   }
   114109   if( !db || db->mallocFailed ){
   114110     return SQLITE_NOMEM;
   114111   }
   114112   return db->errCode;
   114113 }
   114114 
   114115 /*
   114116 ** Create a new collating function for database "db".  The name is zName
   114117 ** and the encoding is enc.
   114118 */
   114119 static int createCollation(
   114120   sqlite3* db,
   114121   const char *zName,
   114122   u8 enc,
   114123   void* pCtx,
   114124   int(*xCompare)(void*,int,const void*,int,const void*),
   114125   void(*xDel)(void*)
   114126 ){
   114127   CollSeq *pColl;
   114128   int enc2;
   114129   int nName = sqlite3Strlen30(zName);
   114130 
   114131   assert( sqlite3_mutex_held(db->mutex) );
   114132 
   114133   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   114134   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   114135   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   114136   */
   114137   enc2 = enc;
   114138   testcase( enc2==SQLITE_UTF16 );
   114139   testcase( enc2==SQLITE_UTF16_ALIGNED );
   114140   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   114141     enc2 = SQLITE_UTF16NATIVE;
   114142   }
   114143   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   114144     return SQLITE_MISUSE_BKPT;
   114145   }
   114146 
   114147   /* Check if this call is removing or replacing an existing collation
   114148   ** sequence. If so, and there are active VMs, return busy. If there
   114149   ** are no active VMs, invalidate any pre-compiled statements.
   114150   */
   114151   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   114152   if( pColl && pColl->xCmp ){
   114153     if( db->activeVdbeCnt ){
   114154       sqlite3Error(db, SQLITE_BUSY,
   114155         "unable to delete/modify collation sequence due to active statements");
   114156       return SQLITE_BUSY;
   114157     }
   114158     sqlite3ExpirePreparedStatements(db);
   114159 
   114160     /* If collation sequence pColl was created directly by a call to
   114161     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   114162     ** then any copies made by synthCollSeq() need to be invalidated.
   114163     ** Also, collation destructor - CollSeq.xDel() - function may need
   114164     ** to be called.
   114165     */
   114166     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   114167       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   114168       int j;
   114169       for(j=0; j<3; j++){
   114170         CollSeq *p = &aColl[j];
   114171         if( p->enc==pColl->enc ){
   114172           if( p->xDel ){
   114173             p->xDel(p->pUser);
   114174           }
   114175           p->xCmp = 0;
   114176         }
   114177       }
   114178     }
   114179   }
   114180 
   114181   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   114182   if( pColl==0 ) return SQLITE_NOMEM;
   114183   pColl->xCmp = xCompare;
   114184   pColl->pUser = pCtx;
   114185   pColl->xDel = xDel;
   114186   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   114187   sqlite3Error(db, SQLITE_OK, 0);
   114188   return SQLITE_OK;
   114189 }
   114190 
   114191 
   114192 /*
   114193 ** This array defines hard upper bounds on limit values.  The
   114194 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   114195 ** #defines in sqlite3.h.
   114196 */
   114197 static const int aHardLimit[] = {
   114198   SQLITE_MAX_LENGTH,
   114199   SQLITE_MAX_SQL_LENGTH,
   114200   SQLITE_MAX_COLUMN,
   114201   SQLITE_MAX_EXPR_DEPTH,
   114202   SQLITE_MAX_COMPOUND_SELECT,
   114203   SQLITE_MAX_VDBE_OP,
   114204   SQLITE_MAX_FUNCTION_ARG,
   114205   SQLITE_MAX_ATTACHED,
   114206   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   114207   SQLITE_MAX_VARIABLE_NUMBER,
   114208   SQLITE_MAX_TRIGGER_DEPTH,
   114209 };
   114210 
   114211 /*
   114212 ** Make sure the hard limits are set to reasonable values
   114213 */
   114214 #if SQLITE_MAX_LENGTH<100
   114215 # error SQLITE_MAX_LENGTH must be at least 100
   114216 #endif
   114217 #if SQLITE_MAX_SQL_LENGTH<100
   114218 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   114219 #endif
   114220 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   114221 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   114222 #endif
   114223 #if SQLITE_MAX_COMPOUND_SELECT<2
   114224 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   114225 #endif
   114226 #if SQLITE_MAX_VDBE_OP<40
   114227 # error SQLITE_MAX_VDBE_OP must be at least 40
   114228 #endif
   114229 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   114230 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   114231 #endif
   114232 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
   114233 # error SQLITE_MAX_ATTACHED must be between 0 and 62
   114234 #endif
   114235 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   114236 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   114237 #endif
   114238 #if SQLITE_MAX_COLUMN>32767
   114239 # error SQLITE_MAX_COLUMN must not exceed 32767
   114240 #endif
   114241 #if SQLITE_MAX_TRIGGER_DEPTH<1
   114242 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   114243 #endif
   114244 
   114245 
   114246 /*
   114247 ** Change the value of a limit.  Report the old value.
   114248 ** If an invalid limit index is supplied, report -1.
   114249 ** Make no changes but still report the old value if the
   114250 ** new limit is negative.
   114251 **
   114252 ** A new lower limit does not shrink existing constructs.
   114253 ** It merely prevents new constructs that exceed the limit
   114254 ** from forming.
   114255 */
   114256 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   114257   int oldLimit;
   114258 
   114259 
   114260   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   114261   ** there is a hard upper bound set at compile-time by a C preprocessor
   114262   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   114263   ** "_MAX_".)
   114264   */
   114265   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   114266   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   114267   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   114268   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   114269   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   114270   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   114271   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   114272   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   114273   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   114274                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   114275   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   114276   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   114277   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   114278 
   114279 
   114280   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   114281     return -1;
   114282   }
   114283   oldLimit = db->aLimit[limitId];
   114284   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   114285     if( newLimit>aHardLimit[limitId] ){
   114286       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   114287     }
   114288     db->aLimit[limitId] = newLimit;
   114289   }
   114290   return oldLimit;                     /* IMP: R-53341-35419 */
   114291 }
   114292 
   114293 /*
   114294 ** This function is used to parse both URIs and non-URI filenames passed by the
   114295 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
   114296 ** URIs specified as part of ATTACH statements.
   114297 **
   114298 ** The first argument to this function is the name of the VFS to use (or
   114299 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
   114300 ** query parameter. The second argument contains the URI (or non-URI filename)
   114301 ** itself. When this function is called the *pFlags variable should contain
   114302 ** the default flags to open the database handle with. The value stored in
   114303 ** *pFlags may be updated before returning if the URI filename contains
   114304 ** "cache=xxx" or "mode=xxx" query parameters.
   114305 **
   114306 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
   114307 ** the VFS that should be used to open the database file. *pzFile is set to
   114308 ** point to a buffer containing the name of the file to open. It is the
   114309 ** responsibility of the caller to eventually call sqlite3_free() to release
   114310 ** this buffer.
   114311 **
   114312 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
   114313 ** may be set to point to a buffer containing an English language error
   114314 ** message. It is the responsibility of the caller to eventually release
   114315 ** this buffer by calling sqlite3_free().
   114316 */
   114317 SQLITE_PRIVATE int sqlite3ParseUri(
   114318   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   114319   const char *zUri,               /* Nul-terminated URI to parse */
   114320   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
   114321   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   114322   char **pzFile,                  /* OUT: Filename component of URI */
   114323   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
   114324 ){
   114325   int rc = SQLITE_OK;
   114326   unsigned int flags = *pFlags;
   114327   const char *zVfs = zDefaultVfs;
   114328   char *zFile;
   114329   char c;
   114330   int nUri = sqlite3Strlen30(zUri);
   114331 
   114332   assert( *pzErrMsg==0 );
   114333 
   114334   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
   114335    && nUri>=5 && memcmp(zUri, "file:", 5)==0
   114336   ){
   114337     char *zOpt;
   114338     int eState;                   /* Parser state when parsing URI */
   114339     int iIn;                      /* Input character index */
   114340     int iOut = 0;                 /* Output character index */
   114341     int nByte = nUri+2;           /* Bytes of space to allocate */
   114342 
   114343     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
   114344     ** method that there may be extra parameters following the file-name.  */
   114345     flags |= SQLITE_OPEN_URI;
   114346 
   114347     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
   114348     zFile = sqlite3_malloc(nByte);
   114349     if( !zFile ) return SQLITE_NOMEM;
   114350 
   114351     /* Discard the scheme and authority segments of the URI. */
   114352     if( zUri[5]=='/' && zUri[6]=='/' ){
   114353       iIn = 7;
   114354       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
   114355 
   114356       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
   114357         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
   114358             iIn-7, &zUri[7]);
   114359         rc = SQLITE_ERROR;
   114360         goto parse_uri_out;
   114361       }
   114362     }else{
   114363       iIn = 5;
   114364     }
   114365 
   114366     /* Copy the filename and any query parameters into the zFile buffer.
   114367     ** Decode %HH escape codes along the way.
   114368     **
   114369     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
   114370     ** on the parsing context. As follows:
   114371     **
   114372     **   0: Parsing file-name.
   114373     **   1: Parsing name section of a name=value query parameter.
   114374     **   2: Parsing value section of a name=value query parameter.
   114375     */
   114376     eState = 0;
   114377     while( (c = zUri[iIn])!=0 && c!='#' ){
   114378       iIn++;
   114379       if( c=='%'
   114380        && sqlite3Isxdigit(zUri[iIn])
   114381        && sqlite3Isxdigit(zUri[iIn+1])
   114382       ){
   114383         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
   114384         octet += sqlite3HexToInt(zUri[iIn++]);
   114385 
   114386         assert( octet>=0 && octet<256 );
   114387         if( octet==0 ){
   114388           /* This branch is taken when "%00" appears within the URI. In this
   114389           ** case we ignore all text in the remainder of the path, name or
   114390           ** value currently being parsed. So ignore the current character
   114391           ** and skip to the next "?", "=" or "&", as appropriate. */
   114392           while( (c = zUri[iIn])!=0 && c!='#'
   114393               && (eState!=0 || c!='?')
   114394               && (eState!=1 || (c!='=' && c!='&'))
   114395               && (eState!=2 || c!='&')
   114396           ){
   114397             iIn++;
   114398           }
   114399           continue;
   114400         }
   114401         c = octet;
   114402       }else if( eState==1 && (c=='&' || c=='=') ){
   114403         if( zFile[iOut-1]==0 ){
   114404           /* An empty option name. Ignore this option altogether. */
   114405           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
   114406           continue;
   114407         }
   114408         if( c=='&' ){
   114409           zFile[iOut++] = '\0';
   114410         }else{
   114411           eState = 2;
   114412         }
   114413         c = 0;
   114414       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
   114415         c = 0;
   114416         eState = 1;
   114417       }
   114418       zFile[iOut++] = c;
   114419     }
   114420     if( eState==1 ) zFile[iOut++] = '\0';
   114421     zFile[iOut++] = '\0';
   114422     zFile[iOut++] = '\0';
   114423 
   114424     /* Check if there were any options specified that should be interpreted
   114425     ** here. Options that are interpreted here include "vfs" and those that
   114426     ** correspond to flags that may be passed to the sqlite3_open_v2()
   114427     ** method. */
   114428     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
   114429     while( zOpt[0] ){
   114430       int nOpt = sqlite3Strlen30(zOpt);
   114431       char *zVal = &zOpt[nOpt+1];
   114432       int nVal = sqlite3Strlen30(zVal);
   114433 
   114434       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
   114435         zVfs = zVal;
   114436       }else{
   114437         struct OpenMode {
   114438           const char *z;
   114439           int mode;
   114440         } *aMode = 0;
   114441         char *zModeType = 0;
   114442         int mask = 0;
   114443         int limit = 0;
   114444 
   114445         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
   114446           static struct OpenMode aCacheMode[] = {
   114447             { "shared",  SQLITE_OPEN_SHAREDCACHE },
   114448             { "private", SQLITE_OPEN_PRIVATECACHE },
   114449             { 0, 0 }
   114450           };
   114451 
   114452           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
   114453           aMode = aCacheMode;
   114454           limit = mask;
   114455           zModeType = "cache";
   114456         }
   114457         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
   114458           static struct OpenMode aOpenMode[] = {
   114459             { "ro",  SQLITE_OPEN_READONLY },
   114460             { "rw",  SQLITE_OPEN_READWRITE },
   114461             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
   114462             { 0, 0 }
   114463           };
   114464 
   114465           mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
   114466           aMode = aOpenMode;
   114467           limit = mask & flags;
   114468           zModeType = "access";
   114469         }
   114470 
   114471         if( aMode ){
   114472           int i;
   114473           int mode = 0;
   114474           for(i=0; aMode[i].z; i++){
   114475             const char *z = aMode[i].z;
   114476             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
   114477               mode = aMode[i].mode;
   114478               break;
   114479             }
   114480           }
   114481           if( mode==0 ){
   114482             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
   114483             rc = SQLITE_ERROR;
   114484             goto parse_uri_out;
   114485           }
   114486           if( mode>limit ){
   114487             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
   114488                                         zModeType, zVal);
   114489             rc = SQLITE_PERM;
   114490             goto parse_uri_out;
   114491           }
   114492           flags = (flags & ~mask) | mode;
   114493         }
   114494       }
   114495 
   114496       zOpt = &zVal[nVal+1];
   114497     }
   114498 
   114499   }else{
   114500     zFile = sqlite3_malloc(nUri+2);
   114501     if( !zFile ) return SQLITE_NOMEM;
   114502     memcpy(zFile, zUri, nUri);
   114503     zFile[nUri] = '\0';
   114504     zFile[nUri+1] = '\0';
   114505   }
   114506 
   114507   *ppVfs = sqlite3_vfs_find(zVfs);
   114508   if( *ppVfs==0 ){
   114509     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
   114510     rc = SQLITE_ERROR;
   114511   }
   114512  parse_uri_out:
   114513   if( rc!=SQLITE_OK ){
   114514     sqlite3_free(zFile);
   114515     zFile = 0;
   114516   }
   114517   *pFlags = flags;
   114518   *pzFile = zFile;
   114519   return rc;
   114520 }
   114521 
   114522 
   114523 /*
   114524 ** This routine does the work of opening a database on behalf of
   114525 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   114526 ** is UTF-8 encoded.
   114527 */
   114528 static int openDatabase(
   114529   const char *zFilename, /* Database filename UTF-8 encoded */
   114530   sqlite3 **ppDb,        /* OUT: Returned database handle */
   114531   unsigned int flags,    /* Operational flags */
   114532   const char *zVfs       /* Name of the VFS to use */
   114533 ){
   114534   sqlite3 *db;                    /* Store allocated handle here */
   114535   int rc;                         /* Return code */
   114536   int isThreadsafe;               /* True for threadsafe connections */
   114537   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   114538   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
   114539 
   114540   *ppDb = 0;
   114541 #ifndef SQLITE_OMIT_AUTOINIT
   114542   rc = sqlite3_initialize();
   114543   if( rc ) return rc;
   114544 #endif
   114545 
   114546   /* Only allow sensible combinations of bits in the flags argument.
   114547   ** Throw an error if any non-sense combination is used.  If we
   114548   ** do not block illegal combinations here, it could trigger
   114549   ** assert() statements in deeper layers.  Sensible combinations
   114550   ** are:
   114551   **
   114552   **  1:  SQLITE_OPEN_READONLY
   114553   **  2:  SQLITE_OPEN_READWRITE
   114554   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   114555   */
   114556   assert( SQLITE_OPEN_READONLY  == 0x01 );
   114557   assert( SQLITE_OPEN_READWRITE == 0x02 );
   114558   assert( SQLITE_OPEN_CREATE    == 0x04 );
   114559   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   114560   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   114561   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   114562   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
   114563 
   114564   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   114565     isThreadsafe = 0;
   114566   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   114567     isThreadsafe = 0;
   114568   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   114569     isThreadsafe = 1;
   114570   }else{
   114571     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   114572   }
   114573   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   114574     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   114575   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   114576     flags |= SQLITE_OPEN_SHAREDCACHE;
   114577   }
   114578 
   114579   /* Remove harmful bits from the flags parameter
   114580   **
   114581   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   114582   ** dealt with in the previous code block.  Besides these, the only
   114583   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   114584   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
   114585   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
   114586   ** off all other flags.
   114587   */
   114588   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   114589                SQLITE_OPEN_EXCLUSIVE |
   114590                SQLITE_OPEN_MAIN_DB |
   114591                SQLITE_OPEN_TEMP_DB |
   114592                SQLITE_OPEN_TRANSIENT_DB |
   114593                SQLITE_OPEN_MAIN_JOURNAL |
   114594                SQLITE_OPEN_TEMP_JOURNAL |
   114595                SQLITE_OPEN_SUBJOURNAL |
   114596                SQLITE_OPEN_MASTER_JOURNAL |
   114597                SQLITE_OPEN_NOMUTEX |
   114598                SQLITE_OPEN_FULLMUTEX |
   114599                SQLITE_OPEN_WAL
   114600              );
   114601 
   114602   /* Allocate the sqlite data structure */
   114603   db = sqlite3MallocZero( sizeof(sqlite3) );
   114604   if( db==0 ) goto opendb_out;
   114605   if( isThreadsafe ){
   114606     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   114607     if( db->mutex==0 ){
   114608       sqlite3_free(db);
   114609       db = 0;
   114610       goto opendb_out;
   114611     }
   114612   }
   114613   sqlite3_mutex_enter(db->mutex);
   114614   db->errMask = 0xff;
   114615   db->nDb = 2;
   114616   db->magic = SQLITE_MAGIC_BUSY;
   114617   db->aDb = db->aDbStatic;
   114618 
   114619   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   114620   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   114621   db->autoCommit = 1;
   114622   db->nextAutovac = -1;
   114623   db->nextPagesize = 0;
   114624   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
   114625 #if SQLITE_DEFAULT_FILE_FORMAT<4
   114626                  | SQLITE_LegacyFileFmt
   114627 #endif
   114628 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   114629                  | SQLITE_LoadExtension
   114630 #endif
   114631 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   114632                  | SQLITE_RecTriggers
   114633 #endif
   114634 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
   114635                  | SQLITE_ForeignKeys
   114636 #endif
   114637       ;
   114638   sqlite3HashInit(&db->aCollSeq);
   114639 #ifndef SQLITE_OMIT_VIRTUALTABLE
   114640   sqlite3HashInit(&db->aModule);
   114641 #endif
   114642 
   114643   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   114644   ** and UTF-16, so add a version for each to avoid any unnecessary
   114645   ** conversions. The only error that can occur here is a malloc() failure.
   114646   */
   114647   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
   114648   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
   114649   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
   114650   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
   114651   if( db->mallocFailed ){
   114652     goto opendb_out;
   114653   }
   114654   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   114655   assert( db->pDfltColl!=0 );
   114656 
   114657   /* Also add a UTF-8 case-insensitive collation sequence. */
   114658   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
   114659 
   114660   /* Parse the filename/URI argument. */
   114661   db->openFlags = flags;
   114662   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   114663   if( rc!=SQLITE_OK ){
   114664     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   114665     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
   114666     sqlite3_free(zErrMsg);
   114667     goto opendb_out;
   114668   }
   114669 
   114670   /* Open the backend database driver */
   114671   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
   114672                         flags | SQLITE_OPEN_MAIN_DB);
   114673   if( rc!=SQLITE_OK ){
   114674     if( rc==SQLITE_IOERR_NOMEM ){
   114675       rc = SQLITE_NOMEM;
   114676     }
   114677     sqlite3Error(db, rc, 0);
   114678     goto opendb_out;
   114679   }
   114680   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   114681   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   114682 
   114683 
   114684   /* The default safety_level for the main database is 'full'; for the temp
   114685   ** database it is 'NONE'. This matches the pager layer defaults.
   114686   */
   114687   db->aDb[0].zName = "main";
   114688   db->aDb[0].safety_level = 3;
   114689   db->aDb[1].zName = "temp";
   114690   db->aDb[1].safety_level = 1;
   114691 
   114692   db->magic = SQLITE_MAGIC_OPEN;
   114693   if( db->mallocFailed ){
   114694     goto opendb_out;
   114695   }
   114696 
   114697   /* Register all built-in functions, but do not attempt to read the
   114698   ** database schema yet. This is delayed until the first time the database
   114699   ** is accessed.
   114700   */
   114701   sqlite3Error(db, SQLITE_OK, 0);
   114702   sqlite3RegisterBuiltinFunctions(db);
   114703 
   114704   /* Load automatic extensions - extensions that have been registered
   114705   ** using the sqlite3_automatic_extension() API.
   114706   */
   114707   rc = sqlite3_errcode(db);
   114708   if( rc==SQLITE_OK ){
   114709     sqlite3AutoLoadExtensions(db);
   114710     rc = sqlite3_errcode(db);
   114711     if( rc!=SQLITE_OK ){
   114712       goto opendb_out;
   114713     }
   114714   }
   114715 
   114716 #ifdef SQLITE_ENABLE_FTS1
   114717   if( !db->mallocFailed ){
   114718     extern int sqlite3Fts1Init(sqlite3*);
   114719     rc = sqlite3Fts1Init(db);
   114720   }
   114721 #endif
   114722 
   114723 #ifdef SQLITE_ENABLE_FTS2
   114724   if( !db->mallocFailed && rc==SQLITE_OK ){
   114725     extern int sqlite3Fts2Init(sqlite3*);
   114726     rc = sqlite3Fts2Init(db);
   114727   }
   114728 #endif
   114729 
   114730 #ifdef SQLITE_ENABLE_FTS3
   114731   // Begin Android change
   114732   #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
   114733     /* Also register as fts1 and fts2, for backwards compatability on
   114734     ** systems known to have never seen a pre-fts3 database.
   114735     */
   114736     if( !db->mallocFailed && rc==SQLITE_OK ){
   114737       rc = sqlite3Fts3Init(db, "fts1");
   114738     }
   114739 
   114740     if( !db->mallocFailed && rc==SQLITE_OK ){
   114741       rc = sqlite3Fts3Init(db, "fts2");
   114742     }
   114743   #endif
   114744 
   114745     if( !db->mallocFailed && rc==SQLITE_OK ){
   114746       rc = sqlite3Fts3Init(db, "fts3");
   114747     }
   114748   // End Android change
   114749 #endif
   114750 
   114751 #ifdef SQLITE_ENABLE_ICU
   114752   if( !db->mallocFailed && rc==SQLITE_OK ){
   114753     rc = sqlite3IcuInit(db);
   114754   }
   114755 #endif
   114756 
   114757 #ifdef SQLITE_ENABLE_RTREE
   114758   if( !db->mallocFailed && rc==SQLITE_OK){
   114759     rc = sqlite3RtreeInit(db);
   114760   }
   114761 #endif
   114762 
   114763   sqlite3Error(db, rc, 0);
   114764 
   114765   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   114766   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   114767   ** mode.  Doing nothing at all also makes NORMAL the default.
   114768   */
   114769 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   114770   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   114771   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   114772                           SQLITE_DEFAULT_LOCKING_MODE);
   114773 #endif
   114774 
   114775   /* Enable the lookaside-malloc subsystem */
   114776   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   114777                         sqlite3GlobalConfig.nLookaside);
   114778 
   114779   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   114780 
   114781 opendb_out:
   114782   sqlite3_free(zOpen);
   114783   if( db ){
   114784     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   114785     sqlite3_mutex_leave(db->mutex);
   114786   }
   114787   rc = sqlite3_errcode(db);
   114788   assert( db!=0 || rc==SQLITE_NOMEM );
   114789   if( rc==SQLITE_NOMEM ){
   114790     sqlite3_close(db);
   114791     db = 0;
   114792   }else if( rc!=SQLITE_OK ){
   114793     db->magic = SQLITE_MAGIC_SICK;
   114794   }
   114795   *ppDb = db;
   114796   return sqlite3ApiExit(0, rc);
   114797 }
   114798 
   114799 /*
   114800 ** Open a new database handle.
   114801 */
   114802 SQLITE_API int sqlite3_open(
   114803   const char *zFilename,
   114804   sqlite3 **ppDb
   114805 ){
   114806   return openDatabase(zFilename, ppDb,
   114807                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   114808 }
   114809 SQLITE_API int sqlite3_open_v2(
   114810   const char *filename,   /* Database filename (UTF-8) */
   114811   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   114812   int flags,              /* Flags */
   114813   const char *zVfs        /* Name of VFS module to use */
   114814 ){
   114815   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
   114816 }
   114817 
   114818 #ifndef SQLITE_OMIT_UTF16
   114819 /*
   114820 ** Open a new database handle.
   114821 */
   114822 SQLITE_API int sqlite3_open16(
   114823   const void *zFilename,
   114824   sqlite3 **ppDb
   114825 ){
   114826   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   114827   sqlite3_value *pVal;
   114828   int rc;
   114829 
   114830   assert( zFilename );
   114831   assert( ppDb );
   114832   *ppDb = 0;
   114833 #ifndef SQLITE_OMIT_AUTOINIT
   114834   rc = sqlite3_initialize();
   114835   if( rc ) return rc;
   114836 #endif
   114837   pVal = sqlite3ValueNew(0);
   114838   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   114839   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   114840   if( zFilename8 ){
   114841     rc = openDatabase(zFilename8, ppDb,
   114842                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   114843     assert( *ppDb || rc==SQLITE_NOMEM );
   114844     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   114845       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   114846     }
   114847   }else{
   114848     rc = SQLITE_NOMEM;
   114849   }
   114850   sqlite3ValueFree(pVal);
   114851 
   114852   return sqlite3ApiExit(0, rc);
   114853 }
   114854 #endif /* SQLITE_OMIT_UTF16 */
   114855 
   114856 /*
   114857 ** Register a new collation sequence with the database handle db.
   114858 */
   114859 SQLITE_API int sqlite3_create_collation(
   114860   sqlite3* db,
   114861   const char *zName,
   114862   int enc,
   114863   void* pCtx,
   114864   int(*xCompare)(void*,int,const void*,int,const void*)
   114865 ){
   114866   int rc;
   114867   sqlite3_mutex_enter(db->mutex);
   114868   assert( !db->mallocFailed );
   114869   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
   114870   rc = sqlite3ApiExit(db, rc);
   114871   sqlite3_mutex_leave(db->mutex);
   114872   return rc;
   114873 }
   114874 
   114875 /*
   114876 ** Register a new collation sequence with the database handle db.
   114877 */
   114878 SQLITE_API int sqlite3_create_collation_v2(
   114879   sqlite3* db,
   114880   const char *zName,
   114881   int enc,
   114882   void* pCtx,
   114883   int(*xCompare)(void*,int,const void*,int,const void*),
   114884   void(*xDel)(void*)
   114885 ){
   114886   int rc;
   114887   sqlite3_mutex_enter(db->mutex);
   114888   assert( !db->mallocFailed );
   114889   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
   114890   rc = sqlite3ApiExit(db, rc);
   114891   sqlite3_mutex_leave(db->mutex);
   114892   return rc;
   114893 }
   114894 
   114895 #ifndef SQLITE_OMIT_UTF16
   114896 /*
   114897 ** Register a new collation sequence with the database handle db.
   114898 */
   114899 SQLITE_API int sqlite3_create_collation16(
   114900   sqlite3* db,
   114901   const void *zName,
   114902   int enc,
   114903   void* pCtx,
   114904   int(*xCompare)(void*,int,const void*,int,const void*)
   114905 ){
   114906   int rc = SQLITE_OK;
   114907   char *zName8;
   114908   sqlite3_mutex_enter(db->mutex);
   114909   assert( !db->mallocFailed );
   114910   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   114911   if( zName8 ){
   114912     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
   114913     sqlite3DbFree(db, zName8);
   114914   }
   114915   rc = sqlite3ApiExit(db, rc);
   114916   sqlite3_mutex_leave(db->mutex);
   114917   return rc;
   114918 }
   114919 #endif /* SQLITE_OMIT_UTF16 */
   114920 
   114921 /*
   114922 ** Register a collation sequence factory callback with the database handle
   114923 ** db. Replace any previously installed collation sequence factory.
   114924 */
   114925 SQLITE_API int sqlite3_collation_needed(
   114926   sqlite3 *db,
   114927   void *pCollNeededArg,
   114928   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   114929 ){
   114930   sqlite3_mutex_enter(db->mutex);
   114931   db->xCollNeeded = xCollNeeded;
   114932   db->xCollNeeded16 = 0;
   114933   db->pCollNeededArg = pCollNeededArg;
   114934   sqlite3_mutex_leave(db->mutex);
   114935   return SQLITE_OK;
   114936 }
   114937 
   114938 #ifndef SQLITE_OMIT_UTF16
   114939 /*
   114940 ** Register a collation sequence factory callback with the database handle
   114941 ** db. Replace any previously installed collation sequence factory.
   114942 */
   114943 SQLITE_API int sqlite3_collation_needed16(
   114944   sqlite3 *db,
   114945   void *pCollNeededArg,
   114946   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   114947 ){
   114948   sqlite3_mutex_enter(db->mutex);
   114949   db->xCollNeeded = 0;
   114950   db->xCollNeeded16 = xCollNeeded16;
   114951   db->pCollNeededArg = pCollNeededArg;
   114952   sqlite3_mutex_leave(db->mutex);
   114953   return SQLITE_OK;
   114954 }
   114955 #endif /* SQLITE_OMIT_UTF16 */
   114956 
   114957 #ifndef SQLITE_OMIT_DEPRECATED
   114958 /*
   114959 ** This function is now an anachronism. It used to be used to recover from a
   114960 ** malloc() failure, but SQLite now does this automatically.
   114961 */
   114962 SQLITE_API int sqlite3_global_recover(void){
   114963   return SQLITE_OK;
   114964 }
   114965 #endif
   114966 
   114967 /*
   114968 ** Test to see whether or not the database connection is in autocommit
   114969 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   114970 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   114971 ** by the next COMMIT or ROLLBACK.
   114972 **
   114973 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
   114974 */
   114975 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   114976   return db->autoCommit;
   114977 }
   114978 
   114979 /*
   114980 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   114981 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   114982 ** constants.  They server two purposes:
   114983 **
   114984 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   114985 **       to detect when version error conditions occurs.
   114986 **
   114987 **   2.  Invoke sqlite3_log() to provide the source code location where
   114988 **       a low-level error is first detected.
   114989 */
   114990 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   114991   testcase( sqlite3GlobalConfig.xLog!=0 );
   114992   sqlite3_log(SQLITE_CORRUPT,
   114993               "database corruption at line %d of [%.10s]",
   114994               lineno, 20+sqlite3_sourceid());
   114995   return SQLITE_CORRUPT;
   114996 }
   114997 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   114998   testcase( sqlite3GlobalConfig.xLog!=0 );
   114999   sqlite3_log(SQLITE_MISUSE,
   115000               "misuse at line %d of [%.10s]",
   115001               lineno, 20+sqlite3_sourceid());
   115002   return SQLITE_MISUSE;
   115003 }
   115004 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   115005   testcase( sqlite3GlobalConfig.xLog!=0 );
   115006   sqlite3_log(SQLITE_CANTOPEN,
   115007               "cannot open file at line %d of [%.10s]",
   115008               lineno, 20+sqlite3_sourceid());
   115009   return SQLITE_CANTOPEN;
   115010 }
   115011 
   115012 
   115013 #ifndef SQLITE_OMIT_DEPRECATED
   115014 /*
   115015 ** This is a convenience routine that makes sure that all thread-specific
   115016 ** data for this thread has been deallocated.
   115017 **
   115018 ** SQLite no longer uses thread-specific data so this routine is now a
   115019 ** no-op.  It is retained for historical compatibility.
   115020 */
   115021 SQLITE_API void sqlite3_thread_cleanup(void){
   115022 }
   115023 #endif
   115024 
   115025 /*
   115026 ** Return meta information about a specific column of a database table.
   115027 ** See comment in sqlite3.h (sqlite.h.in) for details.
   115028 */
   115029 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   115030 SQLITE_API int sqlite3_table_column_metadata(
   115031   sqlite3 *db,                /* Connection handle */
   115032   const char *zDbName,        /* Database name or NULL */
   115033   const char *zTableName,     /* Table name */
   115034   const char *zColumnName,    /* Column name */
   115035   char const **pzDataType,    /* OUTPUT: Declared data type */
   115036   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   115037   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   115038   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   115039   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   115040 ){
   115041   int rc;
   115042   char *zErrMsg = 0;
   115043   Table *pTab = 0;
   115044   Column *pCol = 0;
   115045   int iCol;
   115046 
   115047   char const *zDataType = 0;
   115048   char const *zCollSeq = 0;
   115049   int notnull = 0;
   115050   int primarykey = 0;
   115051   int autoinc = 0;
   115052 
   115053   /* Ensure the database schema has been loaded */
   115054   sqlite3_mutex_enter(db->mutex);
   115055   sqlite3BtreeEnterAll(db);
   115056   rc = sqlite3Init(db, &zErrMsg);
   115057   if( SQLITE_OK!=rc ){
   115058     goto error_out;
   115059   }
   115060 
   115061   /* Locate the table in question */
   115062   pTab = sqlite3FindTable(db, zTableName, zDbName);
   115063   if( !pTab || pTab->pSelect ){
   115064     pTab = 0;
   115065     goto error_out;
   115066   }
   115067 
   115068   /* Find the column for which info is requested */
   115069   if( sqlite3IsRowid(zColumnName) ){
   115070     iCol = pTab->iPKey;
   115071     if( iCol>=0 ){
   115072       pCol = &pTab->aCol[iCol];
   115073     }
   115074   }else{
   115075     for(iCol=0; iCol<pTab->nCol; iCol++){
   115076       pCol = &pTab->aCol[iCol];
   115077       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   115078         break;
   115079       }
   115080     }
   115081     if( iCol==pTab->nCol ){
   115082       pTab = 0;
   115083       goto error_out;
   115084     }
   115085   }
   115086 
   115087   /* The following block stores the meta information that will be returned
   115088   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   115089   ** and autoinc. At this point there are two possibilities:
   115090   **
   115091   **     1. The specified column name was rowid", "oid" or "_rowid_"
   115092   **        and there is no explicitly declared IPK column.
   115093   **
   115094   **     2. The table is not a view and the column name identified an
   115095   **        explicitly declared column. Copy meta information from *pCol.
   115096   */
   115097   if( pCol ){
   115098     zDataType = pCol->zType;
   115099     zCollSeq = pCol->zColl;
   115100     notnull = pCol->notNull!=0;
   115101     primarykey  = pCol->isPrimKey!=0;
   115102     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   115103   }else{
   115104     zDataType = "INTEGER";
   115105     primarykey = 1;
   115106   }
   115107   if( !zCollSeq ){
   115108     zCollSeq = "BINARY";
   115109   }
   115110 
   115111 error_out:
   115112   sqlite3BtreeLeaveAll(db);
   115113 
   115114   /* Whether the function call succeeded or failed, set the output parameters
   115115   ** to whatever their local counterparts contain. If an error did occur,
   115116   ** this has the effect of zeroing all output parameters.
   115117   */
   115118   if( pzDataType ) *pzDataType = zDataType;
   115119   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   115120   if( pNotNull ) *pNotNull = notnull;
   115121   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   115122   if( pAutoinc ) *pAutoinc = autoinc;
   115123 
   115124   if( SQLITE_OK==rc && !pTab ){
   115125     sqlite3DbFree(db, zErrMsg);
   115126     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   115127         zColumnName);
   115128     rc = SQLITE_ERROR;
   115129   }
   115130   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   115131   sqlite3DbFree(db, zErrMsg);
   115132   rc = sqlite3ApiExit(db, rc);
   115133   sqlite3_mutex_leave(db->mutex);
   115134   return rc;
   115135 }
   115136 #endif
   115137 
   115138 /*
   115139 ** Sleep for a little while.  Return the amount of time slept.
   115140 */
   115141 SQLITE_API int sqlite3_sleep(int ms){
   115142   sqlite3_vfs *pVfs;
   115143   int rc;
   115144   pVfs = sqlite3_vfs_find(0);
   115145   if( pVfs==0 ) return 0;
   115146 
   115147   /* This function works in milliseconds, but the underlying OsSleep()
   115148   ** API uses microseconds. Hence the 1000's.
   115149   */
   115150   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   115151   return rc;
   115152 }
   115153 
   115154 /*
   115155 ** Enable or disable the extended result codes.
   115156 */
   115157 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   115158   sqlite3_mutex_enter(db->mutex);
   115159   db->errMask = onoff ? 0xffffffff : 0xff;
   115160   sqlite3_mutex_leave(db->mutex);
   115161   return SQLITE_OK;
   115162 }
   115163 
   115164 /*
   115165 ** Invoke the xFileControl method on a particular database.
   115166 */
   115167 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   115168   int rc = SQLITE_ERROR;
   115169   Btree *pBtree;
   115170 
   115171   sqlite3_mutex_enter(db->mutex);
   115172   pBtree = sqlite3DbNameToBtree(db, zDbName);
   115173   if( pBtree ){
   115174     Pager *pPager;
   115175     sqlite3_file *fd;
   115176     sqlite3BtreeEnter(pBtree);
   115177     pPager = sqlite3BtreePager(pBtree);
   115178     assert( pPager!=0 );
   115179     fd = sqlite3PagerFile(pPager);
   115180     assert( fd!=0 );
   115181     if( op==SQLITE_FCNTL_FILE_POINTER ){
   115182       *(sqlite3_file**)pArg = fd;
   115183       rc = SQLITE_OK;
   115184     }else if( fd->pMethods ){
   115185       rc = sqlite3OsFileControl(fd, op, pArg);
   115186     }else{
   115187       rc = SQLITE_NOTFOUND;
   115188     }
   115189     sqlite3BtreeLeave(pBtree);
   115190   }
   115191   sqlite3_mutex_leave(db->mutex);
   115192   return rc;
   115193 }
   115194 
   115195 /*
   115196 ** Interface to the testing logic.
   115197 */
   115198 SQLITE_API int sqlite3_test_control(int op, ...){
   115199   int rc = 0;
   115200 #ifndef SQLITE_OMIT_BUILTIN_TEST
   115201   va_list ap;
   115202   va_start(ap, op);
   115203   switch( op ){
   115204 
   115205     /*
   115206     ** Save the current state of the PRNG.
   115207     */
   115208     case SQLITE_TESTCTRL_PRNG_SAVE: {
   115209       sqlite3PrngSaveState();
   115210       break;
   115211     }
   115212 
   115213     /*
   115214     ** Restore the state of the PRNG to the last state saved using
   115215     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   115216     ** this verb acts like PRNG_RESET.
   115217     */
   115218     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   115219       sqlite3PrngRestoreState();
   115220       break;
   115221     }
   115222 
   115223     /*
   115224     ** Reset the PRNG back to its uninitialized state.  The next call
   115225     ** to sqlite3_randomness() will reseed the PRNG using a single call
   115226     ** to the xRandomness method of the default VFS.
   115227     */
   115228     case SQLITE_TESTCTRL_PRNG_RESET: {
   115229       sqlite3PrngResetState();
   115230       break;
   115231     }
   115232 
   115233     /*
   115234     **  sqlite3_test_control(BITVEC_TEST, size, program)
   115235     **
   115236     ** Run a test against a Bitvec object of size.  The program argument
   115237     ** is an array of integers that defines the test.  Return -1 on a
   115238     ** memory allocation error, 0 on success, or non-zero for an error.
   115239     ** See the sqlite3BitvecBuiltinTest() for additional information.
   115240     */
   115241     case SQLITE_TESTCTRL_BITVEC_TEST: {
   115242       int sz = va_arg(ap, int);
   115243       int *aProg = va_arg(ap, int*);
   115244       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   115245       break;
   115246     }
   115247 
   115248     /*
   115249     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   115250     **
   115251     ** Register hooks to call to indicate which malloc() failures
   115252     ** are benign.
   115253     */
   115254     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   115255       typedef void (*void_function)(void);
   115256       void_function xBenignBegin;
   115257       void_function xBenignEnd;
   115258       xBenignBegin = va_arg(ap, void_function);
   115259       xBenignEnd = va_arg(ap, void_function);
   115260       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   115261       break;
   115262     }
   115263 
   115264     /*
   115265     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   115266     **
   115267     ** Set the PENDING byte to the value in the argument, if X>0.
   115268     ** Make no changes if X==0.  Return the value of the pending byte
   115269     ** as it existing before this routine was called.
   115270     **
   115271     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   115272     ** an incompatible database file format.  Changing the PENDING byte
   115273     ** while any database connection is open results in undefined and
   115274     ** dileterious behavior.
   115275     */
   115276     case SQLITE_TESTCTRL_PENDING_BYTE: {
   115277       rc = PENDING_BYTE;
   115278 #ifndef SQLITE_OMIT_WSD
   115279       {
   115280         unsigned int newVal = va_arg(ap, unsigned int);
   115281         if( newVal ) sqlite3PendingByte = newVal;
   115282       }
   115283 #endif
   115284       break;
   115285     }
   115286 
   115287     /*
   115288     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   115289     **
   115290     ** This action provides a run-time test to see whether or not
   115291     ** assert() was enabled at compile-time.  If X is true and assert()
   115292     ** is enabled, then the return value is true.  If X is true and
   115293     ** assert() is disabled, then the return value is zero.  If X is
   115294     ** false and assert() is enabled, then the assertion fires and the
   115295     ** process aborts.  If X is false and assert() is disabled, then the
   115296     ** return value is zero.
   115297     */
   115298     case SQLITE_TESTCTRL_ASSERT: {
   115299       volatile int x = 0;
   115300       assert( (x = va_arg(ap,int))!=0 );
   115301       rc = x;
   115302       break;
   115303     }
   115304 
   115305 
   115306     /*
   115307     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   115308     **
   115309     ** This action provides a run-time test to see how the ALWAYS and
   115310     ** NEVER macros were defined at compile-time.
   115311     **
   115312     ** The return value is ALWAYS(X).
   115313     **
   115314     ** The recommended test is X==2.  If the return value is 2, that means
   115315     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   115316     ** default setting.  If the return value is 1, then ALWAYS() is either
   115317     ** hard-coded to true or else it asserts if its argument is false.
   115318     ** The first behavior (hard-coded to true) is the case if
   115319     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   115320     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   115321     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   115322     **
   115323     ** The run-time test procedure might look something like this:
   115324     **
   115325     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   115326     **      // ALWAYS() and NEVER() are no-op pass-through macros
   115327     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   115328     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   115329     **    }else{
   115330     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   115331     **    }
   115332     */
   115333     case SQLITE_TESTCTRL_ALWAYS: {
   115334       int x = va_arg(ap,int);
   115335       rc = ALWAYS(x);
   115336       break;
   115337     }
   115338 
   115339     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   115340     **
   115341     ** Set the nReserve size to N for the main database on the database
   115342     ** connection db.
   115343     */
   115344     case SQLITE_TESTCTRL_RESERVE: {
   115345       sqlite3 *db = va_arg(ap, sqlite3*);
   115346       int x = va_arg(ap,int);
   115347       sqlite3_mutex_enter(db->mutex);
   115348       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   115349       sqlite3_mutex_leave(db->mutex);
   115350       break;
   115351     }
   115352 
   115353     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   115354     **
   115355     ** Enable or disable various optimizations for testing purposes.  The
   115356     ** argument N is a bitmask of optimizations to be disabled.  For normal
   115357     ** operation N should be 0.  The idea is that a test program (like the
   115358     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   115359     ** with various optimizations disabled to verify that the same answer
   115360     ** is obtained in every case.
   115361     */
   115362     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   115363       sqlite3 *db = va_arg(ap, sqlite3*);
   115364       int x = va_arg(ap,int);
   115365       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
   115366       break;
   115367     }
   115368 
   115369 #ifdef SQLITE_N_KEYWORD
   115370     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   115371     **
   115372     ** If zWord is a keyword recognized by the parser, then return the
   115373     ** number of keywords.  Or if zWord is not a keyword, return 0.
   115374     **
   115375     ** This test feature is only available in the amalgamation since
   115376     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   115377     ** is built using separate source files.
   115378     */
   115379     case SQLITE_TESTCTRL_ISKEYWORD: {
   115380       const char *zWord = va_arg(ap, const char*);
   115381       int n = sqlite3Strlen30(zWord);
   115382       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   115383       break;
   115384     }
   115385 #endif
   115386 
   115387     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   115388     **
   115389     ** Pass pFree into sqlite3ScratchFree().
   115390     ** If sz>0 then allocate a scratch buffer into pNew.
   115391     */
   115392     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   115393       void *pFree, **ppNew;
   115394       int sz;
   115395       sz = va_arg(ap, int);
   115396       ppNew = va_arg(ap, void**);
   115397       pFree = va_arg(ap, void*);
   115398       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   115399       sqlite3ScratchFree(pFree);
   115400       break;
   115401     }
   115402 
   115403     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
   115404     **
   115405     ** If parameter onoff is non-zero, configure the wrappers so that all
   115406     ** subsequent calls to localtime() and variants fail. If onoff is zero,
   115407     ** undo this setting.
   115408     */
   115409     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
   115410       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
   115411       break;
   115412     }
   115413 
   115414 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
   115415     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
   115416     **                        sqlite3_stmt*,const char**);
   115417     **
   115418     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
   115419     ** a string that describes the optimized parse tree.  This test-control
   115420     ** returns a pointer to that string.
   115421     */
   115422     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
   115423       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
   115424       const char **pzRet = va_arg(ap, const char**);
   115425       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
   115426       break;
   115427     }
   115428 #endif
   115429 
   115430   }
   115431   va_end(ap);
   115432 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   115433   return rc;
   115434 }
   115435 
   115436 /*
   115437 ** This is a utility routine, useful to VFS implementations, that checks
   115438 ** to see if a database file was a URI that contained a specific query
   115439 ** parameter, and if so obtains the value of the query parameter.
   115440 **
   115441 ** The zFilename argument is the filename pointer passed into the xOpen()
   115442 ** method of a VFS implementation.  The zParam argument is the name of the
   115443 ** query parameter we seek.  This routine returns the value of the zParam
   115444 ** parameter if it exists.  If the parameter does not exist, this routine
   115445 ** returns a NULL pointer.
   115446 */
   115447 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   115448   if( zFilename==0 ) return 0;
   115449   zFilename += sqlite3Strlen30(zFilename) + 1;
   115450   while( zFilename[0] ){
   115451     int x = strcmp(zFilename, zParam);
   115452     zFilename += sqlite3Strlen30(zFilename) + 1;
   115453     if( x==0 ) return zFilename;
   115454     zFilename += sqlite3Strlen30(zFilename) + 1;
   115455   }
   115456   return 0;
   115457 }
   115458 
   115459 /*
   115460 ** Return a boolean value for a query parameter.
   115461 */
   115462 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
   115463   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   115464   bDflt = bDflt!=0;
   115465   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
   115466 }
   115467 
   115468 /*
   115469 ** Return a 64-bit integer value for a query parameter.
   115470 */
   115471 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
   115472   const char *zFilename,    /* Filename as passed to xOpen */
   115473   const char *zParam,       /* URI parameter sought */
   115474   sqlite3_int64 bDflt       /* return if parameter is missing */
   115475 ){
   115476   const char *z = sqlite3_uri_parameter(zFilename, zParam);
   115477   sqlite3_int64 v;
   115478   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
   115479     bDflt = v;
   115480   }
   115481   return bDflt;
   115482 }
   115483 
   115484 /*
   115485 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
   115486 */
   115487 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
   115488   int i;
   115489   for(i=0; i<db->nDb; i++){
   115490     if( db->aDb[i].pBt
   115491      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
   115492     ){
   115493       return db->aDb[i].pBt;
   115494     }
   115495   }
   115496   return 0;
   115497 }
   115498 
   115499 /*
   115500 ** Return the filename of the database associated with a database
   115501 ** connection.
   115502 */
   115503 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
   115504   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   115505   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
   115506 }
   115507 
   115508 /*
   115509 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
   115510 ** no such database exists.
   115511 */
   115512 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
   115513   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
   115514   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
   115515 }
   115516 
   115517 /************** End of main.c ************************************************/
   115518 /************** Begin file notify.c ******************************************/
   115519 /*
   115520 ** 2009 March 3
   115521 **
   115522 ** The author disclaims copyright to this source code.  In place of
   115523 ** a legal notice, here is a blessing:
   115524 **
   115525 **    May you do good and not evil.
   115526 **    May you find forgiveness for yourself and forgive others.
   115527 **    May you share freely, never taking more than you give.
   115528 **
   115529 *************************************************************************
   115530 **
   115531 ** This file contains the implementation of the sqlite3_unlock_notify()
   115532 ** API method and its associated functionality.
   115533 */
   115534 
   115535 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   115536 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   115537 
   115538 /*
   115539 ** Public interfaces:
   115540 **
   115541 **   sqlite3ConnectionBlocked()
   115542 **   sqlite3ConnectionUnlocked()
   115543 **   sqlite3ConnectionClosed()
   115544 **   sqlite3_unlock_notify()
   115545 */
   115546 
   115547 #define assertMutexHeld() \
   115548   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   115549 
   115550 /*
   115551 ** Head of a linked list of all sqlite3 objects created by this process
   115552 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   115553 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   115554 ** mutex is held.
   115555 */
   115556 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   115557 
   115558 #ifndef NDEBUG
   115559 /*
   115560 ** This function is a complex assert() that verifies the following
   115561 ** properties of the blocked connections list:
   115562 **
   115563 **   1) Each entry in the list has a non-NULL value for either
   115564 **      pUnlockConnection or pBlockingConnection, or both.
   115565 **
   115566 **   2) All entries in the list that share a common value for
   115567 **      xUnlockNotify are grouped together.
   115568 **
   115569 **   3) If the argument db is not NULL, then none of the entries in the
   115570 **      blocked connections list have pUnlockConnection or pBlockingConnection
   115571 **      set to db. This is used when closing connection db.
   115572 */
   115573 static void checkListProperties(sqlite3 *db){
   115574   sqlite3 *p;
   115575   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   115576     int seen = 0;
   115577     sqlite3 *p2;
   115578 
   115579     /* Verify property (1) */
   115580     assert( p->pUnlockConnection || p->pBlockingConnection );
   115581 
   115582     /* Verify property (2) */
   115583     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   115584       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   115585       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   115586       assert( db==0 || p->pUnlockConnection!=db );
   115587       assert( db==0 || p->pBlockingConnection!=db );
   115588     }
   115589   }
   115590 }
   115591 #else
   115592 # define checkListProperties(x)
   115593 #endif
   115594 
   115595 /*
   115596 ** Remove connection db from the blocked connections list. If connection
   115597 ** db is not currently a part of the list, this function is a no-op.
   115598 */
   115599 static void removeFromBlockedList(sqlite3 *db){
   115600   sqlite3 **pp;
   115601   assertMutexHeld();
   115602   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   115603     if( *pp==db ){
   115604       *pp = (*pp)->pNextBlocked;
   115605       break;
   115606     }
   115607   }
   115608 }
   115609 
   115610 /*
   115611 ** Add connection db to the blocked connections list. It is assumed
   115612 ** that it is not already a part of the list.
   115613 */
   115614 static void addToBlockedList(sqlite3 *db){
   115615   sqlite3 **pp;
   115616   assertMutexHeld();
   115617   for(
   115618     pp=&sqlite3BlockedList;
   115619     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   115620     pp=&(*pp)->pNextBlocked
   115621   );
   115622   db->pNextBlocked = *pp;
   115623   *pp = db;
   115624 }
   115625 
   115626 /*
   115627 ** Obtain the STATIC_MASTER mutex.
   115628 */
   115629 static void enterMutex(void){
   115630   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   115631   checkListProperties(0);
   115632 }
   115633 
   115634 /*
   115635 ** Release the STATIC_MASTER mutex.
   115636 */
   115637 static void leaveMutex(void){
   115638   assertMutexHeld();
   115639   checkListProperties(0);
   115640   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   115641 }
   115642 
   115643 /*
   115644 ** Register an unlock-notify callback.
   115645 **
   115646 ** This is called after connection "db" has attempted some operation
   115647 ** but has received an SQLITE_LOCKED error because another connection
   115648 ** (call it pOther) in the same process was busy using the same shared
   115649 ** cache.  pOther is found by looking at db->pBlockingConnection.
   115650 **
   115651 ** If there is no blocking connection, the callback is invoked immediately,
   115652 ** before this routine returns.
   115653 **
   115654 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   115655 ** a deadlock.
   115656 **
   115657 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   115658 ** its locks.
   115659 **
   115660 ** Each call to this routine overrides any prior callbacks registered
   115661 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   115662 ** cancelled.
   115663 */
   115664 SQLITE_API int sqlite3_unlock_notify(
   115665   sqlite3 *db,
   115666   void (*xNotify)(void **, int),
   115667   void *pArg
   115668 ){
   115669   int rc = SQLITE_OK;
   115670 
   115671   sqlite3_mutex_enter(db->mutex);
   115672   enterMutex();
   115673 
   115674   if( xNotify==0 ){
   115675     removeFromBlockedList(db);
   115676     db->pBlockingConnection = 0;
   115677     db->pUnlockConnection = 0;
   115678     db->xUnlockNotify = 0;
   115679     db->pUnlockArg = 0;
   115680   }else if( 0==db->pBlockingConnection ){
   115681     /* The blocking transaction has been concluded. Or there never was a
   115682     ** blocking transaction. In either case, invoke the notify callback
   115683     ** immediately.
   115684     */
   115685     xNotify(&pArg, 1);
   115686   }else{
   115687     sqlite3 *p;
   115688 
   115689     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   115690     if( p ){
   115691       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   115692     }else{
   115693       db->pUnlockConnection = db->pBlockingConnection;
   115694       db->xUnlockNotify = xNotify;
   115695       db->pUnlockArg = pArg;
   115696       removeFromBlockedList(db);
   115697       addToBlockedList(db);
   115698     }
   115699   }
   115700 
   115701   leaveMutex();
   115702   assert( !db->mallocFailed );
   115703   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   115704   sqlite3_mutex_leave(db->mutex);
   115705   return rc;
   115706 }
   115707 
   115708 /*
   115709 ** This function is called while stepping or preparing a statement
   115710 ** associated with connection db. The operation will return SQLITE_LOCKED
   115711 ** to the user because it requires a lock that will not be available
   115712 ** until connection pBlocker concludes its current transaction.
   115713 */
   115714 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   115715   enterMutex();
   115716   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   115717     addToBlockedList(db);
   115718   }
   115719   db->pBlockingConnection = pBlocker;
   115720   leaveMutex();
   115721 }
   115722 
   115723 /*
   115724 ** This function is called when
   115725 ** the transaction opened by database db has just finished. Locks held
   115726 ** by database connection db have been released.
   115727 **
   115728 ** This function loops through each entry in the blocked connections
   115729 ** list and does the following:
   115730 **
   115731 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   115732 **      set to db, then set pBlockingConnection=0.
   115733 **
   115734 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   115735 **      set to db, then invoke the configured unlock-notify callback and
   115736 **      set pUnlockConnection=0.
   115737 **
   115738 **   3) If the two steps above mean that pBlockingConnection==0 and
   115739 **      pUnlockConnection==0, remove the entry from the blocked connections
   115740 **      list.
   115741 */
   115742 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   115743   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   115744   int nArg = 0;                            /* Number of entries in aArg[] */
   115745   sqlite3 **pp;                            /* Iterator variable */
   115746   void **aArg;               /* Arguments to the unlock callback */
   115747   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   115748   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   115749 
   115750   aArg = aStatic;
   115751   enterMutex();         /* Enter STATIC_MASTER mutex */
   115752 
   115753   /* This loop runs once for each entry in the blocked-connections list. */
   115754   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   115755     sqlite3 *p = *pp;
   115756 
   115757     /* Step 1. */
   115758     if( p->pBlockingConnection==db ){
   115759       p->pBlockingConnection = 0;
   115760     }
   115761 
   115762     /* Step 2. */
   115763     if( p->pUnlockConnection==db ){
   115764       assert( p->xUnlockNotify );
   115765       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   115766         xUnlockNotify(aArg, nArg);
   115767         nArg = 0;
   115768       }
   115769 
   115770       sqlite3BeginBenignMalloc();
   115771       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   115772       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   115773       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   115774        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   115775       ){
   115776         /* The aArg[] array needs to grow. */
   115777         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   115778         if( pNew ){
   115779           memcpy(pNew, aArg, nArg*sizeof(void *));
   115780           sqlite3_free(aDyn);
   115781           aDyn = aArg = pNew;
   115782         }else{
   115783           /* This occurs when the array of context pointers that need to
   115784           ** be passed to the unlock-notify callback is larger than the
   115785           ** aStatic[] array allocated on the stack and the attempt to
   115786           ** allocate a larger array from the heap has failed.
   115787           **
   115788           ** This is a difficult situation to handle. Returning an error
   115789           ** code to the caller is insufficient, as even if an error code
   115790           ** is returned the transaction on connection db will still be
   115791           ** closed and the unlock-notify callbacks on blocked connections
   115792           ** will go unissued. This might cause the application to wait
   115793           ** indefinitely for an unlock-notify callback that will never
   115794           ** arrive.
   115795           **
   115796           ** Instead, invoke the unlock-notify callback with the context
   115797           ** array already accumulated. We can then clear the array and
   115798           ** begin accumulating any further context pointers without
   115799           ** requiring any dynamic allocation. This is sub-optimal because
   115800           ** it means that instead of one callback with a large array of
   115801           ** context pointers the application will receive two or more
   115802           ** callbacks with smaller arrays of context pointers, which will
   115803           ** reduce the applications ability to prioritize multiple
   115804           ** connections. But it is the best that can be done under the
   115805           ** circumstances.
   115806           */
   115807           xUnlockNotify(aArg, nArg);
   115808           nArg = 0;
   115809         }
   115810       }
   115811       sqlite3EndBenignMalloc();
   115812 
   115813       aArg[nArg++] = p->pUnlockArg;
   115814       xUnlockNotify = p->xUnlockNotify;
   115815       p->pUnlockConnection = 0;
   115816       p->xUnlockNotify = 0;
   115817       p->pUnlockArg = 0;
   115818     }
   115819 
   115820     /* Step 3. */
   115821     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   115822       /* Remove connection p from the blocked connections list. */
   115823       *pp = p->pNextBlocked;
   115824       p->pNextBlocked = 0;
   115825     }else{
   115826       pp = &p->pNextBlocked;
   115827     }
   115828   }
   115829 
   115830   if( nArg!=0 ){
   115831     xUnlockNotify(aArg, nArg);
   115832   }
   115833   sqlite3_free(aDyn);
   115834   leaveMutex();         /* Leave STATIC_MASTER mutex */
   115835 }
   115836 
   115837 /*
   115838 ** This is called when the database connection passed as an argument is
   115839 ** being closed. The connection is removed from the blocked list.
   115840 */
   115841 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   115842   sqlite3ConnectionUnlocked(db);
   115843   enterMutex();
   115844   removeFromBlockedList(db);
   115845   checkListProperties(db);
   115846   leaveMutex();
   115847 }
   115848 #endif
   115849 
   115850 /************** End of notify.c **********************************************/
   115851 /************** Begin file fts3.c ********************************************/
   115852 /*
   115853 ** 2006 Oct 10
   115854 **
   115855 ** The author disclaims copyright to this source code.  In place of
   115856 ** a legal notice, here is a blessing:
   115857 **
   115858 **    May you do good and not evil.
   115859 **    May you find forgiveness for yourself and forgive others.
   115860 **    May you share freely, never taking more than you give.
   115861 **
   115862 ******************************************************************************
   115863 **
   115864 ** This is an SQLite module implementing full-text search.
   115865 */
   115866 
   115867 /*
   115868 ** The code in this file is only compiled if:
   115869 **
   115870 **     * The FTS3 module is being built as an extension
   115871 **       (in which case SQLITE_CORE is not defined), or
   115872 **
   115873 **     * The FTS3 module is being built into the core of
   115874 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   115875 */
   115876 
   115877 /* The full-text index is stored in a series of b+tree (-like)
   115878 ** structures called segments which map terms to doclists.  The
   115879 ** structures are like b+trees in layout, but are constructed from the
   115880 ** bottom up in optimal fashion and are not updatable.  Since trees
   115881 ** are built from the bottom up, things will be described from the
   115882 ** bottom up.
   115883 **
   115884 **
   115885 **** Varints ****
   115886 ** The basic unit of encoding is a variable-length integer called a
   115887 ** varint.  We encode variable-length integers in little-endian order
   115888 ** using seven bits * per byte as follows:
   115889 **
   115890 ** KEY:
   115891 **         A = 0xxxxxxx    7 bits of data and one flag bit
   115892 **         B = 1xxxxxxx    7 bits of data and one flag bit
   115893 **
   115894 **  7 bits - A
   115895 ** 14 bits - BA
   115896 ** 21 bits - BBA
   115897 ** and so on.
   115898 **
   115899 ** This is similar in concept to how sqlite encodes "varints" but
   115900 ** the encoding is not the same.  SQLite varints are big-endian
   115901 ** are are limited to 9 bytes in length whereas FTS3 varints are
   115902 ** little-endian and can be up to 10 bytes in length (in theory).
   115903 **
   115904 ** Example encodings:
   115905 **
   115906 **     1:    0x01
   115907 **   127:    0x7f
   115908 **   128:    0x81 0x00
   115909 **
   115910 **
   115911 **** Document lists ****
   115912 ** A doclist (document list) holds a docid-sorted list of hits for a
   115913 ** given term.  Doclists hold docids and associated token positions.
   115914 ** A docid is the unique integer identifier for a single document.
   115915 ** A position is the index of a word within the document.  The first
   115916 ** word of the document has a position of 0.
   115917 **
   115918 ** FTS3 used to optionally store character offsets using a compile-time
   115919 ** option.  But that functionality is no longer supported.
   115920 **
   115921 ** A doclist is stored like this:
   115922 **
   115923 ** array {
   115924 **   varint docid;
   115925 **   array {                (position list for column 0)
   115926 **     varint position;     (2 more than the delta from previous position)
   115927 **   }
   115928 **   array {
   115929 **     varint POS_COLUMN;   (marks start of position list for new column)
   115930 **     varint column;       (index of new column)
   115931 **     array {
   115932 **       varint position;   (2 more than the delta from previous position)
   115933 **     }
   115934 **   }
   115935 **   varint POS_END;        (marks end of positions for this document.
   115936 ** }
   115937 **
   115938 ** Here, array { X } means zero or more occurrences of X, adjacent in
   115939 ** memory.  A "position" is an index of a token in the token stream
   115940 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   115941 ** in the same logical place as the position element, and act as sentinals
   115942 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   115943 ** The positions numbers are not stored literally but rather as two more
   115944 ** than the difference from the prior position, or the just the position plus
   115945 ** 2 for the first position.  Example:
   115946 **
   115947 **   label:       A B C D E  F  G H   I  J K
   115948 **   value:     123 5 9 1 1 14 35 0 234 72 0
   115949 **
   115950 ** The 123 value is the first docid.  For column zero in this document
   115951 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   115952 ** at D signals the start of a new column; the 1 at E indicates that the
   115953 ** new column is column number 1.  There are two positions at 12 and 45
   115954 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   115955 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
   115956 ** terminates with the 0 at K.
   115957 **
   115958 ** A "position-list" is the list of positions for multiple columns for
   115959 ** a single docid.  A "column-list" is the set of positions for a single
   115960 ** column.  Hence, a position-list consists of one or more column-lists,
   115961 ** a document record consists of a docid followed by a position-list and
   115962 ** a doclist consists of one or more document records.
   115963 **
   115964 ** A bare doclist omits the position information, becoming an
   115965 ** array of varint-encoded docids.
   115966 **
   115967 **** Segment leaf nodes ****
   115968 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   115969 ** nodes are written using LeafWriter, and read using LeafReader (to
   115970 ** iterate through a single leaf node's data) and LeavesReader (to
   115971 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   115972 ** the format:
   115973 **
   115974 ** varint iHeight;             (height from leaf level, always 0)
   115975 ** varint nTerm;               (length of first term)
   115976 ** char pTerm[nTerm];          (content of first term)
   115977 ** varint nDoclist;            (length of term's associated doclist)
   115978 ** char pDoclist[nDoclist];    (content of doclist)
   115979 ** array {
   115980 **                             (further terms are delta-encoded)
   115981 **   varint nPrefix;           (length of prefix shared with previous term)
   115982 **   varint nSuffix;           (length of unshared suffix)
   115983 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   115984 **   varint nDoclist;          (length of term's associated doclist)
   115985 **   char pDoclist[nDoclist];  (content of doclist)
   115986 ** }
   115987 **
   115988 ** Here, array { X } means zero or more occurrences of X, adjacent in
   115989 ** memory.
   115990 **
   115991 ** Leaf nodes are broken into blocks which are stored contiguously in
   115992 ** the %_segments table in sorted order.  This means that when the end
   115993 ** of a node is reached, the next term is in the node with the next
   115994 ** greater node id.
   115995 **
   115996 ** New data is spilled to a new leaf node when the current node
   115997 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   115998 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   115999 ** node (a leaf node with a single term and doclist).  The goal of
   116000 ** these settings is to pack together groups of small doclists while
   116001 ** making it efficient to directly access large doclists.  The
   116002 ** assumption is that large doclists represent terms which are more
   116003 ** likely to be query targets.
   116004 **
   116005 ** TODO(shess) It may be useful for blocking decisions to be more
   116006 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   116007 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   116008 ** that this might extend through 2x or 4x the pagesize.
   116009 **
   116010 **
   116011 **** Segment interior nodes ****
   116012 ** Segment interior nodes store blockids for subtree nodes and terms
   116013 ** to describe what data is stored by the each subtree.  Interior
   116014 ** nodes are written using InteriorWriter, and read using
   116015 ** InteriorReader.  InteriorWriters are created as needed when
   116016 ** SegmentWriter creates new leaf nodes, or when an interior node
   116017 ** itself grows too big and must be split.  The format of interior
   116018 ** nodes:
   116019 **
   116020 ** varint iHeight;           (height from leaf level, always >0)
   116021 ** varint iBlockid;          (block id of node's leftmost subtree)
   116022 ** optional {
   116023 **   varint nTerm;           (length of first term)
   116024 **   char pTerm[nTerm];      (content of first term)
   116025 **   array {
   116026 **                                (further terms are delta-encoded)
   116027 **     varint nPrefix;            (length of shared prefix with previous term)
   116028 **     varint nSuffix;            (length of unshared suffix)
   116029 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   116030 **   }
   116031 ** }
   116032 **
   116033 ** Here, optional { X } means an optional element, while array { X }
   116034 ** means zero or more occurrences of X, adjacent in memory.
   116035 **
   116036 ** An interior node encodes n terms separating n+1 subtrees.  The
   116037 ** subtree blocks are contiguous, so only the first subtree's blockid
   116038 ** is encoded.  The subtree at iBlockid will contain all terms less
   116039 ** than the first term encoded (or all terms if no term is encoded).
   116040 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   116041 ** than pTerm[i+1], the subtree for that term will be rooted at
   116042 ** iBlockid+i.  Interior nodes only store enough term data to
   116043 ** distinguish adjacent children (if the rightmost term of the left
   116044 ** child is "something", and the leftmost term of the right child is
   116045 ** "wicked", only "w" is stored).
   116046 **
   116047 ** New data is spilled to a new interior node at the same height when
   116048 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   116049 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   116050 ** interior nodes and making the tree too skinny.  The interior nodes
   116051 ** at a given height are naturally tracked by interior nodes at
   116052 ** height+1, and so on.
   116053 **
   116054 **
   116055 **** Segment directory ****
   116056 ** The segment directory in table %_segdir stores meta-information for
   116057 ** merging and deleting segments, and also the root node of the
   116058 ** segment's tree.
   116059 **
   116060 ** The root node is the top node of the segment's tree after encoding
   116061 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   116062 ** This could be either a leaf node or an interior node.  If the top
   116063 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   116064 ** and a new root interior node is generated (which should always fit
   116065 ** within ROOT_MAX because it only needs space for 2 varints, the
   116066 ** height and the blockid of the previous root).
   116067 **
   116068 ** The meta-information in the segment directory is:
   116069 **   level               - segment level (see below)
   116070 **   idx                 - index within level
   116071 **                       - (level,idx uniquely identify a segment)
   116072 **   start_block         - first leaf node
   116073 **   leaves_end_block    - last leaf node
   116074 **   end_block           - last block (including interior nodes)
   116075 **   root                - contents of root node
   116076 **
   116077 ** If the root node is a leaf node, then start_block,
   116078 ** leaves_end_block, and end_block are all 0.
   116079 **
   116080 **
   116081 **** Segment merging ****
   116082 ** To amortize update costs, segments are grouped into levels and
   116083 ** merged in batches.  Each increase in level represents exponentially
   116084 ** more documents.
   116085 **
   116086 ** New documents (actually, document updates) are tokenized and
   116087 ** written individually (using LeafWriter) to a level 0 segment, with
   116088 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   116089 ** level 0 segments are merged into a single level 1 segment.  Level 1
   116090 ** is populated like level 0, and eventually MERGE_COUNT level 1
   116091 ** segments are merged to a single level 2 segment (representing
   116092 ** MERGE_COUNT^2 updates), and so on.
   116093 **
   116094 ** A segment merge traverses all segments at a given level in
   116095 ** parallel, performing a straightforward sorted merge.  Since segment
   116096 ** leaf nodes are written in to the %_segments table in order, this
   116097 ** merge traverses the underlying sqlite disk structures efficiently.
   116098 ** After the merge, all segment blocks from the merged level are
   116099 ** deleted.
   116100 **
   116101 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   116102 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   116103 ** very similar performance numbers to 16 on insertion, though they're
   116104 ** a tiny bit slower (perhaps due to more overhead in merge-time
   116105 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   116106 ** 16, 2 about 66% slower than 16.
   116107 **
   116108 ** At query time, high MERGE_COUNT increases the number of segments
   116109 ** which need to be scanned and merged.  For instance, with 100k docs
   116110 ** inserted:
   116111 **
   116112 **    MERGE_COUNT   segments
   116113 **       16           25
   116114 **        8           12
   116115 **        4           10
   116116 **        2            6
   116117 **
   116118 ** This appears to have only a moderate impact on queries for very
   116119 ** frequent terms (which are somewhat dominated by segment merge
   116120 ** costs), and infrequent and non-existent terms still seem to be fast
   116121 ** even with many segments.
   116122 **
   116123 ** TODO(shess) That said, it would be nice to have a better query-side
   116124 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   116125 ** optimizations to things like doclist merging will swing the sweet
   116126 ** spot around.
   116127 **
   116128 **
   116129 **
   116130 **** Handling of deletions and updates ****
   116131 ** Since we're using a segmented structure, with no docid-oriented
   116132 ** index into the term index, we clearly cannot simply update the term
   116133 ** index when a document is deleted or updated.  For deletions, we
   116134 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   116135 ** we simply write the new doclist.  Segment merges overwrite older
   116136 ** data for a particular docid with newer data, so deletes or updates
   116137 ** will eventually overtake the earlier data and knock it out.  The
   116138 ** query logic likewise merges doclists so that newer data knocks out
   116139 ** older data.
   116140 */
   116141 
   116142 /************** Include fts3Int.h in the middle of fts3.c ********************/
   116143 /************** Begin file fts3Int.h *****************************************/
   116144 /*
   116145 ** 2009 Nov 12
   116146 **
   116147 ** The author disclaims copyright to this source code.  In place of
   116148 ** a legal notice, here is a blessing:
   116149 **
   116150 **    May you do good and not evil.
   116151 **    May you find forgiveness for yourself and forgive others.
   116152 **    May you share freely, never taking more than you give.
   116153 **
   116154 ******************************************************************************
   116155 **
   116156 */
   116157 #ifndef _FTSINT_H
   116158 #define _FTSINT_H
   116159 
   116160 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   116161 # define NDEBUG 1
   116162 #endif
   116163 
   116164 /*
   116165 ** FTS4 is really an extension for FTS3.  It is enabled using the
   116166 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   116167 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   116168 */
   116169 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   116170 # define SQLITE_ENABLE_FTS3
   116171 #endif
   116172 
   116173 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   116174 
   116175 /* If not building as part of the core, include sqlite3ext.h. */
   116176 #ifndef SQLITE_CORE
   116177 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
   116178 #endif
   116179 
   116180 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   116181 /************** Begin file fts3_tokenizer.h **********************************/
   116182 /*
   116183 ** 2006 July 10
   116184 **
   116185 ** The author disclaims copyright to this source code.
   116186 **
   116187 *************************************************************************
   116188 ** Defines the interface to tokenizers used by fulltext-search.  There
   116189 ** are three basic components:
   116190 **
   116191 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   116192 ** interface functions.  This is essentially the class structure for
   116193 ** tokenizers.
   116194 **
   116195 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   116196 ** including customization information defined at creation time.
   116197 **
   116198 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   116199 ** tokens from a particular input.
   116200 */
   116201 #ifndef _FTS3_TOKENIZER_H_
   116202 #define _FTS3_TOKENIZER_H_
   116203 
   116204 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   116205 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   116206 ** we will need a way to register the API consistently.
   116207 */
   116208 
   116209 /*
   116210 ** Structures used by the tokenizer interface. When a new tokenizer
   116211 ** implementation is registered, the caller provides a pointer to
   116212 ** an sqlite3_tokenizer_module containing pointers to the callback
   116213 ** functions that make up an implementation.
   116214 **
   116215 ** When an fts3 table is created, it passes any arguments passed to
   116216 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   116217 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   116218 ** implementation. The xCreate() function in turn returns an
   116219 ** sqlite3_tokenizer structure representing the specific tokenizer to
   116220 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   116221 **
   116222 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   116223 ** method is called. It returns an sqlite3_tokenizer_cursor object
   116224 ** that may be used to tokenize a specific input buffer based on
   116225 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   116226 ** object.
   116227 */
   116228 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   116229 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   116230 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   116231 
   116232 struct sqlite3_tokenizer_module {
   116233 
   116234   /*
   116235   ** Structure version. Should always be set to 0 or 1.
   116236   */
   116237   int iVersion;
   116238 
   116239   /*
   116240   ** Create a new tokenizer. The values in the argv[] array are the
   116241   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   116242   ** TABLE statement that created the fts3 table. For example, if
   116243   ** the following SQL is executed:
   116244   **
   116245   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   116246   **
   116247   ** then argc is set to 2, and the argv[] array contains pointers
   116248   ** to the strings "arg1" and "arg2".
   116249   **
   116250   ** This method should return either SQLITE_OK (0), or an SQLite error
   116251   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   116252   ** to point at the newly created tokenizer structure. The generic
   116253   ** sqlite3_tokenizer.pModule variable should not be initialised by
   116254   ** this callback. The caller will do so.
   116255   */
   116256   int (*xCreate)(
   116257     int argc,                           /* Size of argv array */
   116258     const char *const*argv,             /* Tokenizer argument strings */
   116259     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   116260   );
   116261 
   116262   /*
   116263   ** Destroy an existing tokenizer. The fts3 module calls this method
   116264   ** exactly once for each successful call to xCreate().
   116265   */
   116266   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   116267 
   116268   /*
   116269   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   116270   ** is responsible for ensuring that the input buffer remains valid
   116271   ** until the cursor is closed (using the xClose() method).
   116272   */
   116273   int (*xOpen)(
   116274     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   116275     const char *pInput, int nBytes,      /* Input buffer */
   116276     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   116277   );
   116278 
   116279   /*
   116280   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   116281   ** method exactly once for each successful call to xOpen().
   116282   */
   116283   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   116284 
   116285   /*
   116286   ** Retrieve the next token from the tokenizer cursor pCursor. This
   116287   ** method should either return SQLITE_OK and set the values of the
   116288   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   116289   ** the end of the buffer has been reached, or an SQLite error code.
   116290   **
   116291   ** *ppToken should be set to point at a buffer containing the
   116292   ** normalized version of the token (i.e. after any case-folding and/or
   116293   ** stemming has been performed). *pnBytes should be set to the length
   116294   ** of this buffer in bytes. The input text that generated the token is
   116295   ** identified by the byte offsets returned in *piStartOffset and
   116296   ** *piEndOffset. *piStartOffset should be set to the index of the first
   116297   ** byte of the token in the input buffer. *piEndOffset should be set
   116298   ** to the index of the first byte just past the end of the token in
   116299   ** the input buffer.
   116300   **
   116301   ** The buffer *ppToken is set to point at is managed by the tokenizer
   116302   ** implementation. It is only required to be valid until the next call
   116303   ** to xNext() or xClose().
   116304   */
   116305   /* TODO(shess) current implementation requires pInput to be
   116306   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   116307   ** should be converted to zInput.
   116308   */
   116309   int (*xNext)(
   116310     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   116311     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   116312     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   116313     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   116314     int *piPosition      /* OUT: Number of tokens returned before this one */
   116315   );
   116316 
   116317   /***********************************************************************
   116318   ** Methods below this point are only available if iVersion>=1.
   116319   */
   116320 
   116321   /*
   116322   ** Configure the language id of a tokenizer cursor.
   116323   */
   116324   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
   116325 };
   116326 
   116327 struct sqlite3_tokenizer {
   116328   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   116329   /* Tokenizer implementations will typically add additional fields */
   116330 };
   116331 
   116332 struct sqlite3_tokenizer_cursor {
   116333   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   116334   /* Tokenizer implementations will typically add additional fields */
   116335 };
   116336 
   116337 int fts3_global_term_cnt(int iTerm, int iCol);
   116338 int fts3_term_cnt(int iTerm, int iCol);
   116339 
   116340 
   116341 #endif /* _FTS3_TOKENIZER_H_ */
   116342 
   116343 /************** End of fts3_tokenizer.h **************************************/
   116344 /************** Continuing where we left off in fts3Int.h ********************/
   116345 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   116346 /************** Begin file fts3_hash.h ***************************************/
   116347 /*
   116348 ** 2001 September 22
   116349 **
   116350 ** The author disclaims copyright to this source code.  In place of
   116351 ** a legal notice, here is a blessing:
   116352 **
   116353 **    May you do good and not evil.
   116354 **    May you find forgiveness for yourself and forgive others.
   116355 **    May you share freely, never taking more than you give.
   116356 **
   116357 *************************************************************************
   116358 ** This is the header file for the generic hash-table implemenation
   116359 ** used in SQLite.  We've modified it slightly to serve as a standalone
   116360 ** hash table implementation for the full-text indexing module.
   116361 **
   116362 */
   116363 #ifndef _FTS3_HASH_H_
   116364 #define _FTS3_HASH_H_
   116365 
   116366 /* Forward declarations of structures. */
   116367 typedef struct Fts3Hash Fts3Hash;
   116368 typedef struct Fts3HashElem Fts3HashElem;
   116369 
   116370 /* A complete hash table is an instance of the following structure.
   116371 ** The internals of this structure are intended to be opaque -- client
   116372 ** code should not attempt to access or modify the fields of this structure
   116373 ** directly.  Change this structure only by using the routines below.
   116374 ** However, many of the "procedures" and "functions" for modifying and
   116375 ** accessing this structure are really macros, so we can't really make
   116376 ** this structure opaque.
   116377 */
   116378 struct Fts3Hash {
   116379   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   116380   char copyKey;           /* True if copy of key made on insert */
   116381   int count;              /* Number of entries in this table */
   116382   Fts3HashElem *first;    /* The first element of the array */
   116383   int htsize;             /* Number of buckets in the hash table */
   116384   struct _fts3ht {        /* the hash table */
   116385     int count;               /* Number of entries with this hash */
   116386     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   116387   } *ht;
   116388 };
   116389 
   116390 /* Each element in the hash table is an instance of the following
   116391 ** structure.  All elements are stored on a single doubly-linked list.
   116392 **
   116393 ** Again, this structure is intended to be opaque, but it can't really
   116394 ** be opaque because it is used by macros.
   116395 */
   116396 struct Fts3HashElem {
   116397   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   116398   void *data;                /* Data associated with this element */
   116399   void *pKey; int nKey;      /* Key associated with this element */
   116400 };
   116401 
   116402 /*
   116403 ** There are 2 different modes of operation for a hash table:
   116404 **
   116405 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   116406 **                           (including the null-terminator, if any).  Case
   116407 **                           is respected in comparisons.
   116408 **
   116409 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   116410 **                           memcmp() is used to compare keys.
   116411 **
   116412 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   116413 */
   116414 #define FTS3_HASH_STRING    1
   116415 #define FTS3_HASH_BINARY    2
   116416 
   116417 /*
   116418 ** Access routines.  To delete, insert a NULL pointer.
   116419 */
   116420 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   116421 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   116422 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   116423 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   116424 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   116425 
   116426 /*
   116427 ** Shorthand for the functions above
   116428 */
   116429 #define fts3HashInit     sqlite3Fts3HashInit
   116430 #define fts3HashInsert   sqlite3Fts3HashInsert
   116431 #define fts3HashFind     sqlite3Fts3HashFind
   116432 #define fts3HashClear    sqlite3Fts3HashClear
   116433 #define fts3HashFindElem sqlite3Fts3HashFindElem
   116434 
   116435 /*
   116436 ** Macros for looping over all elements of a hash table.  The idiom is
   116437 ** like this:
   116438 **
   116439 **   Fts3Hash h;
   116440 **   Fts3HashElem *p;
   116441 **   ...
   116442 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   116443 **     SomeStructure *pData = fts3HashData(p);
   116444 **     // do something with pData
   116445 **   }
   116446 */
   116447 #define fts3HashFirst(H)  ((H)->first)
   116448 #define fts3HashNext(E)   ((E)->next)
   116449 #define fts3HashData(E)   ((E)->data)
   116450 #define fts3HashKey(E)    ((E)->pKey)
   116451 #define fts3HashKeysize(E) ((E)->nKey)
   116452 
   116453 /*
   116454 ** Number of entries in a hash table
   116455 */
   116456 #define fts3HashCount(H)  ((H)->count)
   116457 
   116458 #endif /* _FTS3_HASH_H_ */
   116459 
   116460 /************** End of fts3_hash.h *******************************************/
   116461 /************** Continuing where we left off in fts3Int.h ********************/
   116462 
   116463 /*
   116464 ** This constant controls how often segments are merged. Once there are
   116465 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   116466 ** segment of level N+1.
   116467 */
   116468 #define FTS3_MERGE_COUNT 16
   116469 
   116470 /*
   116471 ** This is the maximum amount of data (in bytes) to store in the
   116472 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   116473 ** populated as documents are inserted/updated/deleted in a transaction
   116474 ** and used to create a new segment when the transaction is committed.
   116475 ** However if this limit is reached midway through a transaction, a new
   116476 ** segment is created and the hash table cleared immediately.
   116477 */
   116478 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   116479 
   116480 /*
   116481 ** Macro to return the number of elements in an array. SQLite has a
   116482 ** similar macro called ArraySize(). Use a different name to avoid
   116483 ** a collision when building an amalgamation with built-in FTS3.
   116484 */
   116485 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   116486 
   116487 
   116488 #ifndef MIN
   116489 # define MIN(x,y) ((x)<(y)?(x):(y))
   116490 #endif
   116491 
   116492 /*
   116493 ** Maximum length of a varint encoded integer. The varint format is different
   116494 ** from that used by SQLite, so the maximum length is 10, not 9.
   116495 */
   116496 #define FTS3_VARINT_MAX 10
   116497 
   116498 /*
   116499 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
   116500 ** in the document set and zero or more prefix indexes. All indexes are stored
   116501 ** as one or more b+-trees in the %_segments and %_segdir tables.
   116502 **
   116503 ** It is possible to determine which index a b+-tree belongs to based on the
   116504 ** value stored in the "%_segdir.level" column. Given this value L, the index
   116505 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
   116506 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
   116507 ** between 1024 and 2047 to index 1, and so on.
   116508 **
   116509 ** It is considered impossible for an index to use more than 1024 levels. In
   116510 ** theory though this may happen, but only after at least
   116511 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
   116512 */
   116513 #define FTS3_SEGDIR_MAXLEVEL      1024
   116514 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
   116515 
   116516 /*
   116517 ** The testcase() macro is only used by the amalgamation.  If undefined,
   116518 ** make it a no-op.
   116519 */
   116520 #ifndef testcase
   116521 # define testcase(X)
   116522 #endif
   116523 
   116524 /*
   116525 ** Terminator values for position-lists and column-lists.
   116526 */
   116527 #define POS_COLUMN  (1)     /* Column-list terminator */
   116528 #define POS_END     (0)     /* Position-list terminator */
   116529 
   116530 /*
   116531 ** This section provides definitions to allow the
   116532 ** FTS3 extension to be compiled outside of the
   116533 ** amalgamation.
   116534 */
   116535 #ifndef SQLITE_AMALGAMATION
   116536 /*
   116537 ** Macros indicating that conditional expressions are always true or
   116538 ** false.
   116539 */
   116540 #ifdef SQLITE_COVERAGE_TEST
   116541 # define ALWAYS(x) (1)
   116542 # define NEVER(X)  (0)
   116543 #else
   116544 # define ALWAYS(x) (x)
   116545 # define NEVER(X)  (x)
   116546 #endif
   116547 
   116548 /*
   116549 ** Internal types used by SQLite.
   116550 */
   116551 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   116552 typedef short int i16;            /* 2-byte (or larger) signed integer */
   116553 typedef unsigned int u32;         /* 4-byte unsigned integer */
   116554 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   116555 
   116556 /*
   116557 ** Macro used to suppress compiler warnings for unused parameters.
   116558 */
   116559 #define UNUSED_PARAMETER(x) (void)(x)
   116560 
   116561 /*
   116562 ** Activate assert() only if SQLITE_TEST is enabled.
   116563 */
   116564 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   116565 # define NDEBUG 1
   116566 #endif
   116567 
   116568 /*
   116569 ** The TESTONLY macro is used to enclose variable declarations or
   116570 ** other bits of code that are needed to support the arguments
   116571 ** within testcase() and assert() macros.
   116572 */
   116573 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   116574 # define TESTONLY(X)  X
   116575 #else
   116576 # define TESTONLY(X)
   116577 #endif
   116578 
   116579 #endif /* SQLITE_AMALGAMATION */
   116580 
   116581 #ifdef SQLITE_DEBUG
   116582 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
   116583 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
   116584 #else
   116585 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
   116586 #endif
   116587 
   116588 typedef struct Fts3Table Fts3Table;
   116589 typedef struct Fts3Cursor Fts3Cursor;
   116590 typedef struct Fts3Expr Fts3Expr;
   116591 typedef struct Fts3Phrase Fts3Phrase;
   116592 typedef struct Fts3PhraseToken Fts3PhraseToken;
   116593 
   116594 typedef struct Fts3Doclist Fts3Doclist;
   116595 typedef struct Fts3SegFilter Fts3SegFilter;
   116596 typedef struct Fts3DeferredToken Fts3DeferredToken;
   116597 typedef struct Fts3SegReader Fts3SegReader;
   116598 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
   116599 
   116600 /*
   116601 ** A connection to a fulltext index is an instance of the following
   116602 ** structure. The xCreate and xConnect methods create an instance
   116603 ** of this structure and xDestroy and xDisconnect free that instance.
   116604 ** All other methods receive a pointer to the structure as one of their
   116605 ** arguments.
   116606 */
   116607 struct Fts3Table {
   116608   sqlite3_vtab base;              /* Base class used by SQLite core */
   116609   sqlite3 *db;                    /* The database connection */
   116610   const char *zDb;                /* logical database name */
   116611   const char *zName;              /* virtual table name */
   116612   int nColumn;                    /* number of named columns in virtual table */
   116613   char **azColumn;                /* column names.  malloced */
   116614   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   116615   char *zContentTbl;              /* content=xxx option, or NULL */
   116616   char *zLanguageid;              /* languageid=xxx option, or NULL */
   116617 
   116618   /* Precompiled statements used by the implementation. Each of these
   116619   ** statements is run and reset within a single virtual table API call.
   116620   */
   116621   sqlite3_stmt *aStmt[28];
   116622 
   116623   char *zReadExprlist;
   116624   char *zWriteExprlist;
   116625 
   116626   int nNodeSize;                  /* Soft limit for node size */
   116627   u8 bHasStat;                    /* True if %_stat table exists */
   116628   u8 bHasDocsize;                 /* True if %_docsize table exists */
   116629   u8 bDescIdx;                    /* True if doclists are in reverse order */
   116630   int nPgsz;                      /* Page size for host database */
   116631   char *zSegmentsTbl;             /* Name of %_segments table */
   116632   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   116633 
   116634   /* TODO: Fix the first paragraph of this comment.
   116635   **
   116636   ** The following array of hash tables is used to buffer pending index
   116637   ** updates during transactions. Variable nPendingData estimates the memory
   116638   ** size of the pending data, including hash table overhead, not including
   116639   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, the buffer
   116640   ** is flushed automatically. Variable iPrevDocid is the docid of the most
   116641   ** recently inserted record.
   116642   **
   116643   ** A single FTS4 table may have multiple full-text indexes. For each index
   116644   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
   116645   ** terms that appear in the document set. Each subsequent index in aIndex[]
   116646   ** is an index of prefixes of a specific length.
   116647   */
   116648   int nIndex;                     /* Size of aIndex[] */
   116649   struct Fts3Index {
   116650     int nPrefix;                  /* Prefix length (0 for main terms index) */
   116651     Fts3Hash hPending;            /* Pending terms table for this index */
   116652   } *aIndex;
   116653   int nMaxPendingData;            /* Max pending data before flush to disk */
   116654   int nPendingData;               /* Current bytes of pending data */
   116655   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
   116656   int iPrevLangid;                /* Langid of recently inserted document */
   116657 
   116658 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   116659   /* State variables used for validating that the transaction control
   116660   ** methods of the virtual table are called at appropriate times.  These
   116661   ** values do not contribute to FTS functionality; they are used for
   116662   ** verifying the operation of the SQLite core.
   116663   */
   116664   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
   116665   int mxSavepoint;       /* Largest valid xSavepoint integer */
   116666 #endif
   116667 };
   116668 
   116669 /*
   116670 ** When the core wants to read from the virtual table, it creates a
   116671 ** virtual table cursor (an instance of the following structure) using
   116672 ** the xOpen method. Cursors are destroyed using the xClose method.
   116673 */
   116674 struct Fts3Cursor {
   116675   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   116676   i16 eSearch;                    /* Search strategy (see below) */
   116677   u8 isEof;                       /* True if at End Of Results */
   116678   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   116679   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   116680   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   116681   int iLangid;                    /* Language being queried for */
   116682   int nPhrase;                    /* Number of matchable phrases in query */
   116683   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   116684   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   116685   char *pNextId;                  /* Pointer into the body of aDoclist */
   116686   char *aDoclist;                 /* List of docids for full-text queries */
   116687   int nDoclist;                   /* Size of buffer at aDoclist */
   116688   u8 bDesc;                       /* True to sort in descending order */
   116689   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   116690   int nRowAvg;                    /* Average size of database rows, in pages */
   116691   sqlite3_int64 nDoc;             /* Documents in table */
   116692 
   116693   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   116694   u32 *aMatchinfo;                /* Information about most recent match */
   116695   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
   116696   char *zMatchinfo;               /* Matchinfo specification */
   116697 };
   116698 
   116699 #define FTS3_EVAL_FILTER    0
   116700 #define FTS3_EVAL_NEXT      1
   116701 #define FTS3_EVAL_MATCHINFO 2
   116702 
   116703 /*
   116704 ** The Fts3Cursor.eSearch member is always set to one of the following.
   116705 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   116706 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   116707 ** of the column to be searched.  For example, in
   116708 **
   116709 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   116710 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   116711 **
   116712 ** Because the LHS of the MATCH operator is 2nd column "b",
   116713 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   116714 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   116715 ** indicating that all columns should be searched,
   116716 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   116717 */
   116718 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   116719 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   116720 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   116721 
   116722 
   116723 struct Fts3Doclist {
   116724   char *aAll;                    /* Array containing doclist (or NULL) */
   116725   int nAll;                      /* Size of a[] in bytes */
   116726   char *pNextDocid;              /* Pointer to next docid */
   116727 
   116728   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
   116729   int bFreeList;                 /* True if pList should be sqlite3_free()d */
   116730   char *pList;                   /* Pointer to position list following iDocid */
   116731   int nList;                     /* Length of position list */
   116732 };
   116733 
   116734 /*
   116735 ** A "phrase" is a sequence of one or more tokens that must match in
   116736 ** sequence.  A single token is the base case and the most common case.
   116737 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   116738 ** nToken will be the number of tokens in the string.
   116739 */
   116740 struct Fts3PhraseToken {
   116741   char *z;                        /* Text of the token */
   116742   int n;                          /* Number of bytes in buffer z */
   116743   int isPrefix;                   /* True if token ends with a "*" character */
   116744   int bFirst;                     /* True if token must appear at position 0 */
   116745 
   116746   /* Variables above this point are populated when the expression is
   116747   ** parsed (by code in fts3_expr.c). Below this point the variables are
   116748   ** used when evaluating the expression. */
   116749   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   116750   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
   116751 };
   116752 
   116753 struct Fts3Phrase {
   116754   /* Cache of doclist for this phrase. */
   116755   Fts3Doclist doclist;
   116756   int bIncr;                 /* True if doclist is loaded incrementally */
   116757   int iDoclistToken;
   116758 
   116759   /* Variables below this point are populated by fts3_expr.c when parsing
   116760   ** a MATCH expression. Everything above is part of the evaluation phase.
   116761   */
   116762   int nToken;                /* Number of tokens in the phrase */
   116763   int iColumn;               /* Index of column this phrase must match */
   116764   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   116765 };
   116766 
   116767 /*
   116768 ** A tree of these objects forms the RHS of a MATCH operator.
   116769 **
   116770 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
   116771 ** points to a malloced buffer, size nDoclist bytes, containing the results
   116772 ** of this phrase query in FTS3 doclist format. As usual, the initial
   116773 ** "Length" field found in doclists stored on disk is omitted from this
   116774 ** buffer.
   116775 **
   116776 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
   116777 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
   116778 ** where nCol is the number of columns in the queried FTS table. The array
   116779 ** is populated as follows:
   116780 **
   116781 **   aMI[iCol*3 + 0] = Undefined
   116782 **   aMI[iCol*3 + 1] = Number of occurrences
   116783 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
   116784 **
   116785 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
   116786 ** when the expression node is.
   116787 */
   116788 struct Fts3Expr {
   116789   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   116790   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   116791   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   116792   Fts3Expr *pLeft;           /* Left operand */
   116793   Fts3Expr *pRight;          /* Right operand */
   116794   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   116795 
   116796   /* The following are used by the fts3_eval.c module. */
   116797   sqlite3_int64 iDocid;      /* Current docid */
   116798   u8 bEof;                   /* True this expression is at EOF already */
   116799   u8 bStart;                 /* True if iDocid is valid */
   116800   u8 bDeferred;              /* True if this expression is entirely deferred */
   116801 
   116802   u32 *aMI;
   116803 };
   116804 
   116805 /*
   116806 ** Candidate values for Fts3Query.eType. Note that the order of the first
   116807 ** four values is in order of precedence when parsing expressions. For
   116808 ** example, the following:
   116809 **
   116810 **   "a OR b AND c NOT d NEAR e"
   116811 **
   116812 ** is equivalent to:
   116813 **
   116814 **   "a OR (b AND (c NOT (d NEAR e)))"
   116815 */
   116816 #define FTSQUERY_NEAR   1
   116817 #define FTSQUERY_NOT    2
   116818 #define FTSQUERY_AND    3
   116819 #define FTSQUERY_OR     4
   116820 #define FTSQUERY_PHRASE 5
   116821 
   116822 
   116823 /* fts3_write.c */
   116824 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   116825 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   116826 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   116827 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   116828 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
   116829   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   116830 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   116831   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
   116832 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   116833 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
   116834 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
   116835 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
   116836 
   116837 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   116838 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   116839 
   116840 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   116841 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   116842 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   116843 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   116844 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   116845 
   116846 /* Special values interpreted by sqlite3SegReaderCursor() */
   116847 #define FTS3_SEGCURSOR_PENDING        -1
   116848 #define FTS3_SEGCURSOR_ALL            -2
   116849 
   116850 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
   116851 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
   116852 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
   116853 
   116854 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
   116855     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
   116856 
   116857 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   116858 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   116859 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   116860 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   116861 #define FTS3_SEGMENT_PREFIX        0x00000008
   116862 #define FTS3_SEGMENT_SCAN          0x00000010
   116863 #define FTS3_SEGMENT_FIRST         0x00000020
   116864 
   116865 /* Type passed as 4th argument to SegmentReaderIterate() */
   116866 struct Fts3SegFilter {
   116867   const char *zTerm;
   116868   int nTerm;
   116869   int iCol;
   116870   int flags;
   116871 };
   116872 
   116873 struct Fts3MultiSegReader {
   116874   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
   116875   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
   116876   int nSegment;                   /* Size of apSegment array */
   116877   int nAdvance;                   /* How many seg-readers to advance */
   116878   Fts3SegFilter *pFilter;         /* Pointer to filter object */
   116879   char *aBuffer;                  /* Buffer to merge doclists in */
   116880   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
   116881 
   116882   int iColFilter;                 /* If >=0, filter for this column */
   116883   int bRestart;
   116884 
   116885   /* Used by fts3.c only. */
   116886   int nCost;                      /* Cost of running iterator */
   116887   int bLookup;                    /* True if a lookup of a single entry. */
   116888 
   116889   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
   116890   char *zTerm;                    /* Pointer to term buffer */
   116891   int nTerm;                      /* Size of zTerm in bytes */
   116892   char *aDoclist;                 /* Pointer to doclist buffer */
   116893   int nDoclist;                   /* Size of aDoclist[] in bytes */
   116894 };
   116895 
   116896 /* fts3.c */
   116897 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   116898 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   116899 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   116900 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   116901 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   116902 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
   116903 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
   116904 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
   116905 
   116906 /* fts3_tokenizer.c */
   116907 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   116908 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   116909 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   116910     sqlite3_tokenizer **, char **
   116911 );
   116912 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   116913 
   116914 /* fts3_snippet.c */
   116915 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   116916 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   116917   const char *, const char *, int, int
   116918 );
   116919 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   116920 
   116921 /* fts3_expr.c */
   116922 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
   116923   char **, int, int, int, const char *, int, Fts3Expr **
   116924 );
   116925 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   116926 #ifdef SQLITE_TEST
   116927 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   116928 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
   116929 #endif
   116930 
   116931 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
   116932   sqlite3_tokenizer_cursor **
   116933 );
   116934 
   116935 /* fts3_aux.c */
   116936 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
   116937 
   116938 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
   116939 
   116940 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   116941     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
   116942 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   116943     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
   116944 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
   116945 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
   116946 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
   116947 
   116948 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
   116949 
   116950 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
   116951 #endif /* _FTSINT_H */
   116952 
   116953 /************** End of fts3Int.h *********************************************/
   116954 /************** Continuing where we left off in fts3.c ***********************/
   116955 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   116956 
   116957 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   116958 # define SQLITE_CORE 1
   116959 #endif
   116960 
   116961 /* #include <assert.h> */
   116962 /* #include <stdlib.h> */
   116963 /* #include <stddef.h> */
   116964 /* #include <stdio.h> */
   116965 /* #include <string.h> */
   116966 /* #include <stdarg.h> */
   116967 
   116968 #ifndef SQLITE_CORE
   116969   SQLITE_EXTENSION_INIT1
   116970 #endif
   116971 
   116972 static int fts3EvalNext(Fts3Cursor *pCsr);
   116973 static int fts3EvalStart(Fts3Cursor *pCsr);
   116974 static int fts3TermSegReaderCursor(
   116975     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
   116976 
   116977 /*
   116978 ** Write a 64-bit variable-length integer to memory starting at p[0].
   116979 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   116980 ** The number of bytes written is returned.
   116981 */
   116982 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   116983   unsigned char *q = (unsigned char *) p;
   116984   sqlite_uint64 vu = v;
   116985   do{
   116986     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   116987     vu >>= 7;
   116988   }while( vu!=0 );
   116989   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   116990   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   116991   return (int) (q - (unsigned char *)p);
   116992 }
   116993 
   116994 /*
   116995 ** Read a 64-bit variable-length integer from memory starting at p[0].
   116996 ** Return the number of bytes read, or 0 on error.
   116997 ** The value is stored in *v.
   116998 */
   116999 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   117000   const unsigned char *q = (const unsigned char *) p;
   117001   sqlite_uint64 x = 0, y = 1;
   117002   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
   117003     x += y * (*q++ & 0x7f);
   117004     y <<= 7;
   117005   }
   117006   x += y * (*q++);
   117007   *v = (sqlite_int64) x;
   117008   return (int) (q - (unsigned char *)p);
   117009 }
   117010 
   117011 /*
   117012 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   117013 ** 32-bit integer before it is returned.
   117014 */
   117015 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   117016  sqlite_int64 i;
   117017  int ret = sqlite3Fts3GetVarint(p, &i);
   117018  *pi = (int) i;
   117019  return ret;
   117020 }
   117021 
   117022 /*
   117023 ** Return the number of bytes required to encode v as a varint
   117024 */
   117025 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   117026   int i = 0;
   117027   do{
   117028     i++;
   117029     v >>= 7;
   117030   }while( v!=0 );
   117031   return i;
   117032 }
   117033 
   117034 /*
   117035 ** Convert an SQL-style quoted string into a normal string by removing
   117036 ** the quote characters.  The conversion is done in-place.  If the
   117037 ** input does not begin with a quote character, then this routine
   117038 ** is a no-op.
   117039 **
   117040 ** Examples:
   117041 **
   117042 **     "abc"   becomes   abc
   117043 **     'xyz'   becomes   xyz
   117044 **     [pqr]   becomes   pqr
   117045 **     `mno`   becomes   mno
   117046 **
   117047 */
   117048 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   117049   char quote;                     /* Quote character (if any ) */
   117050 
   117051   quote = z[0];
   117052   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   117053     int iIn = 1;                  /* Index of next byte to read from input */
   117054     int iOut = 0;                 /* Index of next byte to write to output */
   117055 
   117056     /* If the first byte was a '[', then the close-quote character is a ']' */
   117057     if( quote=='[' ) quote = ']';
   117058 
   117059     while( ALWAYS(z[iIn]) ){
   117060       if( z[iIn]==quote ){
   117061         if( z[iIn+1]!=quote ) break;
   117062         z[iOut++] = quote;
   117063         iIn += 2;
   117064       }else{
   117065         z[iOut++] = z[iIn++];
   117066       }
   117067     }
   117068     z[iOut] = '\0';
   117069   }
   117070 }
   117071 
   117072 /*
   117073 ** Read a single varint from the doclist at *pp and advance *pp to point
   117074 ** to the first byte past the end of the varint.  Add the value of the varint
   117075 ** to *pVal.
   117076 */
   117077 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   117078   sqlite3_int64 iVal;
   117079   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   117080   *pVal += iVal;
   117081 }
   117082 
   117083 /*
   117084 ** When this function is called, *pp points to the first byte following a
   117085 ** varint that is part of a doclist (or position-list, or any other list
   117086 ** of varints). This function moves *pp to point to the start of that varint,
   117087 ** and sets *pVal by the varint value.
   117088 **
   117089 ** Argument pStart points to the first byte of the doclist that the
   117090 ** varint is part of.
   117091 */
   117092 static void fts3GetReverseVarint(
   117093   char **pp,
   117094   char *pStart,
   117095   sqlite3_int64 *pVal
   117096 ){
   117097   sqlite3_int64 iVal;
   117098   char *p;
   117099 
   117100   /* Pointer p now points at the first byte past the varint we are
   117101   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   117102   ** clear on character p[-1]. */
   117103   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
   117104   p++;
   117105   *pp = p;
   117106 
   117107   sqlite3Fts3GetVarint(p, &iVal);
   117108   *pVal = iVal;
   117109 }
   117110 
   117111 /*
   117112 ** The xDisconnect() virtual table method.
   117113 */
   117114 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   117115   Fts3Table *p = (Fts3Table *)pVtab;
   117116   int i;
   117117 
   117118   assert( p->nPendingData==0 );
   117119   assert( p->pSegments==0 );
   117120 
   117121   /* Free any prepared statements held */
   117122   for(i=0; i<SizeofArray(p->aStmt); i++){
   117123     sqlite3_finalize(p->aStmt[i]);
   117124   }
   117125   sqlite3_free(p->zSegmentsTbl);
   117126   sqlite3_free(p->zReadExprlist);
   117127   sqlite3_free(p->zWriteExprlist);
   117128   sqlite3_free(p->zContentTbl);
   117129   sqlite3_free(p->zLanguageid);
   117130 
   117131   /* Invoke the tokenizer destructor to free the tokenizer. */
   117132   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   117133 
   117134   sqlite3_free(p);
   117135   return SQLITE_OK;
   117136 }
   117137 
   117138 /*
   117139 ** Construct one or more SQL statements from the format string given
   117140 ** and then evaluate those statements. The success code is written
   117141 ** into *pRc.
   117142 **
   117143 ** If *pRc is initially non-zero then this routine is a no-op.
   117144 */
   117145 static void fts3DbExec(
   117146   int *pRc,              /* Success code */
   117147   sqlite3 *db,           /* Database in which to run SQL */
   117148   const char *zFormat,   /* Format string for SQL */
   117149   ...                    /* Arguments to the format string */
   117150 ){
   117151   va_list ap;
   117152   char *zSql;
   117153   if( *pRc ) return;
   117154   va_start(ap, zFormat);
   117155   zSql = sqlite3_vmprintf(zFormat, ap);
   117156   va_end(ap);
   117157   if( zSql==0 ){
   117158     *pRc = SQLITE_NOMEM;
   117159   }else{
   117160     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   117161     sqlite3_free(zSql);
   117162   }
   117163 }
   117164 
   117165 /*
   117166 ** The xDestroy() virtual table method.
   117167 */
   117168 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   117169   Fts3Table *p = (Fts3Table *)pVtab;
   117170   int rc = SQLITE_OK;              /* Return code */
   117171   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
   117172   sqlite3 *db = p->db;             /* Database handle */
   117173 
   117174   /* Drop the shadow tables */
   117175   if( p->zContentTbl==0 ){
   117176     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
   117177   }
   117178   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
   117179   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
   117180   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
   117181   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
   117182 
   117183   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   117184   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   117185   ** Otherwise, return an SQLite error code.
   117186   */
   117187   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   117188 }
   117189 
   117190 
   117191 /*
   117192 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   117193 ** passed as the first argument. This is done as part of the xConnect()
   117194 ** and xCreate() methods.
   117195 **
   117196 ** If *pRc is non-zero when this function is called, it is a no-op.
   117197 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   117198 ** before returning.
   117199 */
   117200 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   117201   if( *pRc==SQLITE_OK ){
   117202     int i;                        /* Iterator variable */
   117203     int rc;                       /* Return code */
   117204     char *zSql;                   /* SQL statement passed to declare_vtab() */
   117205     char *zCols;                  /* List of user defined columns */
   117206     const char *zLanguageid;
   117207 
   117208     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
   117209     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   117210 
   117211     /* Create a list of user columns for the virtual table */
   117212     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   117213     for(i=1; zCols && i<p->nColumn; i++){
   117214       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   117215     }
   117216 
   117217     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   117218     zSql = sqlite3_mprintf(
   117219         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
   117220         zCols, p->zName, zLanguageid
   117221     );
   117222     if( !zCols || !zSql ){
   117223       rc = SQLITE_NOMEM;
   117224     }else{
   117225       rc = sqlite3_declare_vtab(p->db, zSql);
   117226     }
   117227 
   117228     sqlite3_free(zSql);
   117229     sqlite3_free(zCols);
   117230     *pRc = rc;
   117231   }
   117232 }
   117233 
   117234 /*
   117235 ** Create the backing store tables (%_content, %_segments and %_segdir)
   117236 ** required by the FTS3 table passed as the only argument. This is done
   117237 ** as part of the vtab xCreate() method.
   117238 **
   117239 ** If the p->bHasDocsize boolean is true (indicating that this is an
   117240 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   117241 ** %_stat tables required by FTS4.
   117242 */
   117243 static int fts3CreateTables(Fts3Table *p){
   117244   int rc = SQLITE_OK;             /* Return code */
   117245   int i;                          /* Iterator variable */
   117246   sqlite3 *db = p->db;            /* The database connection */
   117247 
   117248   if( p->zContentTbl==0 ){
   117249     const char *zLanguageid = p->zLanguageid;
   117250     char *zContentCols;           /* Columns of %_content table */
   117251 
   117252     /* Create a list of user columns for the content table */
   117253     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   117254     for(i=0; zContentCols && i<p->nColumn; i++){
   117255       char *z = p->azColumn[i];
   117256       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   117257     }
   117258     if( zLanguageid && zContentCols ){
   117259       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
   117260     }
   117261     if( zContentCols==0 ) rc = SQLITE_NOMEM;
   117262 
   117263     /* Create the content table */
   117264     fts3DbExec(&rc, db,
   117265        "CREATE TABLE %Q.'%q_content'(%s)",
   117266        p->zDb, p->zName, zContentCols
   117267     );
   117268     sqlite3_free(zContentCols);
   117269   }
   117270 
   117271   /* Create other tables */
   117272   fts3DbExec(&rc, db,
   117273       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   117274       p->zDb, p->zName
   117275   );
   117276   fts3DbExec(&rc, db,
   117277       "CREATE TABLE %Q.'%q_segdir'("
   117278         "level INTEGER,"
   117279         "idx INTEGER,"
   117280         "start_block INTEGER,"
   117281         "leaves_end_block INTEGER,"
   117282         "end_block INTEGER,"
   117283         "root BLOB,"
   117284         "PRIMARY KEY(level, idx)"
   117285       ");",
   117286       p->zDb, p->zName
   117287   );
   117288   if( p->bHasDocsize ){
   117289     fts3DbExec(&rc, db,
   117290         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   117291         p->zDb, p->zName
   117292     );
   117293   }
   117294   if( p->bHasStat ){
   117295     fts3DbExec(&rc, db,
   117296         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
   117297         p->zDb, p->zName
   117298     );
   117299   }
   117300   return rc;
   117301 }
   117302 
   117303 /*
   117304 ** Store the current database page-size in bytes in p->nPgsz.
   117305 **
   117306 ** If *pRc is non-zero when this function is called, it is a no-op.
   117307 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   117308 ** before returning.
   117309 */
   117310 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   117311   if( *pRc==SQLITE_OK ){
   117312     int rc;                       /* Return code */
   117313     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   117314     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   117315 
   117316     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   117317     if( !zSql ){
   117318       rc = SQLITE_NOMEM;
   117319     }else{
   117320       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   117321       if( rc==SQLITE_OK ){
   117322         sqlite3_step(pStmt);
   117323         p->nPgsz = sqlite3_column_int(pStmt, 0);
   117324         rc = sqlite3_finalize(pStmt);
   117325       }else if( rc==SQLITE_AUTH ){
   117326         p->nPgsz = 1024;
   117327         rc = SQLITE_OK;
   117328       }
   117329     }
   117330     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   117331     sqlite3_free(zSql);
   117332     *pRc = rc;
   117333   }
   117334 }
   117335 
   117336 /*
   117337 ** "Special" FTS4 arguments are column specifications of the following form:
   117338 **
   117339 **   <key> = <value>
   117340 **
   117341 ** There may not be whitespace surrounding the "=" character. The <value>
   117342 ** term may be quoted, but the <key> may not.
   117343 */
   117344 static int fts3IsSpecialColumn(
   117345   const char *z,
   117346   int *pnKey,
   117347   char **pzValue
   117348 ){
   117349   char *zValue;
   117350   const char *zCsr = z;
   117351 
   117352   while( *zCsr!='=' ){
   117353     if( *zCsr=='\0' ) return 0;
   117354     zCsr++;
   117355   }
   117356 
   117357   *pnKey = (int)(zCsr-z);
   117358   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   117359   if( zValue ){
   117360     sqlite3Fts3Dequote(zValue);
   117361   }
   117362   *pzValue = zValue;
   117363   return 1;
   117364 }
   117365 
   117366 /*
   117367 ** Append the output of a printf() style formatting to an existing string.
   117368 */
   117369 static void fts3Appendf(
   117370   int *pRc,                       /* IN/OUT: Error code */
   117371   char **pz,                      /* IN/OUT: Pointer to string buffer */
   117372   const char *zFormat,            /* Printf format string to append */
   117373   ...                             /* Arguments for printf format string */
   117374 ){
   117375   if( *pRc==SQLITE_OK ){
   117376     va_list ap;
   117377     char *z;
   117378     va_start(ap, zFormat);
   117379     z = sqlite3_vmprintf(zFormat, ap);
   117380     va_end(ap);
   117381     if( z && *pz ){
   117382       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   117383       sqlite3_free(z);
   117384       z = z2;
   117385     }
   117386     if( z==0 ) *pRc = SQLITE_NOMEM;
   117387     sqlite3_free(*pz);
   117388     *pz = z;
   117389   }
   117390 }
   117391 
   117392 /*
   117393 ** Return a copy of input string zInput enclosed in double-quotes (") and
   117394 ** with all double quote characters escaped. For example:
   117395 **
   117396 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
   117397 **
   117398 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
   117399 ** is the callers responsibility to call sqlite3_free() to release this
   117400 ** memory.
   117401 */
   117402 static char *fts3QuoteId(char const *zInput){
   117403   int nRet;
   117404   char *zRet;
   117405   nRet = 2 + (int)strlen(zInput)*2 + 1;
   117406   zRet = sqlite3_malloc(nRet);
   117407   if( zRet ){
   117408     int i;
   117409     char *z = zRet;
   117410     *(z++) = '"';
   117411     for(i=0; zInput[i]; i++){
   117412       if( zInput[i]=='"' ) *(z++) = '"';
   117413       *(z++) = zInput[i];
   117414     }
   117415     *(z++) = '"';
   117416     *(z++) = '\0';
   117417   }
   117418   return zRet;
   117419 }
   117420 
   117421 /*
   117422 ** Return a list of comma separated SQL expressions and a FROM clause that
   117423 ** could be used in a SELECT statement such as the following:
   117424 **
   117425 **     SELECT <list of expressions> FROM %_content AS x ...
   117426 **
   117427 ** to return the docid, followed by each column of text data in order
   117428 ** from left to write. If parameter zFunc is not NULL, then instead of
   117429 ** being returned directly each column of text data is passed to an SQL
   117430 ** function named zFunc first. For example, if zFunc is "unzip" and the
   117431 ** table has the three user-defined columns "a", "b", and "c", the following
   117432 ** string is returned:
   117433 **
   117434 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
   117435 **
   117436 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   117437 ** is the responsibility of the caller to eventually free it.
   117438 **
   117439 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   117440 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   117441 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   117442 ** no error occurs, *pRc is left unmodified.
   117443 */
   117444 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
   117445   char *zRet = 0;
   117446   char *zFree = 0;
   117447   char *zFunction;
   117448   int i;
   117449 
   117450   if( p->zContentTbl==0 ){
   117451     if( !zFunc ){
   117452       zFunction = "";
   117453     }else{
   117454       zFree = zFunction = fts3QuoteId(zFunc);
   117455     }
   117456     fts3Appendf(pRc, &zRet, "docid");
   117457     for(i=0; i<p->nColumn; i++){
   117458       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
   117459     }
   117460     if( p->zLanguageid ){
   117461       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
   117462     }
   117463     sqlite3_free(zFree);
   117464   }else{
   117465     fts3Appendf(pRc, &zRet, "rowid");
   117466     for(i=0; i<p->nColumn; i++){
   117467       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
   117468     }
   117469     if( p->zLanguageid ){
   117470       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
   117471     }
   117472   }
   117473   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
   117474       p->zDb,
   117475       (p->zContentTbl ? p->zContentTbl : p->zName),
   117476       (p->zContentTbl ? "" : "_content")
   117477   );
   117478   return zRet;
   117479 }
   117480 
   117481 /*
   117482 ** Return a list of N comma separated question marks, where N is the number
   117483 ** of columns in the %_content table (one for the docid plus one for each
   117484 ** user-defined text column).
   117485 **
   117486 ** If argument zFunc is not NULL, then all but the first question mark
   117487 ** is preceded by zFunc and an open bracket, and followed by a closed
   117488 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
   117489 ** user-defined text columns, the following string is returned:
   117490 **
   117491 **     "?, zip(?), zip(?), zip(?)"
   117492 **
   117493 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
   117494 ** is the responsibility of the caller to eventually free it.
   117495 **
   117496 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
   117497 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
   117498 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
   117499 ** no error occurs, *pRc is left unmodified.
   117500 */
   117501 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
   117502   char *zRet = 0;
   117503   char *zFree = 0;
   117504   char *zFunction;
   117505   int i;
   117506 
   117507   if( !zFunc ){
   117508     zFunction = "";
   117509   }else{
   117510     zFree = zFunction = fts3QuoteId(zFunc);
   117511   }
   117512   fts3Appendf(pRc, &zRet, "?");
   117513   for(i=0; i<p->nColumn; i++){
   117514     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
   117515   }
   117516   if( p->zLanguageid ){
   117517     fts3Appendf(pRc, &zRet, ", ?");
   117518   }
   117519   sqlite3_free(zFree);
   117520   return zRet;
   117521 }
   117522 
   117523 /*
   117524 ** This function interprets the string at (*pp) as a non-negative integer
   117525 ** value. It reads the integer and sets *pnOut to the value read, then
   117526 ** sets *pp to point to the byte immediately following the last byte of
   117527 ** the integer value.
   117528 **
   117529 ** Only decimal digits ('0'..'9') may be part of an integer value.
   117530 **
   117531 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
   117532 ** the output value undefined. Otherwise SQLITE_OK is returned.
   117533 **
   117534 ** This function is used when parsing the "prefix=" FTS4 parameter.
   117535 */
   117536 static int fts3GobbleInt(const char **pp, int *pnOut){
   117537   const char *p;                  /* Iterator pointer */
   117538   int nInt = 0;                   /* Output value */
   117539 
   117540   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
   117541     nInt = nInt * 10 + (p[0] - '0');
   117542   }
   117543   if( p==*pp ) return SQLITE_ERROR;
   117544   *pnOut = nInt;
   117545   *pp = p;
   117546   return SQLITE_OK;
   117547 }
   117548 
   117549 /*
   117550 ** This function is called to allocate an array of Fts3Index structures
   117551 ** representing the indexes maintained by the current FTS table. FTS tables
   117552 ** always maintain the main "terms" index, but may also maintain one or
   117553 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
   117554 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
   117555 **
   117556 ** Argument zParam is passed the value of the "prefix=" option if one was
   117557 ** specified, or NULL otherwise.
   117558 **
   117559 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
   117560 ** the allocated array. *pnIndex is set to the number of elements in the
   117561 ** array. If an error does occur, an SQLite error code is returned.
   117562 **
   117563 ** Regardless of whether or not an error is returned, it is the responsibility
   117564 ** of the caller to call sqlite3_free() on the output array to free it.
   117565 */
   117566 static int fts3PrefixParameter(
   117567   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
   117568   int *pnIndex,                   /* OUT: size of *apIndex[] array */
   117569   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
   117570 ){
   117571   struct Fts3Index *aIndex;       /* Allocated array */
   117572   int nIndex = 1;                 /* Number of entries in array */
   117573 
   117574   if( zParam && zParam[0] ){
   117575     const char *p;
   117576     nIndex++;
   117577     for(p=zParam; *p; p++){
   117578       if( *p==',' ) nIndex++;
   117579     }
   117580   }
   117581 
   117582   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
   117583   *apIndex = aIndex;
   117584   *pnIndex = nIndex;
   117585   if( !aIndex ){
   117586     return SQLITE_NOMEM;
   117587   }
   117588 
   117589   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
   117590   if( zParam ){
   117591     const char *p = zParam;
   117592     int i;
   117593     for(i=1; i<nIndex; i++){
   117594       int nPrefix;
   117595       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
   117596       aIndex[i].nPrefix = nPrefix;
   117597       p++;
   117598     }
   117599   }
   117600 
   117601   return SQLITE_OK;
   117602 }
   117603 
   117604 /*
   117605 ** This function is called when initializing an FTS4 table that uses the
   117606 ** content=xxx option. It determines the number of and names of the columns
   117607 ** of the new FTS4 table.
   117608 **
   117609 ** The third argument passed to this function is the value passed to the
   117610 ** config=xxx option (i.e. "xxx"). This function queries the database for
   117611 ** a table of that name. If found, the output variables are populated
   117612 ** as follows:
   117613 **
   117614 **   *pnCol:   Set to the number of columns table xxx has,
   117615 **
   117616 **   *pnStr:   Set to the total amount of space required to store a copy
   117617 **             of each columns name, including the nul-terminator.
   117618 **
   117619 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
   117620 **             the name of the corresponding column in table xxx. The array
   117621 **             and its contents are allocated using a single allocation. It
   117622 **             is the responsibility of the caller to free this allocation
   117623 **             by eventually passing the *pazCol value to sqlite3_free().
   117624 **
   117625 ** If the table cannot be found, an error code is returned and the output
   117626 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
   117627 ** returned (and the output variables are undefined).
   117628 */
   117629 static int fts3ContentColumns(
   117630   sqlite3 *db,                    /* Database handle */
   117631   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
   117632   const char *zTbl,               /* Name of content table */
   117633   const char ***pazCol,           /* OUT: Malloc'd array of column names */
   117634   int *pnCol,                     /* OUT: Size of array *pazCol */
   117635   int *pnStr                      /* OUT: Bytes of string content */
   117636 ){
   117637   int rc = SQLITE_OK;             /* Return code */
   117638   char *zSql;                     /* "SELECT *" statement on zTbl */
   117639   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
   117640 
   117641   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
   117642   if( !zSql ){
   117643     rc = SQLITE_NOMEM;
   117644   }else{
   117645     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   117646   }
   117647   sqlite3_free(zSql);
   117648 
   117649   if( rc==SQLITE_OK ){
   117650     const char **azCol;           /* Output array */
   117651     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
   117652     int nCol;                     /* Number of table columns */
   117653     int i;                        /* Used to iterate through columns */
   117654 
   117655     /* Loop through the returned columns. Set nStr to the number of bytes of
   117656     ** space required to store a copy of each column name, including the
   117657     ** nul-terminator byte.  */
   117658     nCol = sqlite3_column_count(pStmt);
   117659     for(i=0; i<nCol; i++){
   117660       const char *zCol = sqlite3_column_name(pStmt, i);
   117661       nStr += (int)strlen(zCol) + 1;
   117662     }
   117663 
   117664     /* Allocate and populate the array to return. */
   117665     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
   117666     if( azCol==0 ){
   117667       rc = SQLITE_NOMEM;
   117668     }else{
   117669       char *p = (char *)&azCol[nCol];
   117670       for(i=0; i<nCol; i++){
   117671         const char *zCol = sqlite3_column_name(pStmt, i);
   117672         int n = (int)strlen(zCol)+1;
   117673         memcpy(p, zCol, n);
   117674         azCol[i] = p;
   117675         p += n;
   117676       }
   117677     }
   117678     sqlite3_finalize(pStmt);
   117679 
   117680     /* Set the output variables. */
   117681     *pnCol = nCol;
   117682     *pnStr = nStr;
   117683     *pazCol = azCol;
   117684   }
   117685 
   117686   return rc;
   117687 }
   117688 
   117689 /*
   117690 ** This function is the implementation of both the xConnect and xCreate
   117691 ** methods of the FTS3 virtual table.
   117692 **
   117693 ** The argv[] array contains the following:
   117694 **
   117695 **   argv[0]   -> module name  ("fts3" or "fts4")
   117696 **   argv[1]   -> database name
   117697 **   argv[2]   -> table name
   117698 **   argv[...] -> "column name" and other module argument fields.
   117699 */
   117700 static int fts3InitVtab(
   117701   int isCreate,                   /* True for xCreate, false for xConnect */
   117702   sqlite3 *db,                    /* The SQLite database connection */
   117703   void *pAux,                     /* Hash table containing tokenizers */
   117704   int argc,                       /* Number of elements in argv array */
   117705   const char * const *argv,       /* xCreate/xConnect argument array */
   117706   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   117707   char **pzErr                    /* Write any error message here */
   117708 ){
   117709   Fts3Hash *pHash = (Fts3Hash *)pAux;
   117710   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   117711   int rc = SQLITE_OK;             /* Return code */
   117712   int i;                          /* Iterator variable */
   117713   int nByte;                      /* Size of allocation used for *p */
   117714   int iCol;                       /* Column index */
   117715   int nString = 0;                /* Bytes required to hold all column names */
   117716   int nCol = 0;                   /* Number of columns in the FTS table */
   117717   char *zCsr;                     /* Space for holding column names */
   117718   int nDb;                        /* Bytes required to hold database name */
   117719   int nName;                      /* Bytes required to hold table name */
   117720   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   117721   const char **aCol;              /* Array of column names */
   117722   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   117723 
   117724   int nIndex;                     /* Size of aIndex[] array */
   117725   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
   117726 
   117727   /* The results of parsing supported FTS4 key=value options: */
   117728   int bNoDocsize = 0;             /* True to omit %_docsize table */
   117729   int bDescIdx = 0;               /* True to store descending indexes */
   117730   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
   117731   char *zCompress = 0;            /* compress=? parameter (or NULL) */
   117732   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
   117733   char *zContent = 0;             /* content=? parameter (or NULL) */
   117734   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
   117735 
   117736   assert( strlen(argv[0])==4 );
   117737   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   117738        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   117739   );
   117740 
   117741   nDb = (int)strlen(argv[1]) + 1;
   117742   nName = (int)strlen(argv[2]) + 1;
   117743 
   117744   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
   117745   if( !aCol ) return SQLITE_NOMEM;
   117746   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
   117747 
   117748   /* Loop through all of the arguments passed by the user to the FTS3/4
   117749   ** module (i.e. all the column names and special arguments). This loop
   117750   ** does the following:
   117751   **
   117752   **   + Figures out the number of columns the FTSX table will have, and
   117753   **     the number of bytes of space that must be allocated to store copies
   117754   **     of the column names.
   117755   **
   117756   **   + If there is a tokenizer specification included in the arguments,
   117757   **     initializes the tokenizer pTokenizer.
   117758   */
   117759   for(i=3; rc==SQLITE_OK && i<argc; i++){
   117760     char const *z = argv[i];
   117761     int nKey;
   117762     char *zVal;
   117763 
   117764     /* Check if this is a tokenizer specification */
   117765     if( !pTokenizer
   117766      && strlen(z)>8
   117767      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   117768      && 0==sqlite3Fts3IsIdChar(z[8])
   117769     ){
   117770       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   117771     }
   117772 
   117773     /* Check if it is an FTS4 special argument. */
   117774     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   117775       struct Fts4Option {
   117776         const char *zOpt;
   117777         int nOpt;
   117778       } aFts4Opt[] = {
   117779         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
   117780         { "prefix",      6 },     /* 1 -> PREFIX */
   117781         { "compress",    8 },     /* 2 -> COMPRESS */
   117782         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
   117783         { "order",       5 },     /* 4 -> ORDER */
   117784         { "content",     7 },     /* 5 -> CONTENT */
   117785         { "languageid", 10 }      /* 6 -> LANGUAGEID */
   117786       };
   117787 
   117788       int iOpt;
   117789       if( !zVal ){
   117790         rc = SQLITE_NOMEM;
   117791       }else{
   117792         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
   117793           struct Fts4Option *pOp = &aFts4Opt[iOpt];
   117794           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
   117795             break;
   117796           }
   117797         }
   117798         if( iOpt==SizeofArray(aFts4Opt) ){
   117799           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
   117800           rc = SQLITE_ERROR;
   117801         }else{
   117802           switch( iOpt ){
   117803             case 0:               /* MATCHINFO */
   117804               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
   117805                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
   117806                 rc = SQLITE_ERROR;
   117807               }
   117808               bNoDocsize = 1;
   117809               break;
   117810 
   117811             case 1:               /* PREFIX */
   117812               sqlite3_free(zPrefix);
   117813               zPrefix = zVal;
   117814               zVal = 0;
   117815               break;
   117816 
   117817             case 2:               /* COMPRESS */
   117818               sqlite3_free(zCompress);
   117819               zCompress = zVal;
   117820               zVal = 0;
   117821               break;
   117822 
   117823             case 3:               /* UNCOMPRESS */
   117824               sqlite3_free(zUncompress);
   117825               zUncompress = zVal;
   117826               zVal = 0;
   117827               break;
   117828 
   117829             case 4:               /* ORDER */
   117830               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
   117831                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
   117832               ){
   117833                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
   117834                 rc = SQLITE_ERROR;
   117835               }
   117836               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
   117837               break;
   117838 
   117839             case 5:              /* CONTENT */
   117840               sqlite3_free(zContent);
   117841               zContent = zVal;
   117842               zVal = 0;
   117843               break;
   117844 
   117845             case 6:              /* LANGUAGEID */
   117846               assert( iOpt==6 );
   117847               sqlite3_free(zLanguageid);
   117848               zLanguageid = zVal;
   117849               zVal = 0;
   117850               break;
   117851           }
   117852         }
   117853         sqlite3_free(zVal);
   117854       }
   117855     }
   117856 
   117857     /* Otherwise, the argument is a column name. */
   117858     else {
   117859       nString += (int)(strlen(z) + 1);
   117860       aCol[nCol++] = z;
   117861     }
   117862   }
   117863 
   117864   /* If a content=xxx option was specified, the following:
   117865   **
   117866   **   1. Ignore any compress= and uncompress= options.
   117867   **
   117868   **   2. If no column names were specified as part of the CREATE VIRTUAL
   117869   **      TABLE statement, use all columns from the content table.
   117870   */
   117871   if( rc==SQLITE_OK && zContent ){
   117872     sqlite3_free(zCompress);
   117873     sqlite3_free(zUncompress);
   117874     zCompress = 0;
   117875     zUncompress = 0;
   117876     if( nCol==0 ){
   117877       sqlite3_free((void*)aCol);
   117878       aCol = 0;
   117879       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
   117880 
   117881       /* If a languageid= option was specified, remove the language id
   117882       ** column from the aCol[] array. */
   117883       if( rc==SQLITE_OK && zLanguageid ){
   117884         int j;
   117885         for(j=0; j<nCol; j++){
   117886           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
   117887             int k;
   117888             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
   117889             nCol--;
   117890             break;
   117891           }
   117892         }
   117893       }
   117894     }
   117895   }
   117896   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117897 
   117898   if( nCol==0 ){
   117899     assert( nString==0 );
   117900     aCol[0] = "content";
   117901     nString = 8;
   117902     nCol = 1;
   117903   }
   117904 
   117905   if( pTokenizer==0 ){
   117906     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   117907     if( rc!=SQLITE_OK ) goto fts3_init_out;
   117908   }
   117909   assert( pTokenizer );
   117910 
   117911   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
   117912   if( rc==SQLITE_ERROR ){
   117913     assert( zPrefix );
   117914     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
   117915   }
   117916   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117917 
   117918   /* Allocate and populate the Fts3Table structure. */
   117919   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
   117920           nCol * sizeof(char *) +              /* azColumn */
   117921           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
   117922           nName +                              /* zName */
   117923           nDb +                                /* zDb */
   117924           nString;                             /* Space for azColumn strings */
   117925   p = (Fts3Table*)sqlite3_malloc(nByte);
   117926   if( p==0 ){
   117927     rc = SQLITE_NOMEM;
   117928     goto fts3_init_out;
   117929   }
   117930   memset(p, 0, nByte);
   117931   p->db = db;
   117932   p->nColumn = nCol;
   117933   p->nPendingData = 0;
   117934   p->azColumn = (char **)&p[1];
   117935   p->pTokenizer = pTokenizer;
   117936   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   117937   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   117938   p->bHasStat = isFts4;
   117939   p->bDescIdx = bDescIdx;
   117940   p->zContentTbl = zContent;
   117941   p->zLanguageid = zLanguageid;
   117942   zContent = 0;
   117943   zLanguageid = 0;
   117944   TESTONLY( p->inTransaction = -1 );
   117945   TESTONLY( p->mxSavepoint = -1 );
   117946 
   117947   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
   117948   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
   117949   p->nIndex = nIndex;
   117950   for(i=0; i<nIndex; i++){
   117951     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
   117952   }
   117953 
   117954   /* Fill in the zName and zDb fields of the vtab structure. */
   117955   zCsr = (char *)&p->aIndex[nIndex];
   117956   p->zName = zCsr;
   117957   memcpy(zCsr, argv[2], nName);
   117958   zCsr += nName;
   117959   p->zDb = zCsr;
   117960   memcpy(zCsr, argv[1], nDb);
   117961   zCsr += nDb;
   117962 
   117963   /* Fill in the azColumn array */
   117964   for(iCol=0; iCol<nCol; iCol++){
   117965     char *z;
   117966     int n = 0;
   117967     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   117968     memcpy(zCsr, z, n);
   117969     zCsr[n] = '\0';
   117970     sqlite3Fts3Dequote(zCsr);
   117971     p->azColumn[iCol] = zCsr;
   117972     zCsr += n+1;
   117973     assert( zCsr <= &((char *)p)[nByte] );
   117974   }
   117975 
   117976   if( (zCompress==0)!=(zUncompress==0) ){
   117977     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
   117978     rc = SQLITE_ERROR;
   117979     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
   117980   }
   117981   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
   117982   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   117983   if( rc!=SQLITE_OK ) goto fts3_init_out;
   117984 
   117985   /* If this is an xCreate call, create the underlying tables in the
   117986   ** database. TODO: For xConnect(), it could verify that said tables exist.
   117987   */
   117988   if( isCreate ){
   117989     rc = fts3CreateTables(p);
   117990   }
   117991 
   117992   /* Figure out the page-size for the database. This is required in order to
   117993   ** estimate the cost of loading large doclists from the database.  */
   117994   fts3DatabasePageSize(&rc, p);
   117995   p->nNodeSize = p->nPgsz-35;
   117996 
   117997   /* Declare the table schema to SQLite. */
   117998   fts3DeclareVtab(&rc, p);
   117999 
   118000 fts3_init_out:
   118001   sqlite3_free(zPrefix);
   118002   sqlite3_free(aIndex);
   118003   sqlite3_free(zCompress);
   118004   sqlite3_free(zUncompress);
   118005   sqlite3_free(zContent);
   118006   sqlite3_free(zLanguageid);
   118007   sqlite3_free((void *)aCol);
   118008   if( rc!=SQLITE_OK ){
   118009     if( p ){
   118010       fts3DisconnectMethod((sqlite3_vtab *)p);
   118011     }else if( pTokenizer ){
   118012       pTokenizer->pModule->xDestroy(pTokenizer);
   118013     }
   118014   }else{
   118015     assert( p->pSegments==0 );
   118016     *ppVTab = &p->base;
   118017   }
   118018   return rc;
   118019 }
   118020 
   118021 /*
   118022 ** The xConnect() and xCreate() methods for the virtual table. All the
   118023 ** work is done in function fts3InitVtab().
   118024 */
   118025 static int fts3ConnectMethod(
   118026   sqlite3 *db,                    /* Database connection */
   118027   void *pAux,                     /* Pointer to tokenizer hash table */
   118028   int argc,                       /* Number of elements in argv array */
   118029   const char * const *argv,       /* xCreate/xConnect argument array */
   118030   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   118031   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   118032 ){
   118033   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   118034 }
   118035 static int fts3CreateMethod(
   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(1, db, pAux, argc, argv, ppVtab, pzErr);
   118044 }
   118045 
   118046 /*
   118047 ** Implementation of the xBestIndex method for FTS3 tables. There
   118048 ** are three possible strategies, in order of preference:
   118049 **
   118050 **   1. Direct lookup by rowid or docid.
   118051 **   2. Full-text search using a MATCH operator on a non-docid column.
   118052 **   3. Linear scan of %_content table.
   118053 */
   118054 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   118055   Fts3Table *p = (Fts3Table *)pVTab;
   118056   int i;                          /* Iterator variable */
   118057   int iCons = -1;                 /* Index of constraint to use */
   118058   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
   118059 
   118060   /* By default use a full table scan. This is an expensive option,
   118061   ** so search through the constraints to see if a more efficient
   118062   ** strategy is possible.
   118063   */
   118064   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   118065   pInfo->estimatedCost = 500000;
   118066   for(i=0; i<pInfo->nConstraint; i++){
   118067     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   118068     if( pCons->usable==0 ) continue;
   118069 
   118070     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   118071     if( iCons<0
   118072      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   118073      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
   118074     ){
   118075       pInfo->idxNum = FTS3_DOCID_SEARCH;
   118076       pInfo->estimatedCost = 1.0;
   118077       iCons = i;
   118078     }
   118079 
   118080     /* A MATCH constraint. Use a full-text search.
   118081     **
   118082     ** If there is more than one MATCH constraint available, use the first
   118083     ** one encountered. If there is both a MATCH constraint and a direct
   118084     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   118085     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   118086     ** it would lead to an "unable to use function MATCH in the requested
   118087     ** context" error.
   118088     */
   118089     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   118090      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   118091     ){
   118092       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   118093       pInfo->estimatedCost = 2.0;
   118094       iCons = i;
   118095     }
   118096 
   118097     /* Equality constraint on the langid column */
   118098     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   118099      && pCons->iColumn==p->nColumn + 2
   118100     ){
   118101       iLangidCons = i;
   118102     }
   118103   }
   118104 
   118105   if( iCons>=0 ){
   118106     pInfo->aConstraintUsage[iCons].argvIndex = 1;
   118107     pInfo->aConstraintUsage[iCons].omit = 1;
   118108   }
   118109   if( iLangidCons>=0 ){
   118110     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
   118111   }
   118112 
   118113   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
   118114   ** docid) order. Both ascending and descending are possible.
   118115   */
   118116   if( pInfo->nOrderBy==1 ){
   118117     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
   118118     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
   118119       if( pOrder->desc ){
   118120         pInfo->idxStr = "DESC";
   118121       }else{
   118122         pInfo->idxStr = "ASC";
   118123       }
   118124       pInfo->orderByConsumed = 1;
   118125     }
   118126   }
   118127 
   118128   assert( p->pSegments==0 );
   118129   return SQLITE_OK;
   118130 }
   118131 
   118132 /*
   118133 ** Implementation of xOpen method.
   118134 */
   118135 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   118136   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   118137 
   118138   UNUSED_PARAMETER(pVTab);
   118139 
   118140   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   118141   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   118142   ** if the allocation fails, return SQLITE_NOMEM.
   118143   */
   118144   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   118145   if( !pCsr ){
   118146     return SQLITE_NOMEM;
   118147   }
   118148   memset(pCsr, 0, sizeof(Fts3Cursor));
   118149   return SQLITE_OK;
   118150 }
   118151 
   118152 /*
   118153 ** Close the cursor.  For additional information see the documentation
   118154 ** on the xClose method of the virtual table interface.
   118155 */
   118156 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   118157   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   118158   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   118159   sqlite3_finalize(pCsr->pStmt);
   118160   sqlite3Fts3ExprFree(pCsr->pExpr);
   118161   sqlite3Fts3FreeDeferredTokens(pCsr);
   118162   sqlite3_free(pCsr->aDoclist);
   118163   sqlite3_free(pCsr->aMatchinfo);
   118164   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   118165   sqlite3_free(pCsr);
   118166   return SQLITE_OK;
   118167 }
   118168 
   118169 /*
   118170 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
   118171 ** compose and prepare an SQL statement of the form:
   118172 **
   118173 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
   118174 **
   118175 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
   118176 ** it. If an error occurs, return an SQLite error code.
   118177 **
   118178 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
   118179 */
   118180 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
   118181   int rc = SQLITE_OK;
   118182   if( pCsr->pStmt==0 ){
   118183     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   118184     char *zSql;
   118185     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
   118186     if( !zSql ) return SQLITE_NOMEM;
   118187     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   118188     sqlite3_free(zSql);
   118189   }
   118190   *ppStmt = pCsr->pStmt;
   118191   return rc;
   118192 }
   118193 
   118194 /*
   118195 ** Position the pCsr->pStmt statement so that it is on the row
   118196 ** of the %_content table that contains the last match.  Return
   118197 ** SQLITE_OK on success.
   118198 */
   118199 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   118200   int rc = SQLITE_OK;
   118201   if( pCsr->isRequireSeek ){
   118202     sqlite3_stmt *pStmt = 0;
   118203 
   118204     rc = fts3CursorSeekStmt(pCsr, &pStmt);
   118205     if( rc==SQLITE_OK ){
   118206       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   118207       pCsr->isRequireSeek = 0;
   118208       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   118209         return SQLITE_OK;
   118210       }else{
   118211         rc = sqlite3_reset(pCsr->pStmt);
   118212         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
   118213           /* If no row was found and no error has occured, then the %_content
   118214           ** table is missing a row that is present in the full-text index.
   118215           ** The data structures are corrupt.  */
   118216           rc = FTS_CORRUPT_VTAB;
   118217           pCsr->isEof = 1;
   118218         }
   118219       }
   118220     }
   118221   }
   118222 
   118223   if( rc!=SQLITE_OK && pContext ){
   118224     sqlite3_result_error_code(pContext, rc);
   118225   }
   118226   return rc;
   118227 }
   118228 
   118229 /*
   118230 ** This function is used to process a single interior node when searching
   118231 ** a b-tree for a term or term prefix. The node data is passed to this
   118232 ** function via the zNode/nNode parameters. The term to search for is
   118233 ** passed in zTerm/nTerm.
   118234 **
   118235 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   118236 ** of the child node that heads the sub-tree that may contain the term.
   118237 **
   118238 ** If piLast is not NULL, then *piLast is set to the right-most child node
   118239 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   118240 ** a prefix.
   118241 **
   118242 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   118243 */
   118244 static int fts3ScanInteriorNode(
   118245   const char *zTerm,              /* Term to select leaves for */
   118246   int nTerm,                      /* Size of term zTerm in bytes */
   118247   const char *zNode,              /* Buffer containing segment interior node */
   118248   int nNode,                      /* Size of buffer at zNode */
   118249   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   118250   sqlite3_int64 *piLast           /* OUT: Selected child node */
   118251 ){
   118252   int rc = SQLITE_OK;             /* Return code */
   118253   const char *zCsr = zNode;       /* Cursor to iterate through node */
   118254   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   118255   char *zBuffer = 0;              /* Buffer to load terms into */
   118256   int nAlloc = 0;                 /* Size of allocated buffer */
   118257   int isFirstTerm = 1;            /* True when processing first term on page */
   118258   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   118259 
   118260   /* Skip over the 'height' varint that occurs at the start of every
   118261   ** interior node. Then load the blockid of the left-child of the b-tree
   118262   ** node into variable iChild.
   118263   **
   118264   ** Even if the data structure on disk is corrupted, this (reading two
   118265   ** varints from the buffer) does not risk an overread. If zNode is a
   118266   ** root node, then the buffer comes from a SELECT statement. SQLite does
   118267   ** not make this guarantee explicitly, but in practice there are always
   118268   ** either more than 20 bytes of allocated space following the nNode bytes of
   118269   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   118270   ** table, then there are always 20 bytes of zeroed padding following the
   118271   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   118272   */
   118273   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   118274   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   118275   if( zCsr>zEnd ){
   118276     return FTS_CORRUPT_VTAB;
   118277   }
   118278 
   118279   while( zCsr<zEnd && (piFirst || piLast) ){
   118280     int cmp;                      /* memcmp() result */
   118281     int nSuffix;                  /* Size of term suffix */
   118282     int nPrefix = 0;              /* Size of term prefix */
   118283     int nBuffer;                  /* Total term size */
   118284 
   118285     /* Load the next term on the node into zBuffer. Use realloc() to expand
   118286     ** the size of zBuffer if required.  */
   118287     if( !isFirstTerm ){
   118288       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
   118289     }
   118290     isFirstTerm = 0;
   118291     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
   118292 
   118293     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
   118294       rc = FTS_CORRUPT_VTAB;
   118295       goto finish_scan;
   118296     }
   118297     if( nPrefix+nSuffix>nAlloc ){
   118298       char *zNew;
   118299       nAlloc = (nPrefix+nSuffix) * 2;
   118300       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   118301       if( !zNew ){
   118302         rc = SQLITE_NOMEM;
   118303         goto finish_scan;
   118304       }
   118305       zBuffer = zNew;
   118306     }
   118307     assert( zBuffer );
   118308     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   118309     nBuffer = nPrefix + nSuffix;
   118310     zCsr += nSuffix;
   118311 
   118312     /* Compare the term we are searching for with the term just loaded from
   118313     ** the interior node. If the specified term is greater than or equal
   118314     ** to the term from the interior node, then all terms on the sub-tree
   118315     ** headed by node iChild are smaller than zTerm. No need to search
   118316     ** iChild.
   118317     **
   118318     ** If the interior node term is larger than the specified term, then
   118319     ** the tree headed by iChild may contain the specified term.
   118320     */
   118321     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   118322     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   118323       *piFirst = iChild;
   118324       piFirst = 0;
   118325     }
   118326 
   118327     if( piLast && cmp<0 ){
   118328       *piLast = iChild;
   118329       piLast = 0;
   118330     }
   118331 
   118332     iChild++;
   118333   };
   118334 
   118335   if( piFirst ) *piFirst = iChild;
   118336   if( piLast ) *piLast = iChild;
   118337 
   118338  finish_scan:
   118339   sqlite3_free(zBuffer);
   118340   return rc;
   118341 }
   118342 
   118343 
   118344 /*
   118345 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   118346 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   118347 ** contains a term. This function searches the sub-tree headed by the zNode
   118348 ** node for the range of leaf nodes that may contain the specified term
   118349 ** or terms for which the specified term is a prefix.
   118350 **
   118351 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   118352 ** left-most leaf node in the tree that may contain the specified term.
   118353 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   118354 ** right-most leaf node that may contain a term for which the specified
   118355 ** term is a prefix.
   118356 **
   118357 ** It is possible that the range of returned leaf nodes does not contain
   118358 ** the specified term or any terms for which it is a prefix. However, if the
   118359 ** segment does contain any such terms, they are stored within the identified
   118360 ** range. Because this function only inspects interior segment nodes (and
   118361 ** never loads leaf nodes into memory), it is not possible to be sure.
   118362 **
   118363 ** If an error occurs, an error code other than SQLITE_OK is returned.
   118364 */
   118365 static int fts3SelectLeaf(
   118366   Fts3Table *p,                   /* Virtual table handle */
   118367   const char *zTerm,              /* Term to select leaves for */
   118368   int nTerm,                      /* Size of term zTerm in bytes */
   118369   const char *zNode,              /* Buffer containing segment interior node */
   118370   int nNode,                      /* Size of buffer at zNode */
   118371   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   118372   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   118373 ){
   118374   int rc;                         /* Return code */
   118375   int iHeight;                    /* Height of this node in tree */
   118376 
   118377   assert( piLeaf || piLeaf2 );
   118378 
   118379   sqlite3Fts3GetVarint32(zNode, &iHeight);
   118380   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   118381   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   118382 
   118383   if( rc==SQLITE_OK && iHeight>1 ){
   118384     char *zBlob = 0;              /* Blob read from %_segments table */
   118385     int nBlob;                    /* Size of zBlob in bytes */
   118386 
   118387     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   118388       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
   118389       if( rc==SQLITE_OK ){
   118390         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   118391       }
   118392       sqlite3_free(zBlob);
   118393       piLeaf = 0;
   118394       zBlob = 0;
   118395     }
   118396 
   118397     if( rc==SQLITE_OK ){
   118398       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
   118399     }
   118400     if( rc==SQLITE_OK ){
   118401       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   118402     }
   118403     sqlite3_free(zBlob);
   118404   }
   118405 
   118406   return rc;
   118407 }
   118408 
   118409 /*
   118410 ** This function is used to create delta-encoded serialized lists of FTS3
   118411 ** varints. Each call to this function appends a single varint to a list.
   118412 */
   118413 static void fts3PutDeltaVarint(
   118414   char **pp,                      /* IN/OUT: Output pointer */
   118415   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   118416   sqlite3_int64 iVal              /* Write this value to the list */
   118417 ){
   118418   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   118419   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   118420   *piPrev = iVal;
   118421 }
   118422 
   118423 /*
   118424 ** When this function is called, *ppPoslist is assumed to point to the
   118425 ** start of a position-list. After it returns, *ppPoslist points to the
   118426 ** first byte after the position-list.
   118427 **
   118428 ** A position list is list of positions (delta encoded) and columns for
   118429 ** a single document record of a doclist.  So, in other words, this
   118430 ** routine advances *ppPoslist so that it points to the next docid in
   118431 ** the doclist, or to the first byte past the end of the doclist.
   118432 **
   118433 ** If pp is not NULL, then the contents of the position list are copied
   118434 ** to *pp. *pp is set to point to the first byte past the last byte copied
   118435 ** before this function returns.
   118436 */
   118437 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   118438   char *pEnd = *ppPoslist;
   118439   char c = 0;
   118440 
   118441   /* The end of a position list is marked by a zero encoded as an FTS3
   118442   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   118443   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   118444   ** of some other, multi-byte, value.
   118445   **
   118446   ** The following while-loop moves pEnd to point to the first byte that is not
   118447   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   118448   ** pEnd once more so that it points to the byte immediately following the
   118449   ** last byte in the position-list.
   118450   */
   118451   while( *pEnd | c ){
   118452     c = *pEnd++ & 0x80;
   118453     testcase( c!=0 && (*pEnd)==0 );
   118454   }
   118455   pEnd++;  /* Advance past the POS_END terminator byte */
   118456 
   118457   if( pp ){
   118458     int n = (int)(pEnd - *ppPoslist);
   118459     char *p = *pp;
   118460     memcpy(p, *ppPoslist, n);
   118461     p += n;
   118462     *pp = p;
   118463   }
   118464   *ppPoslist = pEnd;
   118465 }
   118466 
   118467 /*
   118468 ** When this function is called, *ppPoslist is assumed to point to the
   118469 ** start of a column-list. After it returns, *ppPoslist points to the
   118470 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   118471 **
   118472 ** A column-list is list of delta-encoded positions for a single column
   118473 ** within a single document within a doclist.
   118474 **
   118475 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   118476 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   118477 ** the POS_COLUMN or POS_END that terminates the column-list.
   118478 **
   118479 ** If pp is not NULL, then the contents of the column-list are copied
   118480 ** to *pp. *pp is set to point to the first byte past the last byte copied
   118481 ** before this function returns.  The POS_COLUMN or POS_END terminator
   118482 ** is not copied into *pp.
   118483 */
   118484 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   118485   char *pEnd = *ppPoslist;
   118486   char c = 0;
   118487 
   118488   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   118489   ** not part of a multi-byte varint.
   118490   */
   118491   while( 0xFE & (*pEnd | c) ){
   118492     c = *pEnd++ & 0x80;
   118493     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   118494   }
   118495   if( pp ){
   118496     int n = (int)(pEnd - *ppPoslist);
   118497     char *p = *pp;
   118498     memcpy(p, *ppPoslist, n);
   118499     p += n;
   118500     *pp = p;
   118501   }
   118502   *ppPoslist = pEnd;
   118503 }
   118504 
   118505 /*
   118506 ** Value used to signify the end of an position-list. This is safe because
   118507 ** it is not possible to have a document with 2^31 terms.
   118508 */
   118509 #define POSITION_LIST_END 0x7fffffff
   118510 
   118511 /*
   118512 ** This function is used to help parse position-lists. When this function is
   118513 ** called, *pp may point to the start of the next varint in the position-list
   118514 ** being parsed, or it may point to 1 byte past the end of the position-list
   118515 ** (in which case **pp will be a terminator bytes POS_END (0) or
   118516 ** (1)).
   118517 **
   118518 ** If *pp points past the end of the current position-list, set *pi to
   118519 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   118520 ** increment the current value of *pi by the value read, and set *pp to
   118521 ** point to the next value before returning.
   118522 **
   118523 ** Before calling this routine *pi must be initialized to the value of
   118524 ** the previous position, or zero if we are reading the first position
   118525 ** in the position-list.  Because positions are delta-encoded, the value
   118526 ** of the previous position is needed in order to compute the value of
   118527 ** the next position.
   118528 */
   118529 static void fts3ReadNextPos(
   118530   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   118531   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   118532 ){
   118533   if( (**pp)&0xFE ){
   118534     fts3GetDeltaVarint(pp, pi);
   118535     *pi -= 2;
   118536   }else{
   118537     *pi = POSITION_LIST_END;
   118538   }
   118539 }
   118540 
   118541 /*
   118542 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   118543 ** the value of iCol encoded as a varint to *pp.   This will start a new
   118544 ** column list.
   118545 **
   118546 ** Set *pp to point to the byte just after the last byte written before
   118547 ** returning (do not modify it if iCol==0). Return the total number of bytes
   118548 ** written (0 if iCol==0).
   118549 */
   118550 static int fts3PutColNumber(char **pp, int iCol){
   118551   int n = 0;                      /* Number of bytes written */
   118552   if( iCol ){
   118553     char *p = *pp;                /* Output pointer */
   118554     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   118555     *p = 0x01;
   118556     *pp = &p[n];
   118557   }
   118558   return n;
   118559 }
   118560 
   118561 /*
   118562 ** Compute the union of two position lists.  The output written
   118563 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   118564 ** order and with any duplicates removed.  All pointers are
   118565 ** updated appropriately.   The caller is responsible for insuring
   118566 ** that there is enough space in *pp to hold the complete output.
   118567 */
   118568 static void fts3PoslistMerge(
   118569   char **pp,                      /* Output buffer */
   118570   char **pp1,                     /* Left input list */
   118571   char **pp2                      /* Right input list */
   118572 ){
   118573   char *p = *pp;
   118574   char *p1 = *pp1;
   118575   char *p2 = *pp2;
   118576 
   118577   while( *p1 || *p2 ){
   118578     int iCol1;         /* The current column index in pp1 */
   118579     int iCol2;         /* The current column index in pp2 */
   118580 
   118581     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
   118582     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   118583     else iCol1 = 0;
   118584 
   118585     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
   118586     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   118587     else iCol2 = 0;
   118588 
   118589     if( iCol1==iCol2 ){
   118590       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   118591       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   118592       sqlite3_int64 iPrev = 0;
   118593       int n = fts3PutColNumber(&p, iCol1);
   118594       p1 += n;
   118595       p2 += n;
   118596 
   118597       /* At this point, both p1 and p2 point to the start of column-lists
   118598       ** for the same column (the column with index iCol1 and iCol2).
   118599       ** A column-list is a list of non-negative delta-encoded varints, each
   118600       ** incremented by 2 before being stored. Each list is terminated by a
   118601       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   118602       ** and writes the results to buffer p. p is left pointing to the byte
   118603       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   118604       ** written to the output.
   118605       */
   118606       fts3GetDeltaVarint(&p1, &i1);
   118607       fts3GetDeltaVarint(&p2, &i2);
   118608       do {
   118609         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   118610         iPrev -= 2;
   118611         if( i1==i2 ){
   118612           fts3ReadNextPos(&p1, &i1);
   118613           fts3ReadNextPos(&p2, &i2);
   118614         }else if( i1<i2 ){
   118615           fts3ReadNextPos(&p1, &i1);
   118616         }else{
   118617           fts3ReadNextPos(&p2, &i2);
   118618         }
   118619       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   118620     }else if( iCol1<iCol2 ){
   118621       p1 += fts3PutColNumber(&p, iCol1);
   118622       fts3ColumnlistCopy(&p, &p1);
   118623     }else{
   118624       p2 += fts3PutColNumber(&p, iCol2);
   118625       fts3ColumnlistCopy(&p, &p2);
   118626     }
   118627   }
   118628 
   118629   *p++ = POS_END;
   118630   *pp = p;
   118631   *pp1 = p1 + 1;
   118632   *pp2 = p2 + 1;
   118633 }
   118634 
   118635 /*
   118636 ** This function is used to merge two position lists into one. When it is
   118637 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   118638 ** the part of a doclist that follows each document id. For example, if a row
   118639 ** contains:
   118640 **
   118641 **     'a b c'|'x y z'|'a b b a'
   118642 **
   118643 ** Then the position list for this row for token 'b' would consist of:
   118644 **
   118645 **     0x02 0x01 0x02 0x03 0x03 0x00
   118646 **
   118647 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   118648 ** byte following the 0x00 terminator of their respective position lists.
   118649 **
   118650 ** If isSaveLeft is 0, an entry is added to the output position list for
   118651 ** each position in *pp2 for which there exists one or more positions in
   118652 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   118653 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   118654 ** slots before it.
   118655 **
   118656 ** e.g. nToken==1 searches for adjacent positions.
   118657 */
   118658 static int fts3PoslistPhraseMerge(
   118659   char **pp,                      /* IN/OUT: Preallocated output buffer */
   118660   int nToken,                     /* Maximum difference in token positions */
   118661   int isSaveLeft,                 /* Save the left position */
   118662   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   118663   char **pp1,                     /* IN/OUT: Left input list */
   118664   char **pp2                      /* IN/OUT: Right input list */
   118665 ){
   118666   char *p = *pp;
   118667   char *p1 = *pp1;
   118668   char *p2 = *pp2;
   118669   int iCol1 = 0;
   118670   int iCol2 = 0;
   118671 
   118672   /* Never set both isSaveLeft and isExact for the same invocation. */
   118673   assert( isSaveLeft==0 || isExact==0 );
   118674 
   118675   assert( p!=0 && *p1!=0 && *p2!=0 );
   118676   if( *p1==POS_COLUMN ){
   118677     p1++;
   118678     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118679   }
   118680   if( *p2==POS_COLUMN ){
   118681     p2++;
   118682     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118683   }
   118684 
   118685   while( 1 ){
   118686     if( iCol1==iCol2 ){
   118687       char *pSave = p;
   118688       sqlite3_int64 iPrev = 0;
   118689       sqlite3_int64 iPos1 = 0;
   118690       sqlite3_int64 iPos2 = 0;
   118691 
   118692       if( iCol1 ){
   118693         *p++ = POS_COLUMN;
   118694         p += sqlite3Fts3PutVarint(p, iCol1);
   118695       }
   118696 
   118697       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   118698       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   118699       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   118700       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   118701 
   118702       while( 1 ){
   118703         if( iPos2==iPos1+nToken
   118704          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   118705         ){
   118706           sqlite3_int64 iSave;
   118707           iSave = isSaveLeft ? iPos1 : iPos2;
   118708           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   118709           pSave = 0;
   118710           assert( p );
   118711         }
   118712         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   118713           if( (*p2&0xFE)==0 ) break;
   118714           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   118715         }else{
   118716           if( (*p1&0xFE)==0 ) break;
   118717           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   118718         }
   118719       }
   118720 
   118721       if( pSave ){
   118722         assert( pp && p );
   118723         p = pSave;
   118724       }
   118725 
   118726       fts3ColumnlistCopy(0, &p1);
   118727       fts3ColumnlistCopy(0, &p2);
   118728       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   118729       if( 0==*p1 || 0==*p2 ) break;
   118730 
   118731       p1++;
   118732       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118733       p2++;
   118734       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118735     }
   118736 
   118737     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   118738     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   118739     ** end of the position list, or the 0x01 that precedes the next
   118740     ** column-number in the position list.
   118741     */
   118742     else if( iCol1<iCol2 ){
   118743       fts3ColumnlistCopy(0, &p1);
   118744       if( 0==*p1 ) break;
   118745       p1++;
   118746       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   118747     }else{
   118748       fts3ColumnlistCopy(0, &p2);
   118749       if( 0==*p2 ) break;
   118750       p2++;
   118751       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   118752     }
   118753   }
   118754 
   118755   fts3PoslistCopy(0, &p2);
   118756   fts3PoslistCopy(0, &p1);
   118757   *pp1 = p1;
   118758   *pp2 = p2;
   118759   if( *pp==p ){
   118760     return 0;
   118761   }
   118762   *p++ = 0x00;
   118763   *pp = p;
   118764   return 1;
   118765 }
   118766 
   118767 /*
   118768 ** Merge two position-lists as required by the NEAR operator. The argument
   118769 ** position lists correspond to the left and right phrases of an expression
   118770 ** like:
   118771 **
   118772 **     "phrase 1" NEAR "phrase number 2"
   118773 **
   118774 ** Position list *pp1 corresponds to the left-hand side of the NEAR
   118775 ** expression and *pp2 to the right. As usual, the indexes in the position
   118776 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
   118777 ** in the example above).
   118778 **
   118779 ** The output position list - written to *pp - is a copy of *pp2 with those
   118780 ** entries that are not sufficiently NEAR entries in *pp1 removed.
   118781 */
   118782 static int fts3PoslistNearMerge(
   118783   char **pp,                      /* Output buffer */
   118784   char *aTmp,                     /* Temporary buffer space */
   118785   int nRight,                     /* Maximum difference in token positions */
   118786   int nLeft,                      /* Maximum difference in token positions */
   118787   char **pp1,                     /* IN/OUT: Left input list */
   118788   char **pp2                      /* IN/OUT: Right input list */
   118789 ){
   118790   char *p1 = *pp1;
   118791   char *p2 = *pp2;
   118792 
   118793   char *pTmp1 = aTmp;
   118794   char *pTmp2;
   118795   char *aTmp2;
   118796   int res = 1;
   118797 
   118798   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   118799   aTmp2 = pTmp2 = pTmp1;
   118800   *pp1 = p1;
   118801   *pp2 = p2;
   118802   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   118803   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   118804     fts3PoslistMerge(pp, &aTmp, &aTmp2);
   118805   }else if( pTmp1!=aTmp ){
   118806     fts3PoslistCopy(pp, &aTmp);
   118807   }else if( pTmp2!=aTmp2 ){
   118808     fts3PoslistCopy(pp, &aTmp2);
   118809   }else{
   118810     res = 0;
   118811   }
   118812 
   118813   return res;
   118814 }
   118815 
   118816 /*
   118817 ** An instance of this function is used to merge together the (potentially
   118818 ** large number of) doclists for each term that matches a prefix query.
   118819 ** See function fts3TermSelectMerge() for details.
   118820 */
   118821 typedef struct TermSelect TermSelect;
   118822 struct TermSelect {
   118823   char *aaOutput[16];             /* Malloc'd output buffers */
   118824   int anOutput[16];               /* Size each output buffer in bytes */
   118825 };
   118826 
   118827 /*
   118828 ** This function is used to read a single varint from a buffer. Parameter
   118829 ** pEnd points 1 byte past the end of the buffer. When this function is
   118830 ** called, if *pp points to pEnd or greater, then the end of the buffer
   118831 ** has been reached. In this case *pp is set to 0 and the function returns.
   118832 **
   118833 ** If *pp does not point to or past pEnd, then a single varint is read
   118834 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
   118835 **
   118836 ** If bDescIdx is false, the value read is added to *pVal before returning.
   118837 ** If it is true, the value read is subtracted from *pVal before this
   118838 ** function returns.
   118839 */
   118840 static void fts3GetDeltaVarint3(
   118841   char **pp,                      /* IN/OUT: Point to read varint from */
   118842   char *pEnd,                     /* End of buffer */
   118843   int bDescIdx,                   /* True if docids are descending */
   118844   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
   118845 ){
   118846   if( *pp>=pEnd ){
   118847     *pp = 0;
   118848   }else{
   118849     sqlite3_int64 iVal;
   118850     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   118851     if( bDescIdx ){
   118852       *pVal -= iVal;
   118853     }else{
   118854       *pVal += iVal;
   118855     }
   118856   }
   118857 }
   118858 
   118859 /*
   118860 ** This function is used to write a single varint to a buffer. The varint
   118861 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
   118862 ** end of the value written.
   118863 **
   118864 ** If *pbFirst is zero when this function is called, the value written to
   118865 ** the buffer is that of parameter iVal.
   118866 **
   118867 ** If *pbFirst is non-zero when this function is called, then the value
   118868 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
   118869 ** (if bDescIdx is non-zero).
   118870 **
   118871 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
   118872 ** to the value of parameter iVal.
   118873 */
   118874 static void fts3PutDeltaVarint3(
   118875   char **pp,                      /* IN/OUT: Output pointer */
   118876   int bDescIdx,                   /* True for descending docids */
   118877   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   118878   int *pbFirst,                   /* IN/OUT: True after first int written */
   118879   sqlite3_int64 iVal              /* Write this value to the list */
   118880 ){
   118881   sqlite3_int64 iWrite;
   118882   if( bDescIdx==0 || *pbFirst==0 ){
   118883     iWrite = iVal - *piPrev;
   118884   }else{
   118885     iWrite = *piPrev - iVal;
   118886   }
   118887   assert( *pbFirst || *piPrev==0 );
   118888   assert( *pbFirst==0 || iWrite>0 );
   118889   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   118890   *piPrev = iVal;
   118891   *pbFirst = 1;
   118892 }
   118893 
   118894 
   118895 /*
   118896 ** This macro is used by various functions that merge doclists. The two
   118897 ** arguments are 64-bit docid values. If the value of the stack variable
   118898 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
   118899 ** Otherwise, (i2-i1).
   118900 **
   118901 ** Using this makes it easier to write code that can merge doclists that are
   118902 ** sorted in either ascending or descending order.
   118903 */
   118904 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
   118905 
   118906 /*
   118907 ** This function does an "OR" merge of two doclists (output contains all
   118908 ** positions contained in either argument doclist). If the docids in the
   118909 ** input doclists are sorted in ascending order, parameter bDescDoclist
   118910 ** should be false. If they are sorted in ascending order, it should be
   118911 ** passed a non-zero value.
   118912 **
   118913 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
   118914 ** containing the output doclist and SQLITE_OK is returned. In this case
   118915 ** *pnOut is set to the number of bytes in the output doclist.
   118916 **
   118917 ** If an error occurs, an SQLite error code is returned. The output values
   118918 ** are undefined in this case.
   118919 */
   118920 static int fts3DoclistOrMerge(
   118921   int bDescDoclist,               /* True if arguments are desc */
   118922   char *a1, int n1,               /* First doclist */
   118923   char *a2, int n2,               /* Second doclist */
   118924   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
   118925 ){
   118926   sqlite3_int64 i1 = 0;
   118927   sqlite3_int64 i2 = 0;
   118928   sqlite3_int64 iPrev = 0;
   118929   char *pEnd1 = &a1[n1];
   118930   char *pEnd2 = &a2[n2];
   118931   char *p1 = a1;
   118932   char *p2 = a2;
   118933   char *p;
   118934   char *aOut;
   118935   int bFirstOut = 0;
   118936 
   118937   *paOut = 0;
   118938   *pnOut = 0;
   118939 
   118940   /* Allocate space for the output. Both the input and output doclists
   118941   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
   118942   ** then the first docid in each list is simply encoded as a varint. For
   118943   ** each subsequent docid, the varint stored is the difference between the
   118944   ** current and previous docid (a positive number - since the list is in
   118945   ** ascending order).
   118946   **
   118947   ** The first docid written to the output is therefore encoded using the
   118948   ** same number of bytes as it is in whichever of the input lists it is
   118949   ** read from. And each subsequent docid read from the same input list
   118950   ** consumes either the same or less bytes as it did in the input (since
   118951   ** the difference between it and the previous value in the output must
   118952   ** be a positive value less than or equal to the delta value read from
   118953   ** the input list). The same argument applies to all but the first docid
   118954   ** read from the 'other' list. And to the contents of all position lists
   118955   ** that will be copied and merged from the input to the output.
   118956   **
   118957   ** However, if the first docid copied to the output is a negative number,
   118958   ** then the encoding of the first docid from the 'other' input list may
   118959   ** be larger in the output than it was in the input (since the delta value
   118960   ** may be a larger positive integer than the actual docid).
   118961   **
   118962   ** The space required to store the output is therefore the sum of the
   118963   ** sizes of the two inputs, plus enough space for exactly one of the input
   118964   ** docids to grow.
   118965   **
   118966   ** A symetric argument may be made if the doclists are in descending
   118967   ** order.
   118968   */
   118969   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
   118970   if( !aOut ) return SQLITE_NOMEM;
   118971 
   118972   p = aOut;
   118973   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   118974   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   118975   while( p1 || p2 ){
   118976     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   118977 
   118978     if( p2 && p1 && iDiff==0 ){
   118979       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   118980       fts3PoslistMerge(&p, &p1, &p2);
   118981       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   118982       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   118983     }else if( !p2 || (p1 && iDiff<0) ){
   118984       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   118985       fts3PoslistCopy(&p, &p1);
   118986       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   118987     }else{
   118988       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
   118989       fts3PoslistCopy(&p, &p2);
   118990       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   118991     }
   118992   }
   118993 
   118994   *paOut = aOut;
   118995   *pnOut = (int)(p-aOut);
   118996   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
   118997   return SQLITE_OK;
   118998 }
   118999 
   119000 /*
   119001 ** This function does a "phrase" merge of two doclists. In a phrase merge,
   119002 ** the output contains a copy of each position from the right-hand input
   119003 ** doclist for which there is a position in the left-hand input doclist
   119004 ** exactly nDist tokens before it.
   119005 **
   119006 ** If the docids in the input doclists are sorted in ascending order,
   119007 ** parameter bDescDoclist should be false. If they are sorted in ascending
   119008 ** order, it should be passed a non-zero value.
   119009 **
   119010 ** The right-hand input doclist is overwritten by this function.
   119011 */
   119012 static void fts3DoclistPhraseMerge(
   119013   int bDescDoclist,               /* True if arguments are desc */
   119014   int nDist,                      /* Distance from left to right (1=adjacent) */
   119015   char *aLeft, int nLeft,         /* Left doclist */
   119016   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
   119017 ){
   119018   sqlite3_int64 i1 = 0;
   119019   sqlite3_int64 i2 = 0;
   119020   sqlite3_int64 iPrev = 0;
   119021   char *pEnd1 = &aLeft[nLeft];
   119022   char *pEnd2 = &aRight[*pnRight];
   119023   char *p1 = aLeft;
   119024   char *p2 = aRight;
   119025   char *p;
   119026   int bFirstOut = 0;
   119027   char *aOut = aRight;
   119028 
   119029   assert( nDist>0 );
   119030 
   119031   p = aOut;
   119032   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
   119033   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
   119034 
   119035   while( p1 && p2 ){
   119036     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
   119037     if( iDiff==0 ){
   119038       char *pSave = p;
   119039       sqlite3_int64 iPrevSave = iPrev;
   119040       int bFirstOutSave = bFirstOut;
   119041 
   119042       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
   119043       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
   119044         p = pSave;
   119045         iPrev = iPrevSave;
   119046         bFirstOut = bFirstOutSave;
   119047       }
   119048       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   119049       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   119050     }else if( iDiff<0 ){
   119051       fts3PoslistCopy(0, &p1);
   119052       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
   119053     }else{
   119054       fts3PoslistCopy(0, &p2);
   119055       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
   119056     }
   119057   }
   119058 
   119059   *pnRight = (int)(p - aOut);
   119060 }
   119061 
   119062 /*
   119063 ** Argument pList points to a position list nList bytes in size. This
   119064 ** function checks to see if the position list contains any entries for
   119065 ** a token in position 0 (of any column). If so, it writes argument iDelta
   119066 ** to the output buffer pOut, followed by a position list consisting only
   119067 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
   119068 ** The value returned is the number of bytes written to pOut (if any).
   119069 */
   119070 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
   119071   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
   119072   char *pList,                    /* Position list (no 0x00 term) */
   119073   int nList,                      /* Size of pList in bytes */
   119074   char *pOut                      /* Write output here */
   119075 ){
   119076   int nOut = 0;
   119077   int bWritten = 0;               /* True once iDelta has been written */
   119078   char *p = pList;
   119079   char *pEnd = &pList[nList];
   119080 
   119081   if( *p!=0x01 ){
   119082     if( *p==0x02 ){
   119083       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   119084       pOut[nOut++] = 0x02;
   119085       bWritten = 1;
   119086     }
   119087     fts3ColumnlistCopy(0, &p);
   119088   }
   119089 
   119090   while( p<pEnd && *p==0x01 ){
   119091     sqlite3_int64 iCol;
   119092     p++;
   119093     p += sqlite3Fts3GetVarint(p, &iCol);
   119094     if( *p==0x02 ){
   119095       if( bWritten==0 ){
   119096         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
   119097         bWritten = 1;
   119098       }
   119099       pOut[nOut++] = 0x01;
   119100       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
   119101       pOut[nOut++] = 0x02;
   119102     }
   119103     fts3ColumnlistCopy(0, &p);
   119104   }
   119105   if( bWritten ){
   119106     pOut[nOut++] = 0x00;
   119107   }
   119108 
   119109   return nOut;
   119110 }
   119111 
   119112 
   119113 /*
   119114 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   119115 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   119116 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   119117 **
   119118 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   119119 ** the responsibility of the caller to free any doclists left in the
   119120 ** TermSelect.aaOutput[] array.
   119121 */
   119122 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
   119123   char *aOut = 0;
   119124   int nOut = 0;
   119125   int i;
   119126 
   119127   /* Loop through the doclists in the aaOutput[] array. Merge them all
   119128   ** into a single doclist.
   119129   */
   119130   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   119131     if( pTS->aaOutput[i] ){
   119132       if( !aOut ){
   119133         aOut = pTS->aaOutput[i];
   119134         nOut = pTS->anOutput[i];
   119135         pTS->aaOutput[i] = 0;
   119136       }else{
   119137         int nNew;
   119138         char *aNew;
   119139 
   119140         int rc = fts3DoclistOrMerge(p->bDescIdx,
   119141             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
   119142         );
   119143         if( rc!=SQLITE_OK ){
   119144           sqlite3_free(aOut);
   119145           return rc;
   119146         }
   119147 
   119148         sqlite3_free(pTS->aaOutput[i]);
   119149         sqlite3_free(aOut);
   119150         pTS->aaOutput[i] = 0;
   119151         aOut = aNew;
   119152         nOut = nNew;
   119153       }
   119154     }
   119155   }
   119156 
   119157   pTS->aaOutput[0] = aOut;
   119158   pTS->anOutput[0] = nOut;
   119159   return SQLITE_OK;
   119160 }
   119161 
   119162 /*
   119163 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
   119164 ** as the first argument. The merge is an "OR" merge (see function
   119165 ** fts3DoclistOrMerge() for details).
   119166 **
   119167 ** This function is called with the doclist for each term that matches
   119168 ** a queried prefix. It merges all these doclists into one, the doclist
   119169 ** for the specified prefix. Since there can be a very large number of
   119170 ** doclists to merge, the merging is done pair-wise using the TermSelect
   119171 ** object.
   119172 **
   119173 ** This function returns SQLITE_OK if the merge is successful, or an
   119174 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
   119175 */
   119176 static int fts3TermSelectMerge(
   119177   Fts3Table *p,                   /* FTS table handle */
   119178   TermSelect *pTS,                /* TermSelect object to merge into */
   119179   char *aDoclist,                 /* Pointer to doclist */
   119180   int nDoclist                    /* Size of aDoclist in bytes */
   119181 ){
   119182   if( pTS->aaOutput[0]==0 ){
   119183     /* If this is the first term selected, copy the doclist to the output
   119184     ** buffer using memcpy(). */
   119185     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
   119186     pTS->anOutput[0] = nDoclist;
   119187     if( pTS->aaOutput[0] ){
   119188       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   119189     }else{
   119190       return SQLITE_NOMEM;
   119191     }
   119192   }else{
   119193     char *aMerge = aDoclist;
   119194     int nMerge = nDoclist;
   119195     int iOut;
   119196 
   119197     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   119198       if( pTS->aaOutput[iOut]==0 ){
   119199         assert( iOut>0 );
   119200         pTS->aaOutput[iOut] = aMerge;
   119201         pTS->anOutput[iOut] = nMerge;
   119202         break;
   119203       }else{
   119204         char *aNew;
   119205         int nNew;
   119206 
   119207         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
   119208             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
   119209         );
   119210         if( rc!=SQLITE_OK ){
   119211           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   119212           return rc;
   119213         }
   119214 
   119215         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
   119216         sqlite3_free(pTS->aaOutput[iOut]);
   119217         pTS->aaOutput[iOut] = 0;
   119218 
   119219         aMerge = aNew;
   119220         nMerge = nNew;
   119221         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   119222           pTS->aaOutput[iOut] = aMerge;
   119223           pTS->anOutput[iOut] = nMerge;
   119224         }
   119225       }
   119226     }
   119227   }
   119228   return SQLITE_OK;
   119229 }
   119230 
   119231 /*
   119232 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
   119233 */
   119234 static int fts3SegReaderCursorAppend(
   119235   Fts3MultiSegReader *pCsr,
   119236   Fts3SegReader *pNew
   119237 ){
   119238   if( (pCsr->nSegment%16)==0 ){
   119239     Fts3SegReader **apNew;
   119240     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
   119241     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
   119242     if( !apNew ){
   119243       sqlite3Fts3SegReaderFree(pNew);
   119244       return SQLITE_NOMEM;
   119245     }
   119246     pCsr->apSegment = apNew;
   119247   }
   119248   pCsr->apSegment[pCsr->nSegment++] = pNew;
   119249   return SQLITE_OK;
   119250 }
   119251 
   119252 /*
   119253 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
   119254 ** 8th argument.
   119255 **
   119256 ** This function returns SQLITE_OK if successful, or an SQLite error code
   119257 ** otherwise.
   119258 */
   119259 static int fts3SegReaderCursor(
   119260   Fts3Table *p,                   /* FTS3 table handle */
   119261   int iLangid,                    /* Language id */
   119262   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   119263   int iLevel,                     /* Level of segments to scan */
   119264   const char *zTerm,              /* Term to query for */
   119265   int nTerm,                      /* Size of zTerm in bytes */
   119266   int isPrefix,                   /* True for a prefix search */
   119267   int isScan,                     /* True to scan from zTerm to EOF */
   119268   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
   119269 ){
   119270   int rc = SQLITE_OK;             /* Error code */
   119271   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   119272   int rc2;                        /* Result of sqlite3_reset() */
   119273 
   119274   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   119275   ** for the pending-terms. If this is a scan, then this call must be being
   119276   ** made by an fts4aux module, not an FTS table. In this case calling
   119277   ** Fts3SegReaderPending might segfault, as the data structures used by
   119278   ** fts4aux are not completely populated. So it's easiest to filter these
   119279   ** calls out here.  */
   119280   if( iLevel<0 && p->aIndex ){
   119281     Fts3SegReader *pSeg = 0;
   119282     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
   119283     if( rc==SQLITE_OK && pSeg ){
   119284       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   119285     }
   119286   }
   119287 
   119288   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   119289     if( rc==SQLITE_OK ){
   119290       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
   119291     }
   119292 
   119293     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   119294       Fts3SegReader *pSeg = 0;
   119295 
   119296       /* Read the values returned by the SELECT into local variables. */
   119297       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
   119298       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
   119299       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
   119300       int nRoot = sqlite3_column_bytes(pStmt, 4);
   119301       char const *zRoot = sqlite3_column_blob(pStmt, 4);
   119302 
   119303       /* If zTerm is not NULL, and this segment is not stored entirely on its
   119304       ** root node, the range of leaves scanned can be reduced. Do this. */
   119305       if( iStartBlock && zTerm ){
   119306         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
   119307         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
   119308         if( rc!=SQLITE_OK ) goto finished;
   119309         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
   119310       }
   119311 
   119312       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
   119313           (isPrefix==0 && isScan==0),
   119314           iStartBlock, iLeavesEndBlock,
   119315           iEndBlock, zRoot, nRoot, &pSeg
   119316       );
   119317       if( rc!=SQLITE_OK ) goto finished;
   119318       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
   119319     }
   119320   }
   119321 
   119322  finished:
   119323   rc2 = sqlite3_reset(pStmt);
   119324   if( rc==SQLITE_DONE ) rc = rc2;
   119325 
   119326   return rc;
   119327 }
   119328 
   119329 /*
   119330 ** Set up a cursor object for iterating through a full-text index or a
   119331 ** single level therein.
   119332 */
   119333 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
   119334   Fts3Table *p,                   /* FTS3 table handle */
   119335   int iLangid,
   119336   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
   119337   int iLevel,                     /* Level of segments to scan */
   119338   const char *zTerm,              /* Term to query for */
   119339   int nTerm,                      /* Size of zTerm in bytes */
   119340   int isPrefix,                   /* True for a prefix search */
   119341   int isScan,                     /* True to scan from zTerm to EOF */
   119342   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
   119343 ){
   119344   assert( iIndex>=0 && iIndex<p->nIndex );
   119345   assert( iLevel==FTS3_SEGCURSOR_ALL
   119346       ||  iLevel==FTS3_SEGCURSOR_PENDING
   119347       ||  iLevel>=0
   119348   );
   119349   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   119350   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
   119351   assert( isPrefix==0 || isScan==0 );
   119352 
   119353   /* "isScan" is only set to true by the ft4aux module, an ordinary
   119354   ** full-text tables. */
   119355   assert( isScan==0 || p->aIndex==0 );
   119356 
   119357   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
   119358 
   119359   return fts3SegReaderCursor(
   119360       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
   119361   );
   119362 }
   119363 
   119364 /*
   119365 ** In addition to its current configuration, have the Fts3MultiSegReader
   119366 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
   119367 **
   119368 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   119369 */
   119370 static int fts3SegReaderCursorAddZero(
   119371   Fts3Table *p,                   /* FTS virtual table handle */
   119372   int iLangid,
   119373   const char *zTerm,              /* Term to scan doclist of */
   119374   int nTerm,                      /* Number of bytes in zTerm */
   119375   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
   119376 ){
   119377   return fts3SegReaderCursor(p,
   119378       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   119379   );
   119380 }
   119381 
   119382 /*
   119383 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
   119384 ** if isPrefix is true, to scan the doclist for all terms for which
   119385 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
   119386 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
   119387 ** an SQLite error code.
   119388 **
   119389 ** It is the responsibility of the caller to free this object by eventually
   119390 ** passing it to fts3SegReaderCursorFree()
   119391 **
   119392 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   119393 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
   119394 */
   119395 static int fts3TermSegReaderCursor(
   119396   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   119397   const char *zTerm,              /* Term to query for */
   119398   int nTerm,                      /* Size of zTerm in bytes */
   119399   int isPrefix,                   /* True for a prefix search */
   119400   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
   119401 ){
   119402   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
   119403   int rc = SQLITE_NOMEM;          /* Return code */
   119404 
   119405   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
   119406   if( pSegcsr ){
   119407     int i;
   119408     int bFound = 0;               /* True once an index has been found */
   119409     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   119410 
   119411     if( isPrefix ){
   119412       for(i=1; bFound==0 && i<p->nIndex; i++){
   119413         if( p->aIndex[i].nPrefix==nTerm ){
   119414           bFound = 1;
   119415           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119416               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
   119417           );
   119418           pSegcsr->bLookup = 1;
   119419         }
   119420       }
   119421 
   119422       for(i=1; bFound==0 && i<p->nIndex; i++){
   119423         if( p->aIndex[i].nPrefix==nTerm+1 ){
   119424           bFound = 1;
   119425           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119426               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
   119427           );
   119428           if( rc==SQLITE_OK ){
   119429             rc = fts3SegReaderCursorAddZero(
   119430                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
   119431             );
   119432           }
   119433         }
   119434       }
   119435     }
   119436 
   119437     if( bFound==0 ){
   119438       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
   119439           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
   119440       );
   119441       pSegcsr->bLookup = !isPrefix;
   119442     }
   119443   }
   119444 
   119445   *ppSegcsr = pSegcsr;
   119446   return rc;
   119447 }
   119448 
   119449 /*
   119450 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
   119451 */
   119452 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
   119453   sqlite3Fts3SegReaderFinish(pSegcsr);
   119454   sqlite3_free(pSegcsr);
   119455 }
   119456 
   119457 /*
   119458 ** This function retreives the doclist for the specified term (or term
   119459 ** prefix) from the database.
   119460 */
   119461 static int fts3TermSelect(
   119462   Fts3Table *p,                   /* Virtual table handle */
   119463   Fts3PhraseToken *pTok,          /* Token to query for */
   119464   int iColumn,                    /* Column to query (or -ve for all columns) */
   119465   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   119466   char **ppOut                    /* OUT: Malloced result buffer */
   119467 ){
   119468   int rc;                         /* Return code */
   119469   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
   119470   TermSelect tsc;                 /* Object for pair-wise doclist merging */
   119471   Fts3SegFilter filter;           /* Segment term filter configuration */
   119472 
   119473   pSegcsr = pTok->pSegcsr;
   119474   memset(&tsc, 0, sizeof(TermSelect));
   119475 
   119476   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
   119477         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   119478         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
   119479         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   119480   filter.iCol = iColumn;
   119481   filter.zTerm = pTok->z;
   119482   filter.nTerm = pTok->n;
   119483 
   119484   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   119485   while( SQLITE_OK==rc
   119486       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   119487   ){
   119488     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   119489   }
   119490 
   119491   if( rc==SQLITE_OK ){
   119492     rc = fts3TermSelectFinishMerge(p, &tsc);
   119493   }
   119494   if( rc==SQLITE_OK ){
   119495     *ppOut = tsc.aaOutput[0];
   119496     *pnOut = tsc.anOutput[0];
   119497   }else{
   119498     int i;
   119499     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   119500       sqlite3_free(tsc.aaOutput[i]);
   119501     }
   119502   }
   119503 
   119504   fts3SegReaderCursorFree(pSegcsr);
   119505   pTok->pSegcsr = 0;
   119506   return rc;
   119507 }
   119508 
   119509 /*
   119510 ** This function counts the total number of docids in the doclist stored
   119511 ** in buffer aList[], size nList bytes.
   119512 **
   119513 ** If the isPoslist argument is true, then it is assumed that the doclist
   119514 ** contains a position-list following each docid. Otherwise, it is assumed
   119515 ** that the doclist is simply a list of docids stored as delta encoded
   119516 ** varints.
   119517 */
   119518 static int fts3DoclistCountDocids(char *aList, int nList){
   119519   int nDoc = 0;                   /* Return value */
   119520   if( aList ){
   119521     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   119522     char *p = aList;              /* Cursor */
   119523     while( p<aEnd ){
   119524       nDoc++;
   119525       while( (*p++)&0x80 );     /* Skip docid varint */
   119526       fts3PoslistCopy(0, &p);   /* Skip over position list */
   119527     }
   119528   }
   119529 
   119530   return nDoc;
   119531 }
   119532 
   119533 /*
   119534 ** Advance the cursor to the next row in the %_content table that
   119535 ** matches the search criteria.  For a MATCH search, this will be
   119536 ** the next row that matches. For a full-table scan, this will be
   119537 ** simply the next row in the %_content table.  For a docid lookup,
   119538 ** this routine simply sets the EOF flag.
   119539 **
   119540 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   119541 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   119542 ** subsequently to determine whether or not an EOF was hit.
   119543 */
   119544 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   119545   int rc;
   119546   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   119547   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
   119548     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   119549       pCsr->isEof = 1;
   119550       rc = sqlite3_reset(pCsr->pStmt);
   119551     }else{
   119552       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   119553       rc = SQLITE_OK;
   119554     }
   119555   }else{
   119556     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   119557   }
   119558   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   119559   return rc;
   119560 }
   119561 
   119562 /*
   119563 ** This is the xFilter interface for the virtual table.  See
   119564 ** the virtual table xFilter method documentation for additional
   119565 ** information.
   119566 **
   119567 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   119568 ** the %_content table.
   119569 **
   119570 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   119571 ** in the %_content table.
   119572 **
   119573 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   119574 ** column on the left-hand side of the MATCH operator is column
   119575 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   119576 ** side of the MATCH operator.
   119577 */
   119578 static int fts3FilterMethod(
   119579   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   119580   int idxNum,                     /* Strategy index */
   119581   const char *idxStr,             /* Unused */
   119582   int nVal,                       /* Number of elements in apVal */
   119583   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   119584 ){
   119585   int rc;
   119586   char *zSql;                     /* SQL statement used to access %_content */
   119587   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   119588   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   119589 
   119590   UNUSED_PARAMETER(idxStr);
   119591   UNUSED_PARAMETER(nVal);
   119592 
   119593   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   119594   assert( nVal==0 || nVal==1 || nVal==2 );
   119595   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
   119596   assert( p->pSegments==0 );
   119597 
   119598   /* In case the cursor has been used before, clear it now. */
   119599   sqlite3_finalize(pCsr->pStmt);
   119600   sqlite3_free(pCsr->aDoclist);
   119601   sqlite3Fts3ExprFree(pCsr->pExpr);
   119602   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   119603 
   119604   if( idxStr ){
   119605     pCsr->bDesc = (idxStr[0]=='D');
   119606   }else{
   119607     pCsr->bDesc = p->bDescIdx;
   119608   }
   119609   pCsr->eSearch = (i16)idxNum;
   119610 
   119611   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
   119612     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
   119613     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
   119614 
   119615     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   119616       return SQLITE_NOMEM;
   119617     }
   119618 
   119619     pCsr->iLangid = 0;
   119620     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
   119621 
   119622     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
   119623         p->azColumn, p->bHasStat, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
   119624     );
   119625     if( rc!=SQLITE_OK ){
   119626       if( rc==SQLITE_ERROR ){
   119627         static const char *zErr = "malformed MATCH expression: [%s]";
   119628         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
   119629       }
   119630       return rc;
   119631     }
   119632 
   119633     rc = sqlite3Fts3ReadLock(p);
   119634     if( rc!=SQLITE_OK ) return rc;
   119635 
   119636     rc = fts3EvalStart(pCsr);
   119637 
   119638     sqlite3Fts3SegmentsClose(p);
   119639     if( rc!=SQLITE_OK ) return rc;
   119640     pCsr->pNextId = pCsr->aDoclist;
   119641     pCsr->iPrevId = 0;
   119642   }
   119643 
   119644   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   119645   ** statement loops through all rows of the %_content table. For a
   119646   ** full-text query or docid lookup, the statement retrieves a single
   119647   ** row by docid.
   119648   */
   119649   if( idxNum==FTS3_FULLSCAN_SEARCH ){
   119650     zSql = sqlite3_mprintf(
   119651         "SELECT %s ORDER BY rowid %s",
   119652         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
   119653     );
   119654     if( zSql ){
   119655       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   119656       sqlite3_free(zSql);
   119657     }else{
   119658       rc = SQLITE_NOMEM;
   119659     }
   119660   }else if( idxNum==FTS3_DOCID_SEARCH ){
   119661     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
   119662     if( rc==SQLITE_OK ){
   119663       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
   119664     }
   119665   }
   119666   if( rc!=SQLITE_OK ) return rc;
   119667 
   119668   return fts3NextMethod(pCursor);
   119669 }
   119670 
   119671 /*
   119672 ** This is the xEof method of the virtual table. SQLite calls this
   119673 ** routine to find out if it has reached the end of a result set.
   119674 */
   119675 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   119676   return ((Fts3Cursor *)pCursor)->isEof;
   119677 }
   119678 
   119679 /*
   119680 ** This is the xRowid method. The SQLite core calls this routine to
   119681 ** retrieve the rowid for the current row of the result set. fts3
   119682 ** exposes %_content.docid as the rowid for the virtual table. The
   119683 ** rowid should be written to *pRowid.
   119684 */
   119685 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   119686   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   119687   *pRowid = pCsr->iPrevId;
   119688   return SQLITE_OK;
   119689 }
   119690 
   119691 /*
   119692 ** This is the xColumn method, called by SQLite to request a value from
   119693 ** the row that the supplied cursor currently points to.
   119694 **
   119695 ** If:
   119696 **
   119697 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
   119698 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
   119699 **   (iCol == p->nColumn+1) -> Docid column
   119700 **   (iCol == p->nColumn+2) -> Langid column
   119701 */
   119702 static int fts3ColumnMethod(
   119703   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   119704   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
   119705   int iCol                        /* Index of column to read value from */
   119706 ){
   119707   int rc = SQLITE_OK;             /* Return Code */
   119708   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   119709   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   119710 
   119711   /* The column value supplied by SQLite must be in range. */
   119712   assert( iCol>=0 && iCol<=p->nColumn+2 );
   119713 
   119714   if( iCol==p->nColumn+1 ){
   119715     /* This call is a request for the "docid" column. Since "docid" is an
   119716     ** alias for "rowid", use the xRowid() method to obtain the value.
   119717     */
   119718     sqlite3_result_int64(pCtx, pCsr->iPrevId);
   119719   }else if( iCol==p->nColumn ){
   119720     /* The extra column whose name is the same as the table.
   119721     ** Return a blob which is a pointer to the cursor.  */
   119722     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   119723   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
   119724     sqlite3_result_int64(pCtx, pCsr->iLangid);
   119725   }else{
   119726     /* The requested column is either a user column (one that contains
   119727     ** indexed data), or the language-id column.  */
   119728     rc = fts3CursorSeek(0, pCsr);
   119729 
   119730     if( rc==SQLITE_OK ){
   119731       if( iCol==p->nColumn+2 ){
   119732         int iLangid = 0;
   119733         if( p->zLanguageid ){
   119734           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
   119735         }
   119736         sqlite3_result_int(pCtx, iLangid);
   119737       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
   119738         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
   119739       }
   119740     }
   119741   }
   119742 
   119743   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   119744   return rc;
   119745 }
   119746 
   119747 /*
   119748 ** This function is the implementation of the xUpdate callback used by
   119749 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   119750 ** inserted, updated or deleted.
   119751 */
   119752 static int fts3UpdateMethod(
   119753   sqlite3_vtab *pVtab,            /* Virtual table handle */
   119754   int nArg,                       /* Size of argument array */
   119755   sqlite3_value **apVal,          /* Array of arguments */
   119756   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   119757 ){
   119758   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   119759 }
   119760 
   119761 /*
   119762 ** Implementation of xSync() method. Flush the contents of the pending-terms
   119763 ** hash-table to the database.
   119764 */
   119765 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   119766   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
   119767   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
   119768   return rc;
   119769 }
   119770 
   119771 /*
   119772 ** Implementation of xBegin() method. This is a no-op.
   119773 */
   119774 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   119775   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   119776   UNUSED_PARAMETER(pVtab);
   119777   assert( p->pSegments==0 );
   119778   assert( p->nPendingData==0 );
   119779   assert( p->inTransaction!=1 );
   119780   TESTONLY( p->inTransaction = 1 );
   119781   TESTONLY( p->mxSavepoint = -1; );
   119782   return SQLITE_OK;
   119783 }
   119784 
   119785 /*
   119786 ** Implementation of xCommit() method. This is a no-op. The contents of
   119787 ** the pending-terms hash-table have already been flushed into the database
   119788 ** by fts3SyncMethod().
   119789 */
   119790 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   119791   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   119792   UNUSED_PARAMETER(pVtab);
   119793   assert( p->nPendingData==0 );
   119794   assert( p->inTransaction!=0 );
   119795   assert( p->pSegments==0 );
   119796   TESTONLY( p->inTransaction = 0 );
   119797   TESTONLY( p->mxSavepoint = -1; );
   119798   return SQLITE_OK;
   119799 }
   119800 
   119801 /*
   119802 ** Implementation of xRollback(). Discard the contents of the pending-terms
   119803 ** hash-table. Any changes made to the database are reverted by SQLite.
   119804 */
   119805 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   119806   Fts3Table *p = (Fts3Table*)pVtab;
   119807   sqlite3Fts3PendingTermsClear(p);
   119808   assert( p->inTransaction!=0 );
   119809   TESTONLY( p->inTransaction = 0 );
   119810   TESTONLY( p->mxSavepoint = -1; );
   119811   return SQLITE_OK;
   119812 }
   119813 
   119814 /*
   119815 ** When called, *ppPoslist must point to the byte immediately following the
   119816 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
   119817 ** moves *ppPoslist so that it instead points to the first byte of the
   119818 ** same position list.
   119819 */
   119820 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   119821   char *p = &(*ppPoslist)[-2];
   119822   char c = 0;
   119823 
   119824   while( p>pStart && (c=*p--)==0 );
   119825   while( p>pStart && (*p & 0x80) | c ){
   119826     c = *p--;
   119827   }
   119828   if( p>pStart ){ p = &p[2]; }
   119829   while( *p++&0x80 );
   119830   *ppPoslist = p;
   119831 }
   119832 
   119833 /*
   119834 ** Helper function used by the implementation of the overloaded snippet(),
   119835 ** offsets() and optimize() SQL functions.
   119836 **
   119837 ** If the value passed as the third argument is a blob of size
   119838 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   119839 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   119840 ** message is written to context pContext and SQLITE_ERROR returned. The
   119841 ** string passed via zFunc is used as part of the error message.
   119842 */
   119843 static int fts3FunctionArg(
   119844   sqlite3_context *pContext,      /* SQL function call context */
   119845   const char *zFunc,              /* Function name */
   119846   sqlite3_value *pVal,            /* argv[0] passed to function */
   119847   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   119848 ){
   119849   Fts3Cursor *pRet;
   119850   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   119851    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   119852   ){
   119853     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   119854     sqlite3_result_error(pContext, zErr, -1);
   119855     sqlite3_free(zErr);
   119856     return SQLITE_ERROR;
   119857   }
   119858   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   119859   *ppCsr = pRet;
   119860   return SQLITE_OK;
   119861 }
   119862 
   119863 /*
   119864 ** Implementation of the snippet() function for FTS3
   119865 */
   119866 static void fts3SnippetFunc(
   119867   sqlite3_context *pContext,      /* SQLite function call context */
   119868   int nVal,                       /* Size of apVal[] array */
   119869   sqlite3_value **apVal           /* Array of arguments */
   119870 ){
   119871   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119872   const char *zStart = "<b>";
   119873   const char *zEnd = "</b>";
   119874   const char *zEllipsis = "<b>...</b>";
   119875   int iCol = -1;
   119876   int nToken = 15;                /* Default number of tokens in snippet */
   119877 
   119878   /* There must be at least one argument passed to this function (otherwise
   119879   ** the non-overloaded version would have been called instead of this one).
   119880   */
   119881   assert( nVal>=1 );
   119882 
   119883   if( nVal>6 ){
   119884     sqlite3_result_error(pContext,
   119885         "wrong number of arguments to function snippet()", -1);
   119886     return;
   119887   }
   119888   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   119889 
   119890   switch( nVal ){
   119891     case 6: nToken = sqlite3_value_int(apVal[5]);
   119892     case 5: iCol = sqlite3_value_int(apVal[4]);
   119893     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   119894     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   119895     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   119896   }
   119897   if( !zEllipsis || !zEnd || !zStart ){
   119898     sqlite3_result_error_nomem(pContext);
   119899   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   119900     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   119901   }
   119902 }
   119903 
   119904 /*
   119905 ** Implementation of the offsets() function for FTS3
   119906 */
   119907 static void fts3OffsetsFunc(
   119908   sqlite3_context *pContext,      /* SQLite function call context */
   119909   int nVal,                       /* Size of argument array */
   119910   sqlite3_value **apVal           /* Array of arguments */
   119911 ){
   119912   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119913 
   119914   UNUSED_PARAMETER(nVal);
   119915 
   119916   assert( nVal==1 );
   119917   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   119918   assert( pCsr );
   119919   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   119920     sqlite3Fts3Offsets(pContext, pCsr);
   119921   }
   119922 }
   119923 
   119924 /*
   119925 ** Implementation of the special optimize() function for FTS3. This
   119926 ** function merges all segments in the database to a single segment.
   119927 ** Example usage is:
   119928 **
   119929 **   SELECT optimize(t) FROM t LIMIT 1;
   119930 **
   119931 ** where 't' is the name of an FTS3 table.
   119932 */
   119933 static void fts3OptimizeFunc(
   119934   sqlite3_context *pContext,      /* SQLite function call context */
   119935   int nVal,                       /* Size of argument array */
   119936   sqlite3_value **apVal           /* Array of arguments */
   119937 ){
   119938   int rc;                         /* Return code */
   119939   Fts3Table *p;                   /* Virtual table handle */
   119940   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   119941 
   119942   UNUSED_PARAMETER(nVal);
   119943 
   119944   assert( nVal==1 );
   119945   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   119946   p = (Fts3Table *)pCursor->base.pVtab;
   119947   assert( p );
   119948 
   119949   rc = sqlite3Fts3Optimize(p);
   119950 
   119951   switch( rc ){
   119952     case SQLITE_OK:
   119953       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   119954       break;
   119955     case SQLITE_DONE:
   119956       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   119957       break;
   119958     default:
   119959       sqlite3_result_error_code(pContext, rc);
   119960       break;
   119961   }
   119962 }
   119963 
   119964 /*
   119965 ** Implementation of the matchinfo() function for FTS3
   119966 */
   119967 static void fts3MatchinfoFunc(
   119968   sqlite3_context *pContext,      /* SQLite function call context */
   119969   int nVal,                       /* Size of argument array */
   119970   sqlite3_value **apVal           /* Array of arguments */
   119971 ){
   119972   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   119973   assert( nVal==1 || nVal==2 );
   119974   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   119975     const char *zArg = 0;
   119976     if( nVal>1 ){
   119977       zArg = (const char *)sqlite3_value_text(apVal[1]);
   119978     }
   119979     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   119980   }
   119981 }
   119982 
   119983 /*
   119984 ** This routine implements the xFindFunction method for the FTS3
   119985 ** virtual table.
   119986 */
   119987 static int fts3FindFunctionMethod(
   119988   sqlite3_vtab *pVtab,            /* Virtual table handle */
   119989   int nArg,                       /* Number of SQL function arguments */
   119990   const char *zName,              /* Name of SQL function */
   119991   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   119992   void **ppArg                    /* Unused */
   119993 ){
   119994   struct Overloaded {
   119995     const char *zName;
   119996     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   119997   } aOverload[] = {
   119998     { "snippet", fts3SnippetFunc },
   119999     { "offsets", fts3OffsetsFunc },
   120000     { "optimize", fts3OptimizeFunc },
   120001     { "matchinfo", fts3MatchinfoFunc },
   120002   };
   120003   int i;                          /* Iterator variable */
   120004 
   120005   UNUSED_PARAMETER(pVtab);
   120006   UNUSED_PARAMETER(nArg);
   120007   UNUSED_PARAMETER(ppArg);
   120008 
   120009   for(i=0; i<SizeofArray(aOverload); i++){
   120010     if( strcmp(zName, aOverload[i].zName)==0 ){
   120011       *pxFunc = aOverload[i].xFunc;
   120012       return 1;
   120013     }
   120014   }
   120015 
   120016   /* No function of the specified name was found. Return 0. */
   120017   return 0;
   120018 }
   120019 
   120020 /*
   120021 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   120022 */
   120023 static int fts3RenameMethod(
   120024   sqlite3_vtab *pVtab,            /* Virtual table handle */
   120025   const char *zName               /* New name of table */
   120026 ){
   120027   Fts3Table *p = (Fts3Table *)pVtab;
   120028   sqlite3 *db = p->db;            /* Database connection */
   120029   int rc;                         /* Return Code */
   120030 
   120031   /* As it happens, the pending terms table is always empty here. This is
   120032   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
   120033   ** always opens a savepoint transaction. And the xSavepoint() method
   120034   ** flushes the pending terms table. But leave the (no-op) call to
   120035   ** PendingTermsFlush() in in case that changes.
   120036   */
   120037   assert( p->nPendingData==0 );
   120038   rc = sqlite3Fts3PendingTermsFlush(p);
   120039 
   120040   if( p->zContentTbl==0 ){
   120041     fts3DbExec(&rc, db,
   120042       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   120043       p->zDb, p->zName, zName
   120044     );
   120045   }
   120046 
   120047   if( p->bHasDocsize ){
   120048     fts3DbExec(&rc, db,
   120049       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   120050       p->zDb, p->zName, zName
   120051     );
   120052   }
   120053   if( p->bHasStat ){
   120054     fts3DbExec(&rc, db,
   120055       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   120056       p->zDb, p->zName, zName
   120057     );
   120058   }
   120059   fts3DbExec(&rc, db,
   120060     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   120061     p->zDb, p->zName, zName
   120062   );
   120063   fts3DbExec(&rc, db,
   120064     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   120065     p->zDb, p->zName, zName
   120066   );
   120067   return rc;
   120068 }
   120069 
   120070 /*
   120071 ** The xSavepoint() method.
   120072 **
   120073 ** Flush the contents of the pending-terms table to disk.
   120074 */
   120075 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120076   UNUSED_PARAMETER(iSavepoint);
   120077   assert( ((Fts3Table *)pVtab)->inTransaction );
   120078   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
   120079   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
   120080   return fts3SyncMethod(pVtab);
   120081 }
   120082 
   120083 /*
   120084 ** The xRelease() method.
   120085 **
   120086 ** This is a no-op.
   120087 */
   120088 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120089   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
   120090   UNUSED_PARAMETER(iSavepoint);
   120091   UNUSED_PARAMETER(pVtab);
   120092   assert( p->inTransaction );
   120093   assert( p->mxSavepoint >= iSavepoint );
   120094   TESTONLY( p->mxSavepoint = iSavepoint-1 );
   120095   return SQLITE_OK;
   120096 }
   120097 
   120098 /*
   120099 ** The xRollbackTo() method.
   120100 **
   120101 ** Discard the contents of the pending terms table.
   120102 */
   120103 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
   120104   Fts3Table *p = (Fts3Table*)pVtab;
   120105   UNUSED_PARAMETER(iSavepoint);
   120106   assert( p->inTransaction );
   120107   assert( p->mxSavepoint >= iSavepoint );
   120108   TESTONLY( p->mxSavepoint = iSavepoint );
   120109   sqlite3Fts3PendingTermsClear(p);
   120110   return SQLITE_OK;
   120111 }
   120112 
   120113 static const sqlite3_module fts3Module = {
   120114   /* iVersion      */ 2,
   120115   /* xCreate       */ fts3CreateMethod,
   120116   /* xConnect      */ fts3ConnectMethod,
   120117   /* xBestIndex    */ fts3BestIndexMethod,
   120118   /* xDisconnect   */ fts3DisconnectMethod,
   120119   /* xDestroy      */ fts3DestroyMethod,
   120120   /* xOpen         */ fts3OpenMethod,
   120121   /* xClose        */ fts3CloseMethod,
   120122   /* xFilter       */ fts3FilterMethod,
   120123   /* xNext         */ fts3NextMethod,
   120124   /* xEof          */ fts3EofMethod,
   120125   /* xColumn       */ fts3ColumnMethod,
   120126   /* xRowid        */ fts3RowidMethod,
   120127   /* xUpdate       */ fts3UpdateMethod,
   120128   /* xBegin        */ fts3BeginMethod,
   120129   /* xSync         */ fts3SyncMethod,
   120130   /* xCommit       */ fts3CommitMethod,
   120131   /* xRollback     */ fts3RollbackMethod,
   120132   /* xFindFunction */ fts3FindFunctionMethod,
   120133   /* xRename */       fts3RenameMethod,
   120134   /* xSavepoint    */ fts3SavepointMethod,
   120135   /* xRelease      */ fts3ReleaseMethod,
   120136   /* xRollbackTo   */ fts3RollbackToMethod,
   120137 };
   120138 
   120139 /*
   120140 ** This function is registered as the module destructor (called when an
   120141 ** FTS3 enabled database connection is closed). It frees the memory
   120142 ** allocated for the tokenizer hash table.
   120143 */
   120144 static void hashDestroy(void *p){
   120145   Fts3Hash *pHash = (Fts3Hash *)p;
   120146   sqlite3Fts3HashClear(pHash);
   120147   sqlite3_free(pHash);
   120148 }
   120149 
   120150 /*
   120151 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   120152 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   120153 ** respectively. The following three forward declarations are for functions
   120154 ** declared in these files used to retrieve the respective implementations.
   120155 **
   120156 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   120157 ** to by the argument to point to the "simple" tokenizer implementation.
   120158 ** And so on.
   120159 */
   120160 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120161 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120162 #ifdef SQLITE_ENABLE_ICU
   120163 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   120164 #endif
   120165 
   120166 /*
   120167 ** Initialise the fts3 extension. If this extension is built as part
   120168 ** of the sqlite library, then this function is called directly by
   120169 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   120170 ** function is called by the sqlite3_extension_init() entry point.
   120171 */
   120172 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){ // Android Change
   120173   int rc = SQLITE_OK;
   120174   Fts3Hash *pHash = 0;
   120175   const sqlite3_tokenizer_module *pSimple = 0;
   120176   const sqlite3_tokenizer_module *pPorter = 0;
   120177 
   120178 #ifdef SQLITE_ENABLE_ICU
   120179   const sqlite3_tokenizer_module *pIcu = 0;
   120180   sqlite3Fts3IcuTokenizerModule(&pIcu);
   120181 #endif
   120182 
   120183 #ifdef SQLITE_TEST
   120184   rc = sqlite3Fts3InitTerm(db);
   120185   if( rc!=SQLITE_OK ) return rc;
   120186 #endif
   120187 
   120188   rc = sqlite3Fts3InitAux(db);
   120189   if( rc!=SQLITE_OK ) return rc;
   120190 
   120191   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   120192   sqlite3Fts3PorterTokenizerModule(&pPorter);
   120193 
   120194   /* Allocate and initialise the hash-table used to store tokenizers. */
   120195   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   120196   if( !pHash ){
   120197     rc = SQLITE_NOMEM;
   120198   }else{
   120199     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   120200   }
   120201 
   120202   /* Load the built-in tokenizers into the hash table */
   120203   if( rc==SQLITE_OK ){
   120204     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   120205      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   120206 #ifdef SQLITE_ENABLE_ICU
   120207      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   120208 #endif
   120209     ){
   120210       rc = SQLITE_NOMEM;
   120211     }
   120212   }
   120213 
   120214 #ifdef SQLITE_TEST
   120215   if( rc==SQLITE_OK ){
   120216     rc = sqlite3Fts3ExprInitTestInterface(db);
   120217   }
   120218 #endif
   120219 
   120220   /* Create the virtual table wrapper around the hash-table and overload
   120221   ** the two scalar functions. If this is successful, register the
   120222   ** module with sqlite.
   120223   */
   120224   if( SQLITE_OK==rc
   120225    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   120226    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   120227    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   120228    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   120229    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   120230    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   120231   ){
   120232     rc = sqlite3_create_module_v2(
   120233         // Begin Android change
   120234         // Also register as fts1 and fts2
   120235         db, registerAs, &fts3Module, (void *)pHash, hashDestroy
   120236         // End Android change
   120237     );
   120238     if( rc==SQLITE_OK ){
   120239       rc = sqlite3_create_module_v2(
   120240           db, "fts4", &fts3Module, (void *)pHash, 0
   120241       );
   120242     }
   120243     return rc;
   120244   }
   120245 
   120246   /* An error has occurred. Delete the hash table and return the error code. */
   120247   assert( rc!=SQLITE_OK );
   120248   if( pHash ){
   120249     sqlite3Fts3HashClear(pHash);
   120250     sqlite3_free(pHash);
   120251   }
   120252   return rc;
   120253 }
   120254 
   120255 /*
   120256 ** Allocate an Fts3MultiSegReader for each token in the expression headed
   120257 ** by pExpr.
   120258 **
   120259 ** An Fts3SegReader object is a cursor that can seek or scan a range of
   120260 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
   120261 ** Fts3SegReader objects internally to provide an interface to seek or scan
   120262 ** within the union of all segments of a b-tree. Hence the name.
   120263 **
   120264 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
   120265 ** segment b-tree (if the term is not a prefix or it is a prefix for which
   120266 ** there exists prefix b-tree of the right length) then it may be traversed
   120267 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
   120268 ** doclist and then traversed.
   120269 */
   120270 static void fts3EvalAllocateReaders(
   120271   Fts3Cursor *pCsr,               /* FTS cursor handle */
   120272   Fts3Expr *pExpr,                /* Allocate readers for this expression */
   120273   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
   120274   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
   120275   int *pRc                        /* IN/OUT: Error code */
   120276 ){
   120277   if( pExpr && SQLITE_OK==*pRc ){
   120278     if( pExpr->eType==FTSQUERY_PHRASE ){
   120279       int i;
   120280       int nToken = pExpr->pPhrase->nToken;
   120281       *pnToken += nToken;
   120282       for(i=0; i<nToken; i++){
   120283         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   120284         int rc = fts3TermSegReaderCursor(pCsr,
   120285             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
   120286         );
   120287         if( rc!=SQLITE_OK ){
   120288           *pRc = rc;
   120289           return;
   120290         }
   120291       }
   120292       assert( pExpr->pPhrase->iDoclistToken==0 );
   120293       pExpr->pPhrase->iDoclistToken = -1;
   120294     }else{
   120295       *pnOr += (pExpr->eType==FTSQUERY_OR);
   120296       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
   120297       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
   120298     }
   120299   }
   120300 }
   120301 
   120302 /*
   120303 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
   120304 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
   120305 **
   120306 ** This function assumes that pList points to a buffer allocated using
   120307 ** sqlite3_malloc(). This function takes responsibility for eventually
   120308 ** freeing the buffer.
   120309 */
   120310 static void fts3EvalPhraseMergeToken(
   120311   Fts3Table *pTab,                /* FTS Table pointer */
   120312   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
   120313   int iToken,                     /* Token pList/nList corresponds to */
   120314   char *pList,                    /* Pointer to doclist */
   120315   int nList                       /* Number of bytes in pList */
   120316 ){
   120317   assert( iToken!=p->iDoclistToken );
   120318 
   120319   if( pList==0 ){
   120320     sqlite3_free(p->doclist.aAll);
   120321     p->doclist.aAll = 0;
   120322     p->doclist.nAll = 0;
   120323   }
   120324 
   120325   else if( p->iDoclistToken<0 ){
   120326     p->doclist.aAll = pList;
   120327     p->doclist.nAll = nList;
   120328   }
   120329 
   120330   else if( p->doclist.aAll==0 ){
   120331     sqlite3_free(pList);
   120332   }
   120333 
   120334   else {
   120335     char *pLeft;
   120336     char *pRight;
   120337     int nLeft;
   120338     int nRight;
   120339     int nDiff;
   120340 
   120341     if( p->iDoclistToken<iToken ){
   120342       pLeft = p->doclist.aAll;
   120343       nLeft = p->doclist.nAll;
   120344       pRight = pList;
   120345       nRight = nList;
   120346       nDiff = iToken - p->iDoclistToken;
   120347     }else{
   120348       pRight = p->doclist.aAll;
   120349       nRight = p->doclist.nAll;
   120350       pLeft = pList;
   120351       nLeft = nList;
   120352       nDiff = p->iDoclistToken - iToken;
   120353     }
   120354 
   120355     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
   120356     sqlite3_free(pLeft);
   120357     p->doclist.aAll = pRight;
   120358     p->doclist.nAll = nRight;
   120359   }
   120360 
   120361   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
   120362 }
   120363 
   120364 /*
   120365 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
   120366 ** does not take deferred tokens into account.
   120367 **
   120368 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120369 */
   120370 static int fts3EvalPhraseLoad(
   120371   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120372   Fts3Phrase *p                   /* Phrase object */
   120373 ){
   120374   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120375   int iToken;
   120376   int rc = SQLITE_OK;
   120377 
   120378   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
   120379     Fts3PhraseToken *pToken = &p->aToken[iToken];
   120380     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
   120381 
   120382     if( pToken->pSegcsr ){
   120383       int nThis = 0;
   120384       char *pThis = 0;
   120385       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
   120386       if( rc==SQLITE_OK ){
   120387         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
   120388       }
   120389     }
   120390     assert( pToken->pSegcsr==0 );
   120391   }
   120392 
   120393   return rc;
   120394 }
   120395 
   120396 /*
   120397 ** This function is called on each phrase after the position lists for
   120398 ** any deferred tokens have been loaded into memory. It updates the phrases
   120399 ** current position list to include only those positions that are really
   120400 ** instances of the phrase (after considering deferred tokens). If this
   120401 ** means that the phrase does not appear in the current row, doclist.pList
   120402 ** and doclist.nList are both zeroed.
   120403 **
   120404 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120405 */
   120406 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
   120407   int iToken;                     /* Used to iterate through phrase tokens */
   120408   char *aPoslist = 0;             /* Position list for deferred tokens */
   120409   int nPoslist = 0;               /* Number of bytes in aPoslist */
   120410   int iPrev = -1;                 /* Token number of previous deferred token */
   120411 
   120412   assert( pPhrase->doclist.bFreeList==0 );
   120413 
   120414   for(iToken=0; iToken<pPhrase->nToken; iToken++){
   120415     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
   120416     Fts3DeferredToken *pDeferred = pToken->pDeferred;
   120417 
   120418     if( pDeferred ){
   120419       char *pList;
   120420       int nList;
   120421       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
   120422       if( rc!=SQLITE_OK ) return rc;
   120423 
   120424       if( pList==0 ){
   120425         sqlite3_free(aPoslist);
   120426         pPhrase->doclist.pList = 0;
   120427         pPhrase->doclist.nList = 0;
   120428         return SQLITE_OK;
   120429 
   120430       }else if( aPoslist==0 ){
   120431         aPoslist = pList;
   120432         nPoslist = nList;
   120433 
   120434       }else{
   120435         char *aOut = pList;
   120436         char *p1 = aPoslist;
   120437         char *p2 = aOut;
   120438 
   120439         assert( iPrev>=0 );
   120440         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
   120441         sqlite3_free(aPoslist);
   120442         aPoslist = pList;
   120443         nPoslist = (int)(aOut - aPoslist);
   120444         if( nPoslist==0 ){
   120445           sqlite3_free(aPoslist);
   120446           pPhrase->doclist.pList = 0;
   120447           pPhrase->doclist.nList = 0;
   120448           return SQLITE_OK;
   120449         }
   120450       }
   120451       iPrev = iToken;
   120452     }
   120453   }
   120454 
   120455   if( iPrev>=0 ){
   120456     int nMaxUndeferred = pPhrase->iDoclistToken;
   120457     if( nMaxUndeferred<0 ){
   120458       pPhrase->doclist.pList = aPoslist;
   120459       pPhrase->doclist.nList = nPoslist;
   120460       pPhrase->doclist.iDocid = pCsr->iPrevId;
   120461       pPhrase->doclist.bFreeList = 1;
   120462     }else{
   120463       int nDistance;
   120464       char *p1;
   120465       char *p2;
   120466       char *aOut;
   120467 
   120468       if( nMaxUndeferred>iPrev ){
   120469         p1 = aPoslist;
   120470         p2 = pPhrase->doclist.pList;
   120471         nDistance = nMaxUndeferred - iPrev;
   120472       }else{
   120473         p1 = pPhrase->doclist.pList;
   120474         p2 = aPoslist;
   120475         nDistance = iPrev - nMaxUndeferred;
   120476       }
   120477 
   120478       aOut = (char *)sqlite3_malloc(nPoslist+8);
   120479       if( !aOut ){
   120480         sqlite3_free(aPoslist);
   120481         return SQLITE_NOMEM;
   120482       }
   120483 
   120484       pPhrase->doclist.pList = aOut;
   120485       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
   120486         pPhrase->doclist.bFreeList = 1;
   120487         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
   120488       }else{
   120489         sqlite3_free(aOut);
   120490         pPhrase->doclist.pList = 0;
   120491         pPhrase->doclist.nList = 0;
   120492       }
   120493       sqlite3_free(aPoslist);
   120494     }
   120495   }
   120496 
   120497   return SQLITE_OK;
   120498 }
   120499 
   120500 /*
   120501 ** This function is called for each Fts3Phrase in a full-text query
   120502 ** expression to initialize the mechanism for returning rows. Once this
   120503 ** function has been called successfully on an Fts3Phrase, it may be
   120504 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
   120505 **
   120506 ** If parameter bOptOk is true, then the phrase may (or may not) use the
   120507 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
   120508 ** memory within this call.
   120509 **
   120510 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
   120511 */
   120512 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
   120513   int rc;                         /* Error code */
   120514   Fts3PhraseToken *pFirst = &p->aToken[0];
   120515   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120516 
   120517   if( pCsr->bDesc==pTab->bDescIdx
   120518    && bOptOk==1
   120519    && p->nToken==1
   120520    && pFirst->pSegcsr
   120521    && pFirst->pSegcsr->bLookup
   120522    && pFirst->bFirst==0
   120523   ){
   120524     /* Use the incremental approach. */
   120525     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
   120526     rc = sqlite3Fts3MsrIncrStart(
   120527         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
   120528     p->bIncr = 1;
   120529 
   120530   }else{
   120531     /* Load the full doclist for the phrase into memory. */
   120532     rc = fts3EvalPhraseLoad(pCsr, p);
   120533     p->bIncr = 0;
   120534   }
   120535 
   120536   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
   120537   return rc;
   120538 }
   120539 
   120540 /*
   120541 ** This function is used to iterate backwards (from the end to start)
   120542 ** through doclists. It is used by this module to iterate through phrase
   120543 ** doclists in reverse and by the fts3_write.c module to iterate through
   120544 ** pending-terms lists when writing to databases with "order=desc".
   120545 **
   120546 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
   120547 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
   120548 ** function iterates from the end of the doclist to the beginning.
   120549 */
   120550 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
   120551   int bDescIdx,                   /* True if the doclist is desc */
   120552   char *aDoclist,                 /* Pointer to entire doclist */
   120553   int nDoclist,                   /* Length of aDoclist in bytes */
   120554   char **ppIter,                  /* IN/OUT: Iterator pointer */
   120555   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
   120556   int *pnList,                    /* IN/OUT: List length pointer */
   120557   u8 *pbEof                       /* OUT: End-of-file flag */
   120558 ){
   120559   char *p = *ppIter;
   120560 
   120561   assert( nDoclist>0 );
   120562   assert( *pbEof==0 );
   120563   assert( p || *piDocid==0 );
   120564   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
   120565 
   120566   if( p==0 ){
   120567     sqlite3_int64 iDocid = 0;
   120568     char *pNext = 0;
   120569     char *pDocid = aDoclist;
   120570     char *pEnd = &aDoclist[nDoclist];
   120571     int iMul = 1;
   120572 
   120573     while( pDocid<pEnd ){
   120574       sqlite3_int64 iDelta;
   120575       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
   120576       iDocid += (iMul * iDelta);
   120577       pNext = pDocid;
   120578       fts3PoslistCopy(0, &pDocid);
   120579       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
   120580       iMul = (bDescIdx ? -1 : 1);
   120581     }
   120582 
   120583     *pnList = (int)(pEnd - pNext);
   120584     *ppIter = pNext;
   120585     *piDocid = iDocid;
   120586   }else{
   120587     int iMul = (bDescIdx ? -1 : 1);
   120588     sqlite3_int64 iDelta;
   120589     fts3GetReverseVarint(&p, aDoclist, &iDelta);
   120590     *piDocid -= (iMul * iDelta);
   120591 
   120592     if( p==aDoclist ){
   120593       *pbEof = 1;
   120594     }else{
   120595       char *pSave = p;
   120596       fts3ReversePoslist(aDoclist, &p);
   120597       *pnList = (int)(pSave - p);
   120598     }
   120599     *ppIter = p;
   120600   }
   120601 }
   120602 
   120603 /*
   120604 ** Attempt to move the phrase iterator to point to the next matching docid.
   120605 ** If an error occurs, return an SQLite error code. Otherwise, return
   120606 ** SQLITE_OK.
   120607 **
   120608 ** If there is no "next" entry and no error occurs, then *pbEof is set to
   120609 ** 1 before returning. Otherwise, if no error occurs and the iterator is
   120610 ** successfully advanced, *pbEof is set to 0.
   120611 */
   120612 static int fts3EvalPhraseNext(
   120613   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120614   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
   120615   u8 *pbEof                       /* OUT: Set to 1 if EOF */
   120616 ){
   120617   int rc = SQLITE_OK;
   120618   Fts3Doclist *pDL = &p->doclist;
   120619   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120620 
   120621   if( p->bIncr ){
   120622     assert( p->nToken==1 );
   120623     assert( pDL->pNextDocid==0 );
   120624     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
   120625         &pDL->iDocid, &pDL->pList, &pDL->nList
   120626     );
   120627     if( rc==SQLITE_OK && !pDL->pList ){
   120628       *pbEof = 1;
   120629     }
   120630   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
   120631     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
   120632         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
   120633     );
   120634     pDL->pList = pDL->pNextDocid;
   120635   }else{
   120636     char *pIter;                            /* Used to iterate through aAll */
   120637     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
   120638     if( pDL->pNextDocid ){
   120639       pIter = pDL->pNextDocid;
   120640     }else{
   120641       pIter = pDL->aAll;
   120642     }
   120643 
   120644     if( pIter>=pEnd ){
   120645       /* We have already reached the end of this doclist. EOF. */
   120646       *pbEof = 1;
   120647     }else{
   120648       sqlite3_int64 iDelta;
   120649       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
   120650       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
   120651         pDL->iDocid += iDelta;
   120652       }else{
   120653         pDL->iDocid -= iDelta;
   120654       }
   120655       pDL->pList = pIter;
   120656       fts3PoslistCopy(0, &pIter);
   120657       pDL->nList = (int)(pIter - pDL->pList);
   120658 
   120659       /* pIter now points just past the 0x00 that terminates the position-
   120660       ** list for document pDL->iDocid. However, if this position-list was
   120661       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
   120662       ** point to the start of the next docid value. The following line deals
   120663       ** with this case by advancing pIter past the zero-padding added by
   120664       ** fts3EvalNearTrim().  */
   120665       while( pIter<pEnd && *pIter==0 ) pIter++;
   120666 
   120667       pDL->pNextDocid = pIter;
   120668       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
   120669       *pbEof = 0;
   120670     }
   120671   }
   120672 
   120673   return rc;
   120674 }
   120675 
   120676 /*
   120677 **
   120678 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   120679 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
   120680 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
   120681 ** expressions for which all descendent tokens are deferred.
   120682 **
   120683 ** If parameter bOptOk is zero, then it is guaranteed that the
   120684 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
   120685 ** each phrase in the expression (subject to deferred token processing).
   120686 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
   120687 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
   120688 **
   120689 ** If an error occurs within this function, *pRc is set to an SQLite error
   120690 ** code before returning.
   120691 */
   120692 static void fts3EvalStartReaders(
   120693   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120694   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
   120695   int bOptOk,                     /* True to enable incremental loading */
   120696   int *pRc                        /* IN/OUT: Error code */
   120697 ){
   120698   if( pExpr && SQLITE_OK==*pRc ){
   120699     if( pExpr->eType==FTSQUERY_PHRASE ){
   120700       int i;
   120701       int nToken = pExpr->pPhrase->nToken;
   120702       for(i=0; i<nToken; i++){
   120703         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
   120704       }
   120705       pExpr->bDeferred = (i==nToken);
   120706       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
   120707     }else{
   120708       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
   120709       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
   120710       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
   120711     }
   120712   }
   120713 }
   120714 
   120715 /*
   120716 ** An array of the following structures is assembled as part of the process
   120717 ** of selecting tokens to defer before the query starts executing (as part
   120718 ** of the xFilter() method). There is one element in the array for each
   120719 ** token in the FTS expression.
   120720 **
   120721 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
   120722 ** to phrases that are connected only by AND and NEAR operators (not OR or
   120723 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
   120724 ** separately. The root of a tokens AND/NEAR cluster is stored in
   120725 ** Fts3TokenAndCost.pRoot.
   120726 */
   120727 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
   120728 struct Fts3TokenAndCost {
   120729   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
   120730   int iToken;                     /* Position of token in phrase */
   120731   Fts3PhraseToken *pToken;        /* The token itself */
   120732   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
   120733   int nOvfl;                      /* Number of overflow pages to load doclist */
   120734   int iCol;                       /* The column the token must match */
   120735 };
   120736 
   120737 /*
   120738 ** This function is used to populate an allocated Fts3TokenAndCost array.
   120739 **
   120740 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   120741 ** Otherwise, if an error occurs during execution, *pRc is set to an
   120742 ** SQLite error code.
   120743 */
   120744 static void fts3EvalTokenCosts(
   120745   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120746   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
   120747   Fts3Expr *pExpr,                /* Expression to consider */
   120748   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
   120749   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
   120750   int *pRc                        /* IN/OUT: Error code */
   120751 ){
   120752   if( *pRc==SQLITE_OK ){
   120753     if( pExpr->eType==FTSQUERY_PHRASE ){
   120754       Fts3Phrase *pPhrase = pExpr->pPhrase;
   120755       int i;
   120756       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
   120757         Fts3TokenAndCost *pTC = (*ppTC)++;
   120758         pTC->pPhrase = pPhrase;
   120759         pTC->iToken = i;
   120760         pTC->pRoot = pRoot;
   120761         pTC->pToken = &pPhrase->aToken[i];
   120762         pTC->iCol = pPhrase->iColumn;
   120763         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
   120764       }
   120765     }else if( pExpr->eType!=FTSQUERY_NOT ){
   120766       assert( pExpr->eType==FTSQUERY_OR
   120767            || pExpr->eType==FTSQUERY_AND
   120768            || pExpr->eType==FTSQUERY_NEAR
   120769       );
   120770       assert( pExpr->pLeft && pExpr->pRight );
   120771       if( pExpr->eType==FTSQUERY_OR ){
   120772         pRoot = pExpr->pLeft;
   120773         **ppOr = pRoot;
   120774         (*ppOr)++;
   120775       }
   120776       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
   120777       if( pExpr->eType==FTSQUERY_OR ){
   120778         pRoot = pExpr->pRight;
   120779         **ppOr = pRoot;
   120780         (*ppOr)++;
   120781       }
   120782       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
   120783     }
   120784   }
   120785 }
   120786 
   120787 /*
   120788 ** Determine the average document (row) size in pages. If successful,
   120789 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
   120790 ** an SQLite error code.
   120791 **
   120792 ** The average document size in pages is calculated by first calculating
   120793 ** determining the average size in bytes, B. If B is less than the amount
   120794 ** of data that will fit on a single leaf page of an intkey table in
   120795 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
   120796 ** the number of overflow pages consumed by a record B bytes in size.
   120797 */
   120798 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   120799   if( pCsr->nRowAvg==0 ){
   120800     /* The average document size, which is required to calculate the cost
   120801     ** of each doclist, has not yet been determined. Read the required
   120802     ** data from the %_stat table to calculate it.
   120803     **
   120804     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   120805     ** varints, where nCol is the number of columns in the FTS3 table.
   120806     ** The first varint is the number of documents currently stored in
   120807     ** the table. The following nCol varints contain the total amount of
   120808     ** data stored in all rows of each column of the table, from left
   120809     ** to right.
   120810     */
   120811     int rc;
   120812     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   120813     sqlite3_stmt *pStmt;
   120814     sqlite3_int64 nDoc = 0;
   120815     sqlite3_int64 nByte = 0;
   120816     const char *pEnd;
   120817     const char *a;
   120818 
   120819     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
   120820     if( rc!=SQLITE_OK ) return rc;
   120821     a = sqlite3_column_blob(pStmt, 0);
   120822     assert( a );
   120823 
   120824     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   120825     a += sqlite3Fts3GetVarint(a, &nDoc);
   120826     while( a<pEnd ){
   120827       a += sqlite3Fts3GetVarint(a, &nByte);
   120828     }
   120829     if( nDoc==0 || nByte==0 ){
   120830       sqlite3_reset(pStmt);
   120831       return FTS_CORRUPT_VTAB;
   120832     }
   120833 
   120834     pCsr->nDoc = nDoc;
   120835     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
   120836     assert( pCsr->nRowAvg>0 );
   120837     rc = sqlite3_reset(pStmt);
   120838     if( rc!=SQLITE_OK ) return rc;
   120839   }
   120840 
   120841   *pnPage = pCsr->nRowAvg;
   120842   return SQLITE_OK;
   120843 }
   120844 
   120845 /*
   120846 ** This function is called to select the tokens (if any) that will be
   120847 ** deferred. The array aTC[] has already been populated when this is
   120848 ** called.
   120849 **
   120850 ** This function is called once for each AND/NEAR cluster in the
   120851 ** expression. Each invocation determines which tokens to defer within
   120852 ** the cluster with root node pRoot. See comments above the definition
   120853 ** of struct Fts3TokenAndCost for more details.
   120854 **
   120855 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
   120856 ** called on each token to defer. Otherwise, an SQLite error code is
   120857 ** returned.
   120858 */
   120859 static int fts3EvalSelectDeferred(
   120860   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   120861   Fts3Expr *pRoot,                /* Consider tokens with this root node */
   120862   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
   120863   int nTC                         /* Number of entries in aTC[] */
   120864 ){
   120865   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120866   int nDocSize = 0;               /* Number of pages per doc loaded */
   120867   int rc = SQLITE_OK;             /* Return code */
   120868   int ii;                         /* Iterator variable for various purposes */
   120869   int nOvfl = 0;                  /* Total overflow pages used by doclists */
   120870   int nToken = 0;                 /* Total number of tokens in cluster */
   120871 
   120872   int nMinEst = 0;                /* The minimum count for any phrase so far. */
   120873   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
   120874 
   120875   /* Tokens are never deferred for FTS tables created using the content=xxx
   120876   ** option. The reason being that it is not guaranteed that the content
   120877   ** table actually contains the same data as the index. To prevent this from
   120878   ** causing any problems, the deferred token optimization is completely
   120879   ** disabled for content=xxx tables. */
   120880   if( pTab->zContentTbl ){
   120881     return SQLITE_OK;
   120882   }
   120883 
   120884   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
   120885   ** associated with the tokens spill onto overflow pages, or if there is
   120886   ** only 1 token, exit early. No tokens to defer in this case. */
   120887   for(ii=0; ii<nTC; ii++){
   120888     if( aTC[ii].pRoot==pRoot ){
   120889       nOvfl += aTC[ii].nOvfl;
   120890       nToken++;
   120891     }
   120892   }
   120893   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
   120894 
   120895   /* Obtain the average docsize (in pages). */
   120896   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
   120897   assert( rc!=SQLITE_OK || nDocSize>0 );
   120898 
   120899 
   120900   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
   120901   ** of the number of overflow pages that will be loaded by the pager layer
   120902   ** to retrieve the entire doclist for the token from the full-text index.
   120903   ** Load the doclists for tokens that are either:
   120904   **
   120905   **   a. The cheapest token in the entire query (i.e. the one visited by the
   120906   **      first iteration of this loop), or
   120907   **
   120908   **   b. Part of a multi-token phrase.
   120909   **
   120910   ** After each token doclist is loaded, merge it with the others from the
   120911   ** same phrase and count the number of documents that the merged doclist
   120912   ** contains. Set variable "nMinEst" to the smallest number of documents in
   120913   ** any phrase doclist for which 1 or more token doclists have been loaded.
   120914   ** Let nOther be the number of other phrases for which it is certain that
   120915   ** one or more tokens will not be deferred.
   120916   **
   120917   ** Then, for each token, defer it if loading the doclist would result in
   120918   ** loading N or more overflow pages into memory, where N is computed as:
   120919   **
   120920   **    (nMinEst + 4^nOther - 1) / (4^nOther)
   120921   */
   120922   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
   120923     int iTC;                      /* Used to iterate through aTC[] array. */
   120924     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
   120925 
   120926     /* Set pTC to point to the cheapest remaining token. */
   120927     for(iTC=0; iTC<nTC; iTC++){
   120928       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
   120929        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
   120930       ){
   120931         pTC = &aTC[iTC];
   120932       }
   120933     }
   120934     assert( pTC );
   120935 
   120936     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
   120937       /* The number of overflow pages to load for this (and therefore all
   120938       ** subsequent) tokens is greater than the estimated number of pages
   120939       ** that will be loaded if all subsequent tokens are deferred.
   120940       */
   120941       Fts3PhraseToken *pToken = pTC->pToken;
   120942       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
   120943       fts3SegReaderCursorFree(pToken->pSegcsr);
   120944       pToken->pSegcsr = 0;
   120945     }else{
   120946       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
   120947       ** for-loop. Except, limit the value to 2^24 to prevent it from
   120948       ** overflowing the 32-bit integer it is stored in. */
   120949       if( ii<12 ) nLoad4 = nLoad4*4;
   120950 
   120951       if( ii==0 || pTC->pPhrase->nToken>1 ){
   120952         /* Either this is the cheapest token in the entire query, or it is
   120953         ** part of a multi-token phrase. Either way, the entire doclist will
   120954         ** (eventually) be loaded into memory. It may as well be now. */
   120955         Fts3PhraseToken *pToken = pTC->pToken;
   120956         int nList = 0;
   120957         char *pList = 0;
   120958         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
   120959         assert( rc==SQLITE_OK || pList==0 );
   120960         if( rc==SQLITE_OK ){
   120961           int nCount;
   120962           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
   120963           nCount = fts3DoclistCountDocids(
   120964               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
   120965           );
   120966           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
   120967         }
   120968       }
   120969     }
   120970     pTC->pToken = 0;
   120971   }
   120972 
   120973   return rc;
   120974 }
   120975 
   120976 /*
   120977 ** This function is called from within the xFilter method. It initializes
   120978 ** the full-text query currently stored in pCsr->pExpr. To iterate through
   120979 ** the results of a query, the caller does:
   120980 **
   120981 **    fts3EvalStart(pCsr);
   120982 **    while( 1 ){
   120983 **      fts3EvalNext(pCsr);
   120984 **      if( pCsr->bEof ) break;
   120985 **      ... return row pCsr->iPrevId to the caller ...
   120986 **    }
   120987 */
   120988 static int fts3EvalStart(Fts3Cursor *pCsr){
   120989   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   120990   int rc = SQLITE_OK;
   120991   int nToken = 0;
   120992   int nOr = 0;
   120993 
   120994   /* Allocate a MultiSegReader for each token in the expression. */
   120995   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
   120996 
   120997   /* Determine which, if any, tokens in the expression should be deferred. */
   120998   if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
   120999     Fts3TokenAndCost *aTC;
   121000     Fts3Expr **apOr;
   121001     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
   121002         sizeof(Fts3TokenAndCost) * nToken
   121003       + sizeof(Fts3Expr *) * nOr * 2
   121004     );
   121005     apOr = (Fts3Expr **)&aTC[nToken];
   121006 
   121007     if( !aTC ){
   121008       rc = SQLITE_NOMEM;
   121009     }else{
   121010       int ii;
   121011       Fts3TokenAndCost *pTC = aTC;
   121012       Fts3Expr **ppOr = apOr;
   121013 
   121014       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
   121015       nToken = (int)(pTC-aTC);
   121016       nOr = (int)(ppOr-apOr);
   121017 
   121018       if( rc==SQLITE_OK ){
   121019         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
   121020         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
   121021           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
   121022         }
   121023       }
   121024 
   121025       sqlite3_free(aTC);
   121026     }
   121027   }
   121028 
   121029   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
   121030   return rc;
   121031 }
   121032 
   121033 /*
   121034 ** Invalidate the current position list for phrase pPhrase.
   121035 */
   121036 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
   121037   if( pPhrase->doclist.bFreeList ){
   121038     sqlite3_free(pPhrase->doclist.pList);
   121039   }
   121040   pPhrase->doclist.pList = 0;
   121041   pPhrase->doclist.nList = 0;
   121042   pPhrase->doclist.bFreeList = 0;
   121043 }
   121044 
   121045 /*
   121046 ** This function is called to edit the position list associated with
   121047 ** the phrase object passed as the fifth argument according to a NEAR
   121048 ** condition. For example:
   121049 **
   121050 **     abc NEAR/5 "def ghi"
   121051 **
   121052 ** Parameter nNear is passed the NEAR distance of the expression (5 in
   121053 ** the example above). When this function is called, *paPoslist points to
   121054 ** the position list, and *pnToken is the number of phrase tokens in, the
   121055 ** phrase on the other side of the NEAR operator to pPhrase. For example,
   121056 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
   121057 ** the position list associated with phrase "abc".
   121058 **
   121059 ** All positions in the pPhrase position list that are not sufficiently
   121060 ** close to a position in the *paPoslist position list are removed. If this
   121061 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
   121062 **
   121063 ** Before returning, *paPoslist is set to point to the position lsit
   121064 ** associated with pPhrase. And *pnToken is set to the number of tokens in
   121065 ** pPhrase.
   121066 */
   121067 static int fts3EvalNearTrim(
   121068   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
   121069   char *aTmp,                     /* Temporary space to use */
   121070   char **paPoslist,               /* IN/OUT: Position list */
   121071   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
   121072   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
   121073 ){
   121074   int nParam1 = nNear + pPhrase->nToken;
   121075   int nParam2 = nNear + *pnToken;
   121076   int nNew;
   121077   char *p2;
   121078   char *pOut;
   121079   int res;
   121080 
   121081   assert( pPhrase->doclist.pList );
   121082 
   121083   p2 = pOut = pPhrase->doclist.pList;
   121084   res = fts3PoslistNearMerge(
   121085     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
   121086   );
   121087   if( res ){
   121088     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
   121089     assert( pPhrase->doclist.pList[nNew]=='\0' );
   121090     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
   121091     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
   121092     pPhrase->doclist.nList = nNew;
   121093     *paPoslist = pPhrase->doclist.pList;
   121094     *pnToken = pPhrase->nToken;
   121095   }
   121096 
   121097   return res;
   121098 }
   121099 
   121100 /*
   121101 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
   121102 ** Otherwise, it advances the expression passed as the second argument to
   121103 ** point to the next matching row in the database. Expressions iterate through
   121104 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
   121105 ** or descending if it is non-zero.
   121106 **
   121107 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
   121108 ** successful, the following variables in pExpr are set:
   121109 **
   121110 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
   121111 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
   121112 **
   121113 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
   121114 ** at EOF, then the following variables are populated with the position list
   121115 ** for the phrase for the visited row:
   121116 **
   121117 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
   121118 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
   121119 **
   121120 ** It says above that this function advances the expression to the next
   121121 ** matching row. This is usually true, but there are the following exceptions:
   121122 **
   121123 **   1. Deferred tokens are not taken into account. If a phrase consists
   121124 **      entirely of deferred tokens, it is assumed to match every row in
   121125 **      the db. In this case the position-list is not populated at all.
   121126 **
   121127 **      Or, if a phrase contains one or more deferred tokens and one or
   121128 **      more non-deferred tokens, then the expression is advanced to the
   121129 **      next possible match, considering only non-deferred tokens. In other
   121130 **      words, if the phrase is "A B C", and "B" is deferred, the expression
   121131 **      is advanced to the next row that contains an instance of "A * C",
   121132 **      where "*" may match any single token. The position list in this case
   121133 **      is populated as for "A * C" before returning.
   121134 **
   121135 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
   121136 **      advanced to point to the next row that matches "x AND y".
   121137 **
   121138 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
   121139 ** really a match, taking into account deferred tokens and NEAR operators.
   121140 */
   121141 static void fts3EvalNextRow(
   121142   Fts3Cursor *pCsr,               /* FTS Cursor handle */
   121143   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
   121144   int *pRc                        /* IN/OUT: Error code */
   121145 ){
   121146   if( *pRc==SQLITE_OK ){
   121147     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
   121148     assert( pExpr->bEof==0 );
   121149     pExpr->bStart = 1;
   121150 
   121151     switch( pExpr->eType ){
   121152       case FTSQUERY_NEAR:
   121153       case FTSQUERY_AND: {
   121154         Fts3Expr *pLeft = pExpr->pLeft;
   121155         Fts3Expr *pRight = pExpr->pRight;
   121156         assert( !pLeft->bDeferred || !pRight->bDeferred );
   121157 
   121158         if( pLeft->bDeferred ){
   121159           /* LHS is entirely deferred. So we assume it matches every row.
   121160           ** Advance the RHS iterator to find the next row visited. */
   121161           fts3EvalNextRow(pCsr, pRight, pRc);
   121162           pExpr->iDocid = pRight->iDocid;
   121163           pExpr->bEof = pRight->bEof;
   121164         }else if( pRight->bDeferred ){
   121165           /* RHS is entirely deferred. So we assume it matches every row.
   121166           ** Advance the LHS iterator to find the next row visited. */
   121167           fts3EvalNextRow(pCsr, pLeft, pRc);
   121168           pExpr->iDocid = pLeft->iDocid;
   121169           pExpr->bEof = pLeft->bEof;
   121170         }else{
   121171           /* Neither the RHS or LHS are deferred. */
   121172           fts3EvalNextRow(pCsr, pLeft, pRc);
   121173           fts3EvalNextRow(pCsr, pRight, pRc);
   121174           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
   121175             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121176             if( iDiff==0 ) break;
   121177             if( iDiff<0 ){
   121178               fts3EvalNextRow(pCsr, pLeft, pRc);
   121179             }else{
   121180               fts3EvalNextRow(pCsr, pRight, pRc);
   121181             }
   121182           }
   121183           pExpr->iDocid = pLeft->iDocid;
   121184           pExpr->bEof = (pLeft->bEof || pRight->bEof);
   121185         }
   121186         break;
   121187       }
   121188 
   121189       case FTSQUERY_OR: {
   121190         Fts3Expr *pLeft = pExpr->pLeft;
   121191         Fts3Expr *pRight = pExpr->pRight;
   121192         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121193 
   121194         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
   121195         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
   121196 
   121197         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
   121198           fts3EvalNextRow(pCsr, pLeft, pRc);
   121199         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
   121200           fts3EvalNextRow(pCsr, pRight, pRc);
   121201         }else{
   121202           fts3EvalNextRow(pCsr, pLeft, pRc);
   121203           fts3EvalNextRow(pCsr, pRight, pRc);
   121204         }
   121205 
   121206         pExpr->bEof = (pLeft->bEof && pRight->bEof);
   121207         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
   121208         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
   121209           pExpr->iDocid = pLeft->iDocid;
   121210         }else{
   121211           pExpr->iDocid = pRight->iDocid;
   121212         }
   121213 
   121214         break;
   121215       }
   121216 
   121217       case FTSQUERY_NOT: {
   121218         Fts3Expr *pLeft = pExpr->pLeft;
   121219         Fts3Expr *pRight = pExpr->pRight;
   121220 
   121221         if( pRight->bStart==0 ){
   121222           fts3EvalNextRow(pCsr, pRight, pRc);
   121223           assert( *pRc!=SQLITE_OK || pRight->bStart );
   121224         }
   121225 
   121226         fts3EvalNextRow(pCsr, pLeft, pRc);
   121227         if( pLeft->bEof==0 ){
   121228           while( !*pRc
   121229               && !pRight->bEof
   121230               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
   121231           ){
   121232             fts3EvalNextRow(pCsr, pRight, pRc);
   121233           }
   121234         }
   121235         pExpr->iDocid = pLeft->iDocid;
   121236         pExpr->bEof = pLeft->bEof;
   121237         break;
   121238       }
   121239 
   121240       default: {
   121241         Fts3Phrase *pPhrase = pExpr->pPhrase;
   121242         fts3EvalInvalidatePoslist(pPhrase);
   121243         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
   121244         pExpr->iDocid = pPhrase->doclist.iDocid;
   121245         break;
   121246       }
   121247     }
   121248   }
   121249 }
   121250 
   121251 /*
   121252 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
   121253 ** cluster, then this function returns 1 immediately.
   121254 **
   121255 ** Otherwise, it checks if the current row really does match the NEAR
   121256 ** expression, using the data currently stored in the position lists
   121257 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
   121258 **
   121259 ** If the current row is a match, the position list associated with each
   121260 ** phrase in the NEAR expression is edited in place to contain only those
   121261 ** phrase instances sufficiently close to their peers to satisfy all NEAR
   121262 ** constraints. In this case it returns 1. If the NEAR expression does not
   121263 ** match the current row, 0 is returned. The position lists may or may not
   121264 ** be edited if 0 is returned.
   121265 */
   121266 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   121267   int res = 1;
   121268 
   121269   /* The following block runs if pExpr is the root of a NEAR query.
   121270   ** For example, the query:
   121271   **
   121272   **         "w" NEAR "x" NEAR "y" NEAR "z"
   121273   **
   121274   ** which is represented in tree form as:
   121275   **
   121276   **                               |
   121277   **                          +--NEAR--+      <-- root of NEAR query
   121278   **                          |        |
   121279   **                     +--NEAR--+   "z"
   121280   **                     |        |
   121281   **                +--NEAR--+   "y"
   121282   **                |        |
   121283   **               "w"      "x"
   121284   **
   121285   ** The right-hand child of a NEAR node is always a phrase. The
   121286   ** left-hand child may be either a phrase or a NEAR node. There are
   121287   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   121288   */
   121289   if( *pRc==SQLITE_OK
   121290    && pExpr->eType==FTSQUERY_NEAR
   121291    && pExpr->bEof==0
   121292    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   121293   ){
   121294     Fts3Expr *p;
   121295     int nTmp = 0;                 /* Bytes of temp space */
   121296     char *aTmp;                   /* Temp space for PoslistNearMerge() */
   121297 
   121298     /* Allocate temporary working space. */
   121299     for(p=pExpr; p->pLeft; p=p->pLeft){
   121300       nTmp += p->pRight->pPhrase->doclist.nList;
   121301     }
   121302     nTmp += p->pPhrase->doclist.nList;
   121303     aTmp = sqlite3_malloc(nTmp*2);
   121304     if( !aTmp ){
   121305       *pRc = SQLITE_NOMEM;
   121306       res = 0;
   121307     }else{
   121308       char *aPoslist = p->pPhrase->doclist.pList;
   121309       int nToken = p->pPhrase->nToken;
   121310 
   121311       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
   121312         Fts3Phrase *pPhrase = p->pRight->pPhrase;
   121313         int nNear = p->nNear;
   121314         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   121315       }
   121316 
   121317       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
   121318       nToken = pExpr->pRight->pPhrase->nToken;
   121319       for(p=pExpr->pLeft; p && res; p=p->pLeft){
   121320         int nNear;
   121321         Fts3Phrase *pPhrase;
   121322         assert( p->pParent && p->pParent->pLeft==p );
   121323         nNear = p->pParent->nNear;
   121324         pPhrase = (
   121325             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
   121326         );
   121327         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
   121328       }
   121329     }
   121330 
   121331     sqlite3_free(aTmp);
   121332   }
   121333 
   121334   return res;
   121335 }
   121336 
   121337 /*
   121338 ** This function is a helper function for fts3EvalTestDeferredAndNear().
   121339 ** Assuming no error occurs or has occurred, It returns non-zero if the
   121340 ** expression passed as the second argument matches the row that pCsr
   121341 ** currently points to, or zero if it does not.
   121342 **
   121343 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
   121344 ** If an error occurs during execution of this function, *pRc is set to
   121345 ** the appropriate SQLite error code. In this case the returned value is
   121346 ** undefined.
   121347 */
   121348 static int fts3EvalTestExpr(
   121349   Fts3Cursor *pCsr,               /* FTS cursor handle */
   121350   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
   121351   int *pRc                        /* IN/OUT: Error code */
   121352 ){
   121353   int bHit = 1;                   /* Return value */
   121354   if( *pRc==SQLITE_OK ){
   121355     switch( pExpr->eType ){
   121356       case FTSQUERY_NEAR:
   121357       case FTSQUERY_AND:
   121358         bHit = (
   121359             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   121360          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   121361          && fts3EvalNearTest(pExpr, pRc)
   121362         );
   121363 
   121364         /* If the NEAR expression does not match any rows, zero the doclist for
   121365         ** all phrases involved in the NEAR. This is because the snippet(),
   121366         ** offsets() and matchinfo() functions are not supposed to recognize
   121367         ** any instances of phrases that are part of unmatched NEAR queries.
   121368         ** For example if this expression:
   121369         **
   121370         **    ... MATCH 'a OR (b NEAR c)'
   121371         **
   121372         ** is matched against a row containing:
   121373         **
   121374         **        'a b d e'
   121375         **
   121376         ** then any snippet() should ony highlight the "a" term, not the "b"
   121377         ** (as "b" is part of a non-matching NEAR clause).
   121378         */
   121379         if( bHit==0
   121380          && pExpr->eType==FTSQUERY_NEAR
   121381          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   121382         ){
   121383           Fts3Expr *p;
   121384           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
   121385             if( p->pRight->iDocid==pCsr->iPrevId ){
   121386               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
   121387             }
   121388           }
   121389           if( p->iDocid==pCsr->iPrevId ){
   121390             fts3EvalInvalidatePoslist(p->pPhrase);
   121391           }
   121392         }
   121393 
   121394         break;
   121395 
   121396       case FTSQUERY_OR: {
   121397         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
   121398         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
   121399         bHit = bHit1 || bHit2;
   121400         break;
   121401       }
   121402 
   121403       case FTSQUERY_NOT:
   121404         bHit = (
   121405             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
   121406          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
   121407         );
   121408         break;
   121409 
   121410       default: {
   121411         if( pCsr->pDeferred
   121412          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
   121413         ){
   121414           Fts3Phrase *pPhrase = pExpr->pPhrase;
   121415           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
   121416           if( pExpr->bDeferred ){
   121417             fts3EvalInvalidatePoslist(pPhrase);
   121418           }
   121419           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
   121420           bHit = (pPhrase->doclist.pList!=0);
   121421           pExpr->iDocid = pCsr->iPrevId;
   121422         }else{
   121423           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
   121424         }
   121425         break;
   121426       }
   121427     }
   121428   }
   121429   return bHit;
   121430 }
   121431 
   121432 /*
   121433 ** This function is called as the second part of each xNext operation when
   121434 ** iterating through the results of a full-text query. At this point the
   121435 ** cursor points to a row that matches the query expression, with the
   121436 ** following caveats:
   121437 **
   121438 **   * Up until this point, "NEAR" operators in the expression have been
   121439 **     treated as "AND".
   121440 **
   121441 **   * Deferred tokens have not yet been considered.
   121442 **
   121443 ** If *pRc is not SQLITE_OK when this function is called, it immediately
   121444 ** returns 0. Otherwise, it tests whether or not after considering NEAR
   121445 ** operators and deferred tokens the current row is still a match for the
   121446 ** expression. It returns 1 if both of the following are true:
   121447 **
   121448 **   1. *pRc is SQLITE_OK when this function returns, and
   121449 **
   121450 **   2. After scanning the current FTS table row for the deferred tokens,
   121451 **      it is determined that the row does *not* match the query.
   121452 **
   121453 ** Or, if no error occurs and it seems the current row does match the FTS
   121454 ** query, return 0.
   121455 */
   121456 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
   121457   int rc = *pRc;
   121458   int bMiss = 0;
   121459   if( rc==SQLITE_OK ){
   121460 
   121461     /* If there are one or more deferred tokens, load the current row into
   121462     ** memory and scan it to determine the position list for each deferred
   121463     ** token. Then, see if this row is really a match, considering deferred
   121464     ** tokens and NEAR operators (neither of which were taken into account
   121465     ** earlier, by fts3EvalNextRow()).
   121466     */
   121467     if( pCsr->pDeferred ){
   121468       rc = fts3CursorSeek(0, pCsr);
   121469       if( rc==SQLITE_OK ){
   121470         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   121471       }
   121472     }
   121473     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
   121474 
   121475     /* Free the position-lists accumulated for each deferred token above. */
   121476     sqlite3Fts3FreeDeferredDoclists(pCsr);
   121477     *pRc = rc;
   121478   }
   121479   return (rc==SQLITE_OK && bMiss);
   121480 }
   121481 
   121482 /*
   121483 ** Advance to the next document that matches the FTS expression in
   121484 ** Fts3Cursor.pExpr.
   121485 */
   121486 static int fts3EvalNext(Fts3Cursor *pCsr){
   121487   int rc = SQLITE_OK;             /* Return Code */
   121488   Fts3Expr *pExpr = pCsr->pExpr;
   121489   assert( pCsr->isEof==0 );
   121490   if( pExpr==0 ){
   121491     pCsr->isEof = 1;
   121492   }else{
   121493     do {
   121494       if( pCsr->isRequireSeek==0 ){
   121495         sqlite3_reset(pCsr->pStmt);
   121496       }
   121497       assert( sqlite3_data_count(pCsr->pStmt)==0 );
   121498       fts3EvalNextRow(pCsr, pExpr, &rc);
   121499       pCsr->isEof = pExpr->bEof;
   121500       pCsr->isRequireSeek = 1;
   121501       pCsr->isMatchinfoNeeded = 1;
   121502       pCsr->iPrevId = pExpr->iDocid;
   121503     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
   121504   }
   121505   return rc;
   121506 }
   121507 
   121508 /*
   121509 ** Restart interation for expression pExpr so that the next call to
   121510 ** fts3EvalNext() visits the first row. Do not allow incremental
   121511 ** loading or merging of phrase doclists for this iteration.
   121512 **
   121513 ** If *pRc is other than SQLITE_OK when this function is called, it is
   121514 ** a no-op. If an error occurs within this function, *pRc is set to an
   121515 ** SQLite error code before returning.
   121516 */
   121517 static void fts3EvalRestart(
   121518   Fts3Cursor *pCsr,
   121519   Fts3Expr *pExpr,
   121520   int *pRc
   121521 ){
   121522   if( pExpr && *pRc==SQLITE_OK ){
   121523     Fts3Phrase *pPhrase = pExpr->pPhrase;
   121524 
   121525     if( pPhrase ){
   121526       fts3EvalInvalidatePoslist(pPhrase);
   121527       if( pPhrase->bIncr ){
   121528         assert( pPhrase->nToken==1 );
   121529         assert( pPhrase->aToken[0].pSegcsr );
   121530         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
   121531         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
   121532       }
   121533 
   121534       pPhrase->doclist.pNextDocid = 0;
   121535       pPhrase->doclist.iDocid = 0;
   121536     }
   121537 
   121538     pExpr->iDocid = 0;
   121539     pExpr->bEof = 0;
   121540     pExpr->bStart = 0;
   121541 
   121542     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
   121543     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
   121544   }
   121545 }
   121546 
   121547 /*
   121548 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
   121549 ** expression rooted at pExpr, the cursor iterates through all rows matched
   121550 ** by pExpr, calling this function for each row. This function increments
   121551 ** the values in Fts3Expr.aMI[] according to the position-list currently
   121552 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
   121553 ** expression nodes.
   121554 */
   121555 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
   121556   if( pExpr ){
   121557     Fts3Phrase *pPhrase = pExpr->pPhrase;
   121558     if( pPhrase && pPhrase->doclist.pList ){
   121559       int iCol = 0;
   121560       char *p = pPhrase->doclist.pList;
   121561 
   121562       assert( *p );
   121563       while( 1 ){
   121564         u8 c = 0;
   121565         int iCnt = 0;
   121566         while( 0xFE & (*p | c) ){
   121567           if( (c&0x80)==0 ) iCnt++;
   121568           c = *p++ & 0x80;
   121569         }
   121570 
   121571         /* aMI[iCol*3 + 1] = Number of occurrences
   121572         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
   121573         */
   121574         pExpr->aMI[iCol*3 + 1] += iCnt;
   121575         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
   121576         if( *p==0x00 ) break;
   121577         p++;
   121578         p += sqlite3Fts3GetVarint32(p, &iCol);
   121579       }
   121580     }
   121581 
   121582     fts3EvalUpdateCounts(pExpr->pLeft);
   121583     fts3EvalUpdateCounts(pExpr->pRight);
   121584   }
   121585 }
   121586 
   121587 /*
   121588 ** Expression pExpr must be of type FTSQUERY_PHRASE.
   121589 **
   121590 ** If it is not already allocated and populated, this function allocates and
   121591 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
   121592 ** of a NEAR expression, then it also allocates and populates the same array
   121593 ** for all other phrases that are part of the NEAR expression.
   121594 **
   121595 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
   121596 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
   121597 */
   121598 static int fts3EvalGatherStats(
   121599   Fts3Cursor *pCsr,               /* Cursor object */
   121600   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
   121601 ){
   121602   int rc = SQLITE_OK;             /* Return code */
   121603 
   121604   assert( pExpr->eType==FTSQUERY_PHRASE );
   121605   if( pExpr->aMI==0 ){
   121606     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121607     Fts3Expr *pRoot;                /* Root of NEAR expression */
   121608     Fts3Expr *p;                    /* Iterator used for several purposes */
   121609 
   121610     sqlite3_int64 iPrevId = pCsr->iPrevId;
   121611     sqlite3_int64 iDocid;
   121612     u8 bEof;
   121613 
   121614     /* Find the root of the NEAR expression */
   121615     pRoot = pExpr;
   121616     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
   121617       pRoot = pRoot->pParent;
   121618     }
   121619     iDocid = pRoot->iDocid;
   121620     bEof = pRoot->bEof;
   121621     assert( pRoot->bStart );
   121622 
   121623     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
   121624     for(p=pRoot; p; p=p->pLeft){
   121625       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
   121626       assert( pE->aMI==0 );
   121627       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
   121628       if( !pE->aMI ) return SQLITE_NOMEM;
   121629       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
   121630     }
   121631 
   121632     fts3EvalRestart(pCsr, pRoot, &rc);
   121633 
   121634     while( pCsr->isEof==0 && rc==SQLITE_OK ){
   121635 
   121636       do {
   121637         /* Ensure the %_content statement is reset. */
   121638         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
   121639         assert( sqlite3_data_count(pCsr->pStmt)==0 );
   121640 
   121641         /* Advance to the next document */
   121642         fts3EvalNextRow(pCsr, pRoot, &rc);
   121643         pCsr->isEof = pRoot->bEof;
   121644         pCsr->isRequireSeek = 1;
   121645         pCsr->isMatchinfoNeeded = 1;
   121646         pCsr->iPrevId = pRoot->iDocid;
   121647       }while( pCsr->isEof==0
   121648            && pRoot->eType==FTSQUERY_NEAR
   121649            && fts3EvalTestDeferredAndNear(pCsr, &rc)
   121650       );
   121651 
   121652       if( rc==SQLITE_OK && pCsr->isEof==0 ){
   121653         fts3EvalUpdateCounts(pRoot);
   121654       }
   121655     }
   121656 
   121657     pCsr->isEof = 0;
   121658     pCsr->iPrevId = iPrevId;
   121659 
   121660     if( bEof ){
   121661       pRoot->bEof = bEof;
   121662     }else{
   121663       /* Caution: pRoot may iterate through docids in ascending or descending
   121664       ** order. For this reason, even though it seems more defensive, the
   121665       ** do loop can not be written:
   121666       **
   121667       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
   121668       */
   121669       fts3EvalRestart(pCsr, pRoot, &rc);
   121670       do {
   121671         fts3EvalNextRow(pCsr, pRoot, &rc);
   121672         assert( pRoot->bEof==0 );
   121673       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
   121674       fts3EvalTestDeferredAndNear(pCsr, &rc);
   121675     }
   121676   }
   121677   return rc;
   121678 }
   121679 
   121680 /*
   121681 ** This function is used by the matchinfo() module to query a phrase
   121682 ** expression node for the following information:
   121683 **
   121684 **   1. The total number of occurrences of the phrase in each column of
   121685 **      the FTS table (considering all rows), and
   121686 **
   121687 **   2. For each column, the number of rows in the table for which the
   121688 **      column contains at least one instance of the phrase.
   121689 **
   121690 ** If no error occurs, SQLITE_OK is returned and the values for each column
   121691 ** written into the array aiOut as follows:
   121692 **
   121693 **   aiOut[iCol*3 + 1] = Number of occurrences
   121694 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
   121695 **
   121696 ** Caveats:
   121697 **
   121698 **   * If a phrase consists entirely of deferred tokens, then all output
   121699 **     values are set to the number of documents in the table. In other
   121700 **     words we assume that very common tokens occur exactly once in each
   121701 **     column of each row of the table.
   121702 **
   121703 **   * If a phrase contains some deferred tokens (and some non-deferred
   121704 **     tokens), count the potential occurrence identified by considering
   121705 **     the non-deferred tokens instead of actual phrase occurrences.
   121706 **
   121707 **   * If the phrase is part of a NEAR expression, then only phrase instances
   121708 **     that meet the NEAR constraint are included in the counts.
   121709 */
   121710 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
   121711   Fts3Cursor *pCsr,               /* FTS cursor handle */
   121712   Fts3Expr *pExpr,                /* Phrase expression */
   121713   u32 *aiOut                      /* Array to write results into (see above) */
   121714 ){
   121715   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121716   int rc = SQLITE_OK;
   121717   int iCol;
   121718 
   121719   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
   121720     assert( pCsr->nDoc>0 );
   121721     for(iCol=0; iCol<pTab->nColumn; iCol++){
   121722       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
   121723       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
   121724     }
   121725   }else{
   121726     rc = fts3EvalGatherStats(pCsr, pExpr);
   121727     if( rc==SQLITE_OK ){
   121728       assert( pExpr->aMI );
   121729       for(iCol=0; iCol<pTab->nColumn; iCol++){
   121730         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
   121731         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
   121732       }
   121733     }
   121734   }
   121735 
   121736   return rc;
   121737 }
   121738 
   121739 /*
   121740 ** The expression pExpr passed as the second argument to this function
   121741 ** must be of type FTSQUERY_PHRASE.
   121742 **
   121743 ** The returned value is either NULL or a pointer to a buffer containing
   121744 ** a position-list indicating the occurrences of the phrase in column iCol
   121745 ** of the current row.
   121746 **
   121747 ** More specifically, the returned buffer contains 1 varint for each
   121748 ** occurence of the phrase in the column, stored using the normal (delta+2)
   121749 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
   121750 ** if the requested column contains "a b X c d X X" and the position-list
   121751 ** for 'X' is requested, the buffer returned may contain:
   121752 **
   121753 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
   121754 **
   121755 ** This function works regardless of whether or not the phrase is deferred,
   121756 ** incremental, or neither.
   121757 */
   121758 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
   121759   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   121760   Fts3Expr *pExpr,                /* Phrase to return doclist for */
   121761   int iCol                        /* Column to return position list for */
   121762 ){
   121763   Fts3Phrase *pPhrase = pExpr->pPhrase;
   121764   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   121765   char *pIter = pPhrase->doclist.pList;
   121766   int iThis;
   121767 
   121768   assert( iCol>=0 && iCol<pTab->nColumn );
   121769   if( !pIter
   121770    || pExpr->bEof
   121771    || pExpr->iDocid!=pCsr->iPrevId
   121772    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
   121773   ){
   121774     return 0;
   121775   }
   121776 
   121777   assert( pPhrase->doclist.nList>0 );
   121778   if( *pIter==0x01 ){
   121779     pIter++;
   121780     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
   121781   }else{
   121782     iThis = 0;
   121783   }
   121784   while( iThis<iCol ){
   121785     fts3ColumnlistCopy(0, &pIter);
   121786     if( *pIter==0x00 ) return 0;
   121787     pIter++;
   121788     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
   121789   }
   121790 
   121791   return ((iCol==iThis)?pIter:0);
   121792 }
   121793 
   121794 /*
   121795 ** Free all components of the Fts3Phrase structure that were allocated by
   121796 ** the eval module. Specifically, this means to free:
   121797 **
   121798 **   * the contents of pPhrase->doclist, and
   121799 **   * any Fts3MultiSegReader objects held by phrase tokens.
   121800 */
   121801 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
   121802   if( pPhrase ){
   121803     int i;
   121804     sqlite3_free(pPhrase->doclist.aAll);
   121805     fts3EvalInvalidatePoslist(pPhrase);
   121806     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
   121807     for(i=0; i<pPhrase->nToken; i++){
   121808       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
   121809       pPhrase->aToken[i].pSegcsr = 0;
   121810     }
   121811   }
   121812 }
   121813 
   121814 /*
   121815 ** Return SQLITE_CORRUPT_VTAB.
   121816 */
   121817 #ifdef SQLITE_DEBUG
   121818 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
   121819   return SQLITE_CORRUPT_VTAB;
   121820 }
   121821 #endif
   121822 
   121823 #if !SQLITE_CORE
   121824 /*
   121825 ** Initialize API pointer table, if required.
   121826 */
   121827 SQLITE_API int sqlite3_extension_init(
   121828   sqlite3 *db,
   121829   char **pzErrMsg,
   121830   const sqlite3_api_routines *pApi
   121831 ){
   121832   SQLITE_EXTENSION_INIT2(pApi)
   121833   return sqlite3Fts3Init(db);
   121834 }
   121835 #endif
   121836 
   121837 #endif
   121838 
   121839 /************** End of fts3.c ************************************************/
   121840 /************** Begin file fts3_aux.c ****************************************/
   121841 /*
   121842 ** 2011 Jan 27
   121843 **
   121844 ** The author disclaims copyright to this source code.  In place of
   121845 ** a legal notice, here is a blessing:
   121846 **
   121847 **    May you do good and not evil.
   121848 **    May you find forgiveness for yourself and forgive others.
   121849 **    May you share freely, never taking more than you give.
   121850 **
   121851 ******************************************************************************
   121852 **
   121853 */
   121854 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   121855 
   121856 /* #include <string.h> */
   121857 /* #include <assert.h> */
   121858 
   121859 typedef struct Fts3auxTable Fts3auxTable;
   121860 typedef struct Fts3auxCursor Fts3auxCursor;
   121861 
   121862 struct Fts3auxTable {
   121863   sqlite3_vtab base;              /* Base class used by SQLite core */
   121864   Fts3Table *pFts3Tab;
   121865 };
   121866 
   121867 struct Fts3auxCursor {
   121868   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   121869   Fts3MultiSegReader csr;        /* Must be right after "base" */
   121870   Fts3SegFilter filter;
   121871   char *zStop;
   121872   int nStop;                      /* Byte-length of string zStop */
   121873   int isEof;                      /* True if cursor is at EOF */
   121874   sqlite3_int64 iRowid;           /* Current rowid */
   121875 
   121876   int iCol;                       /* Current value of 'col' column */
   121877   int nStat;                      /* Size of aStat[] array */
   121878   struct Fts3auxColstats {
   121879     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
   121880     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
   121881   } *aStat;
   121882 };
   121883 
   121884 /*
   121885 ** Schema of the terms table.
   121886 */
   121887 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
   121888 
   121889 /*
   121890 ** This function does all the work for both the xConnect and xCreate methods.
   121891 ** These tables have no persistent representation of their own, so xConnect
   121892 ** and xCreate are identical operations.
   121893 */
   121894 static int fts3auxConnectMethod(
   121895   sqlite3 *db,                    /* Database connection */
   121896   void *pUnused,                  /* Unused */
   121897   int argc,                       /* Number of elements in argv array */
   121898   const char * const *argv,       /* xCreate/xConnect argument array */
   121899   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   121900   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   121901 ){
   121902   char const *zDb;                /* Name of database (e.g. "main") */
   121903   char const *zFts3;              /* Name of fts3 table */
   121904   int nDb;                        /* Result of strlen(zDb) */
   121905   int nFts3;                      /* Result of strlen(zFts3) */
   121906   int nByte;                      /* Bytes of space to allocate here */
   121907   int rc;                         /* value returned by declare_vtab() */
   121908   Fts3auxTable *p;                /* Virtual table object to return */
   121909 
   121910   UNUSED_PARAMETER(pUnused);
   121911 
   121912   /* The user should specify a single argument - the name of an fts3 table. */
   121913   if( argc!=4 ){
   121914     *pzErr = sqlite3_mprintf(
   121915         "wrong number of arguments to fts4aux constructor"
   121916     );
   121917     return SQLITE_ERROR;
   121918   }
   121919 
   121920   zDb = argv[1];
   121921   nDb = (int)strlen(zDb);
   121922   zFts3 = argv[3];
   121923   nFts3 = (int)strlen(zFts3);
   121924 
   121925   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
   121926   if( rc!=SQLITE_OK ) return rc;
   121927 
   121928   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
   121929   p = (Fts3auxTable *)sqlite3_malloc(nByte);
   121930   if( !p ) return SQLITE_NOMEM;
   121931   memset(p, 0, nByte);
   121932 
   121933   p->pFts3Tab = (Fts3Table *)&p[1];
   121934   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
   121935   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
   121936   p->pFts3Tab->db = db;
   121937   p->pFts3Tab->nIndex = 1;
   121938 
   121939   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
   121940   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
   121941   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
   121942 
   121943   *ppVtab = (sqlite3_vtab *)p;
   121944   return SQLITE_OK;
   121945 }
   121946 
   121947 /*
   121948 ** This function does the work for both the xDisconnect and xDestroy methods.
   121949 ** These tables have no persistent representation of their own, so xDisconnect
   121950 ** and xDestroy are identical operations.
   121951 */
   121952 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
   121953   Fts3auxTable *p = (Fts3auxTable *)pVtab;
   121954   Fts3Table *pFts3 = p->pFts3Tab;
   121955   int i;
   121956 
   121957   /* Free any prepared statements held */
   121958   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
   121959     sqlite3_finalize(pFts3->aStmt[i]);
   121960   }
   121961   sqlite3_free(pFts3->zSegmentsTbl);
   121962   sqlite3_free(p);
   121963   return SQLITE_OK;
   121964 }
   121965 
   121966 #define FTS4AUX_EQ_CONSTRAINT 1
   121967 #define FTS4AUX_GE_CONSTRAINT 2
   121968 #define FTS4AUX_LE_CONSTRAINT 4
   121969 
   121970 /*
   121971 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
   121972 */
   121973 static int fts3auxBestIndexMethod(
   121974   sqlite3_vtab *pVTab,
   121975   sqlite3_index_info *pInfo
   121976 ){
   121977   int i;
   121978   int iEq = -1;
   121979   int iGe = -1;
   121980   int iLe = -1;
   121981 
   121982   UNUSED_PARAMETER(pVTab);
   121983 
   121984   /* This vtab delivers always results in "ORDER BY term ASC" order. */
   121985   if( pInfo->nOrderBy==1
   121986    && pInfo->aOrderBy[0].iColumn==0
   121987    && pInfo->aOrderBy[0].desc==0
   121988   ){
   121989     pInfo->orderByConsumed = 1;
   121990   }
   121991 
   121992   /* Search for equality and range constraints on the "term" column. */
   121993   for(i=0; i<pInfo->nConstraint; i++){
   121994     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
   121995       int op = pInfo->aConstraint[i].op;
   121996       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
   121997       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
   121998       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
   121999       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
   122000       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
   122001     }
   122002   }
   122003 
   122004   if( iEq>=0 ){
   122005     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
   122006     pInfo->aConstraintUsage[iEq].argvIndex = 1;
   122007     pInfo->estimatedCost = 5;
   122008   }else{
   122009     pInfo->idxNum = 0;
   122010     pInfo->estimatedCost = 20000;
   122011     if( iGe>=0 ){
   122012       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
   122013       pInfo->aConstraintUsage[iGe].argvIndex = 1;
   122014       pInfo->estimatedCost /= 2;
   122015     }
   122016     if( iLe>=0 ){
   122017       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
   122018       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
   122019       pInfo->estimatedCost /= 2;
   122020     }
   122021   }
   122022 
   122023   return SQLITE_OK;
   122024 }
   122025 
   122026 /*
   122027 ** xOpen - Open a cursor.
   122028 */
   122029 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   122030   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
   122031 
   122032   UNUSED_PARAMETER(pVTab);
   122033 
   122034   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
   122035   if( !pCsr ) return SQLITE_NOMEM;
   122036   memset(pCsr, 0, sizeof(Fts3auxCursor));
   122037 
   122038   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
   122039   return SQLITE_OK;
   122040 }
   122041 
   122042 /*
   122043 ** xClose - Close a cursor.
   122044 */
   122045 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
   122046   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122047   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122048 
   122049   sqlite3Fts3SegmentsClose(pFts3);
   122050   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   122051   sqlite3_free((void *)pCsr->filter.zTerm);
   122052   sqlite3_free(pCsr->zStop);
   122053   sqlite3_free(pCsr->aStat);
   122054   sqlite3_free(pCsr);
   122055   return SQLITE_OK;
   122056 }
   122057 
   122058 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   122059   if( nSize>pCsr->nStat ){
   122060     struct Fts3auxColstats *aNew;
   122061     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
   122062         sizeof(struct Fts3auxColstats) * nSize
   122063     );
   122064     if( aNew==0 ) return SQLITE_NOMEM;
   122065     memset(&aNew[pCsr->nStat], 0,
   122066         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
   122067     );
   122068     pCsr->aStat = aNew;
   122069     pCsr->nStat = nSize;
   122070   }
   122071   return SQLITE_OK;
   122072 }
   122073 
   122074 /*
   122075 ** xNext - Advance the cursor to the next row, if any.
   122076 */
   122077 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
   122078   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122079   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122080   int rc;
   122081 
   122082   /* Increment our pretend rowid value. */
   122083   pCsr->iRowid++;
   122084 
   122085   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
   122086     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
   122087   }
   122088 
   122089   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
   122090   if( rc==SQLITE_ROW ){
   122091     int i = 0;
   122092     int nDoclist = pCsr->csr.nDoclist;
   122093     char *aDoclist = pCsr->csr.aDoclist;
   122094     int iCol;
   122095 
   122096     int eState = 0;
   122097 
   122098     if( pCsr->zStop ){
   122099       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
   122100       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
   122101       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
   122102         pCsr->isEof = 1;
   122103         return SQLITE_OK;
   122104       }
   122105     }
   122106 
   122107     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
   122108     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
   122109     iCol = 0;
   122110 
   122111     while( i<nDoclist ){
   122112       sqlite3_int64 v = 0;
   122113 
   122114       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
   122115       switch( eState ){
   122116         /* State 0. In this state the integer just read was a docid. */
   122117         case 0:
   122118           pCsr->aStat[0].nDoc++;
   122119           eState = 1;
   122120           iCol = 0;
   122121           break;
   122122 
   122123         /* State 1. In this state we are expecting either a 1, indicating
   122124         ** that the following integer will be a column number, or the
   122125         ** start of a position list for column 0.
   122126         **
   122127         ** The only difference between state 1 and state 2 is that if the
   122128         ** integer encountered in state 1 is not 0 or 1, then we need to
   122129         ** increment the column 0 "nDoc" count for this term.
   122130         */
   122131         case 1:
   122132           assert( iCol==0 );
   122133           if( v>1 ){
   122134             pCsr->aStat[1].nDoc++;
   122135           }
   122136           eState = 2;
   122137           /* fall through */
   122138 
   122139         case 2:
   122140           if( v==0 ){       /* 0x00. Next integer will be a docid. */
   122141             eState = 0;
   122142           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
   122143             eState = 3;
   122144           }else{            /* 2 or greater. A position. */
   122145             pCsr->aStat[iCol+1].nOcc++;
   122146             pCsr->aStat[0].nOcc++;
   122147           }
   122148           break;
   122149 
   122150         /* State 3. The integer just read is a column number. */
   122151         default: assert( eState==3 );
   122152           iCol = (int)v;
   122153           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
   122154           pCsr->aStat[iCol+1].nDoc++;
   122155           eState = 2;
   122156           break;
   122157       }
   122158     }
   122159 
   122160     pCsr->iCol = 0;
   122161     rc = SQLITE_OK;
   122162   }else{
   122163     pCsr->isEof = 1;
   122164   }
   122165   return rc;
   122166 }
   122167 
   122168 /*
   122169 ** xFilter - Initialize a cursor to point at the start of its data.
   122170 */
   122171 static int fts3auxFilterMethod(
   122172   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   122173   int idxNum,                     /* Strategy index */
   122174   const char *idxStr,             /* Unused */
   122175   int nVal,                       /* Number of elements in apVal */
   122176   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   122177 ){
   122178   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122179   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
   122180   int rc;
   122181   int isScan;
   122182 
   122183   UNUSED_PARAMETER(nVal);
   122184   UNUSED_PARAMETER(idxStr);
   122185 
   122186   assert( idxStr==0 );
   122187   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
   122188        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
   122189        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
   122190   );
   122191   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
   122192 
   122193   /* In case this cursor is being reused, close and zero it. */
   122194   testcase(pCsr->filter.zTerm);
   122195   sqlite3Fts3SegReaderFinish(&pCsr->csr);
   122196   sqlite3_free((void *)pCsr->filter.zTerm);
   122197   sqlite3_free(pCsr->aStat);
   122198   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
   122199 
   122200   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
   122201   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
   122202 
   122203   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
   122204     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
   122205     if( zStr ){
   122206       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
   122207       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
   122208       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
   122209     }
   122210   }
   122211   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
   122212     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
   122213     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
   122214     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
   122215     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
   122216   }
   122217 
   122218   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
   122219       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
   122220   );
   122221   if( rc==SQLITE_OK ){
   122222     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
   122223   }
   122224 
   122225   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
   122226   return rc;
   122227 }
   122228 
   122229 /*
   122230 ** xEof - Return true if the cursor is at EOF, or false otherwise.
   122231 */
   122232 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
   122233   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122234   return pCsr->isEof;
   122235 }
   122236 
   122237 /*
   122238 ** xColumn - Return a column value.
   122239 */
   122240 static int fts3auxColumnMethod(
   122241   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   122242   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
   122243   int iCol                        /* Index of column to read value from */
   122244 ){
   122245   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
   122246 
   122247   assert( p->isEof==0 );
   122248   if( iCol==0 ){        /* Column "term" */
   122249     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
   122250   }else if( iCol==1 ){  /* Column "col" */
   122251     if( p->iCol ){
   122252       sqlite3_result_int(pContext, p->iCol-1);
   122253     }else{
   122254       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
   122255     }
   122256   }else if( iCol==2 ){  /* Column "documents" */
   122257     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
   122258   }else{                /* Column "occurrences" */
   122259     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
   122260   }
   122261 
   122262   return SQLITE_OK;
   122263 }
   122264 
   122265 /*
   122266 ** xRowid - Return the current rowid for the cursor.
   122267 */
   122268 static int fts3auxRowidMethod(
   122269   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   122270   sqlite_int64 *pRowid            /* OUT: Rowid value */
   122271 ){
   122272   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
   122273   *pRowid = pCsr->iRowid;
   122274   return SQLITE_OK;
   122275 }
   122276 
   122277 /*
   122278 ** Register the fts3aux module with database connection db. Return SQLITE_OK
   122279 ** if successful or an error code if sqlite3_create_module() fails.
   122280 */
   122281 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
   122282   static const sqlite3_module fts3aux_module = {
   122283      0,                           /* iVersion      */
   122284      fts3auxConnectMethod,        /* xCreate       */
   122285      fts3auxConnectMethod,        /* xConnect      */
   122286      fts3auxBestIndexMethod,      /* xBestIndex    */
   122287      fts3auxDisconnectMethod,     /* xDisconnect   */
   122288      fts3auxDisconnectMethod,     /* xDestroy      */
   122289      fts3auxOpenMethod,           /* xOpen         */
   122290      fts3auxCloseMethod,          /* xClose        */
   122291      fts3auxFilterMethod,         /* xFilter       */
   122292      fts3auxNextMethod,           /* xNext         */
   122293      fts3auxEofMethod,            /* xEof          */
   122294      fts3auxColumnMethod,         /* xColumn       */
   122295      fts3auxRowidMethod,          /* xRowid        */
   122296      0,                           /* xUpdate       */
   122297      0,                           /* xBegin        */
   122298      0,                           /* xSync         */
   122299      0,                           /* xCommit       */
   122300      0,                           /* xRollback     */
   122301      0,                           /* xFindFunction */
   122302      0,                           /* xRename       */
   122303      0,                           /* xSavepoint    */
   122304      0,                           /* xRelease      */
   122305      0                            /* xRollbackTo   */
   122306   };
   122307   int rc;                         /* Return code */
   122308 
   122309   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
   122310   return rc;
   122311 }
   122312 
   122313 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   122314 
   122315 /************** End of fts3_aux.c ********************************************/
   122316 /************** Begin file fts3_expr.c ***************************************/
   122317 /*
   122318 ** 2008 Nov 28
   122319 **
   122320 ** The author disclaims copyright to this source code.  In place of
   122321 ** a legal notice, here is a blessing:
   122322 **
   122323 **    May you do good and not evil.
   122324 **    May you find forgiveness for yourself and forgive others.
   122325 **    May you share freely, never taking more than you give.
   122326 **
   122327 ******************************************************************************
   122328 **
   122329 ** This module contains code that implements a parser for fts3 query strings
   122330 ** (the right-hand argument to the MATCH operator). Because the supported
   122331 ** syntax is relatively simple, the whole tokenizer/parser system is
   122332 ** hand-coded.
   122333 */
   122334 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   122335 
   122336 /*
   122337 ** By default, this module parses the legacy syntax that has been
   122338 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   122339 ** is defined, then it uses the new syntax. The differences between
   122340 ** the new and the old syntaxes are:
   122341 **
   122342 **  a) The new syntax supports parenthesis. The old does not.
   122343 **
   122344 **  b) The new syntax supports the AND and NOT operators. The old does not.
   122345 **
   122346 **  c) The old syntax supports the "-" token qualifier. This is not
   122347 **     supported by the new syntax (it is replaced by the NOT operator).
   122348 **
   122349 **  d) When using the old syntax, the OR operator has a greater precedence
   122350 **     than an implicit AND. When using the new, both implicity and explicit
   122351 **     AND operators have a higher precedence than OR.
   122352 **
   122353 ** If compiled with SQLITE_TEST defined, then this module exports the
   122354 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   122355 ** to zero causes the module to use the old syntax. If it is set to
   122356 ** non-zero the new syntax is activated. This is so both syntaxes can
   122357 ** be tested using a single build of testfixture.
   122358 **
   122359 ** The following describes the syntax supported by the fts3 MATCH
   122360 ** operator in a similar format to that used by the lemon parser
   122361 ** generator. This module does not use actually lemon, it uses a
   122362 ** custom parser.
   122363 **
   122364 **   query ::= andexpr (OR andexpr)*.
   122365 **
   122366 **   andexpr ::= notexpr (AND? notexpr)*.
   122367 **
   122368 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   122369 **   notexpr ::= LP query RP.
   122370 **
   122371 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   122372 **
   122373 **   distance_opt ::= .
   122374 **   distance_opt ::= / INTEGER.
   122375 **
   122376 **   phrase ::= TOKEN.
   122377 **   phrase ::= COLUMN:TOKEN.
   122378 **   phrase ::= "TOKEN TOKEN TOKEN...".
   122379 */
   122380 
   122381 #ifdef SQLITE_TEST
   122382 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   122383 #else
   122384 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   122385 #  define sqlite3_fts3_enable_parentheses 1
   122386 # else
   122387 #  define sqlite3_fts3_enable_parentheses 0
   122388 # endif
   122389 #endif
   122390 
   122391 /*
   122392 ** Default span for NEAR operators.
   122393 */
   122394 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   122395 
   122396 /* #include <string.h> */
   122397 /* #include <assert.h> */
   122398 
   122399 /*
   122400 ** isNot:
   122401 **   This variable is used by function getNextNode(). When getNextNode() is
   122402 **   called, it sets ParseContext.isNot to true if the 'next node' is a
   122403 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
   122404 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
   122405 **   zero.
   122406 */
   122407 typedef struct ParseContext ParseContext;
   122408 struct ParseContext {
   122409   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   122410   int iLangid;                        /* Language id used with tokenizer */
   122411   const char **azCol;                 /* Array of column names for fts3 table */
   122412   int bFts4;                          /* True to allow FTS4-only syntax */
   122413   int nCol;                           /* Number of entries in azCol[] */
   122414   int iDefaultCol;                    /* Default column to query */
   122415   int isNot;                          /* True if getNextNode() sees a unary - */
   122416   sqlite3_context *pCtx;              /* Write error message here */
   122417   int nNest;                          /* Number of nested brackets */
   122418 };
   122419 
   122420 /*
   122421 ** This function is equivalent to the standard isspace() function.
   122422 **
   122423 ** The standard isspace() can be awkward to use safely, because although it
   122424 ** is defined to accept an argument of type int, its behaviour when passed
   122425 ** an integer that falls outside of the range of the unsigned char type
   122426 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   122427 ** is defined to accept an argument of type char, and always returns 0 for
   122428 ** any values that fall outside of the range of the unsigned char type (i.e.
   122429 ** negative values).
   122430 */
   122431 static int fts3isspace(char c){
   122432   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   122433 }
   122434 
   122435 /*
   122436 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   122437 ** zero the memory before returning a pointer to it. If unsuccessful,
   122438 ** return NULL.
   122439 */
   122440 static void *fts3MallocZero(int nByte){
   122441   void *pRet = sqlite3_malloc(nByte);
   122442   if( pRet ) memset(pRet, 0, nByte);
   122443   return pRet;
   122444 }
   122445 
   122446 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
   122447   sqlite3_tokenizer *pTokenizer,
   122448   int iLangid,
   122449   const char *z,
   122450   int n,
   122451   sqlite3_tokenizer_cursor **ppCsr
   122452 ){
   122453   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122454   sqlite3_tokenizer_cursor *pCsr = 0;
   122455   int rc;
   122456 
   122457   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
   122458   assert( rc==SQLITE_OK || pCsr==0 );
   122459   if( rc==SQLITE_OK ){
   122460     pCsr->pTokenizer = pTokenizer;
   122461     if( pModule->iVersion>=1 ){
   122462       rc = pModule->xLanguageid(pCsr, iLangid);
   122463       if( rc!=SQLITE_OK ){
   122464         pModule->xClose(pCsr);
   122465         pCsr = 0;
   122466       }
   122467     }
   122468   }
   122469   *ppCsr = pCsr;
   122470   return rc;
   122471 }
   122472 
   122473 
   122474 /*
   122475 ** Extract the next token from buffer z (length n) using the tokenizer
   122476 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   122477 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   122478 ** single token and set *ppExpr to point to it. If the end of the buffer is
   122479 ** reached before a token is found, set *ppExpr to zero. It is the
   122480 ** responsibility of the caller to eventually deallocate the allocated
   122481 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   122482 **
   122483 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   122484 ** fails.
   122485 */
   122486 static int getNextToken(
   122487   ParseContext *pParse,                   /* fts3 query parse context */
   122488   int iCol,                               /* Value for Fts3Phrase.iColumn */
   122489   const char *z, int n,                   /* Input string */
   122490   Fts3Expr **ppExpr,                      /* OUT: expression */
   122491   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122492 ){
   122493   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   122494   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122495   int rc;
   122496   sqlite3_tokenizer_cursor *pCursor;
   122497   Fts3Expr *pRet = 0;
   122498   int nConsumed = 0;
   122499 
   122500   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
   122501   if( rc==SQLITE_OK ){
   122502     const char *zToken;
   122503     int nToken, iStart, iEnd, iPosition;
   122504     int nByte;                               /* total space to allocate */
   122505 
   122506     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   122507     if( rc==SQLITE_OK ){
   122508       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   122509       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   122510       if( !pRet ){
   122511         rc = SQLITE_NOMEM;
   122512       }else{
   122513         pRet->eType = FTSQUERY_PHRASE;
   122514         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   122515         pRet->pPhrase->nToken = 1;
   122516         pRet->pPhrase->iColumn = iCol;
   122517         pRet->pPhrase->aToken[0].n = nToken;
   122518         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   122519         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   122520 
   122521         if( iEnd<n && z[iEnd]=='*' ){
   122522           pRet->pPhrase->aToken[0].isPrefix = 1;
   122523           iEnd++;
   122524         }
   122525 
   122526         while( 1 ){
   122527           if( !sqlite3_fts3_enable_parentheses
   122528            && iStart>0 && z[iStart-1]=='-'
   122529           ){
   122530             pParse->isNot = 1;
   122531             iStart--;
   122532           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
   122533             pRet->pPhrase->aToken[0].bFirst = 1;
   122534             iStart--;
   122535           }else{
   122536             break;
   122537           }
   122538         }
   122539 
   122540       }
   122541       nConsumed = iEnd;
   122542     }
   122543 
   122544     pModule->xClose(pCursor);
   122545   }
   122546 
   122547   *pnConsumed = nConsumed;
   122548   *ppExpr = pRet;
   122549   return rc;
   122550 }
   122551 
   122552 
   122553 /*
   122554 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   122555 ** then free the old allocation.
   122556 */
   122557 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   122558   void *pRet = sqlite3_realloc(pOrig, nNew);
   122559   if( !pRet ){
   122560     sqlite3_free(pOrig);
   122561   }
   122562   return pRet;
   122563 }
   122564 
   122565 /*
   122566 ** Buffer zInput, length nInput, contains the contents of a quoted string
   122567 ** that appeared as part of an fts3 query expression. Neither quote character
   122568 ** is included in the buffer. This function attempts to tokenize the entire
   122569 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   122570 ** containing the results.
   122571 **
   122572 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   122573 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   122574 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   122575 ** to 0.
   122576 */
   122577 static int getNextString(
   122578   ParseContext *pParse,                   /* fts3 query parse context */
   122579   const char *zInput, int nInput,         /* Input string */
   122580   Fts3Expr **ppExpr                       /* OUT: expression */
   122581 ){
   122582   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   122583   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   122584   int rc;
   122585   Fts3Expr *p = 0;
   122586   sqlite3_tokenizer_cursor *pCursor = 0;
   122587   char *zTemp = 0;
   122588   int nTemp = 0;
   122589 
   122590   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   122591   int nToken = 0;
   122592 
   122593   /* The final Fts3Expr data structure, including the Fts3Phrase,
   122594   ** Fts3PhraseToken structures token buffers are all stored as a single
   122595   ** allocation so that the expression can be freed with a single call to
   122596   ** sqlite3_free(). Setting this up requires a two pass approach.
   122597   **
   122598   ** The first pass, in the block below, uses a tokenizer cursor to iterate
   122599   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
   122600   ** to assemble data in two dynamic buffers:
   122601   **
   122602   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
   122603   **             structure, followed by the array of Fts3PhraseToken
   122604   **             structures. This pass only populates the Fts3PhraseToken array.
   122605   **
   122606   **   Buffer zTemp: Contains copies of all tokens.
   122607   **
   122608   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
   122609   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
   122610   ** structures.
   122611   */
   122612   rc = sqlite3Fts3OpenTokenizer(
   122613       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
   122614   if( rc==SQLITE_OK ){
   122615     int ii;
   122616     for(ii=0; rc==SQLITE_OK; ii++){
   122617       const char *zByte;
   122618       int nByte, iBegin, iEnd, iPos;
   122619       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
   122620       if( rc==SQLITE_OK ){
   122621         Fts3PhraseToken *pToken;
   122622 
   122623         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
   122624         if( !p ) goto no_mem;
   122625 
   122626         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
   122627         if( !zTemp ) goto no_mem;
   122628 
   122629         assert( nToken==ii );
   122630         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
   122631         memset(pToken, 0, sizeof(Fts3PhraseToken));
   122632 
   122633         memcpy(&zTemp[nTemp], zByte, nByte);
   122634         nTemp += nByte;
   122635 
   122636         pToken->n = nByte;
   122637         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
   122638         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
   122639         nToken = ii+1;
   122640       }
   122641     }
   122642 
   122643     pModule->xClose(pCursor);
   122644     pCursor = 0;
   122645   }
   122646 
   122647   if( rc==SQLITE_DONE ){
   122648     int jj;
   122649     char *zBuf = 0;
   122650 
   122651     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
   122652     if( !p ) goto no_mem;
   122653     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
   122654     p->eType = FTSQUERY_PHRASE;
   122655     p->pPhrase = (Fts3Phrase *)&p[1];
   122656     p->pPhrase->iColumn = pParse->iDefaultCol;
   122657     p->pPhrase->nToken = nToken;
   122658 
   122659     zBuf = (char *)&p->pPhrase->aToken[nToken];
   122660     if( zTemp ){
   122661       memcpy(zBuf, zTemp, nTemp);
   122662       sqlite3_free(zTemp);
   122663     }else{
   122664       assert( nTemp==0 );
   122665     }
   122666 
   122667     for(jj=0; jj<p->pPhrase->nToken; jj++){
   122668       p->pPhrase->aToken[jj].z = zBuf;
   122669       zBuf += p->pPhrase->aToken[jj].n;
   122670     }
   122671     rc = SQLITE_OK;
   122672   }
   122673 
   122674   *ppExpr = p;
   122675   return rc;
   122676 no_mem:
   122677 
   122678   if( pCursor ){
   122679     pModule->xClose(pCursor);
   122680   }
   122681   sqlite3_free(zTemp);
   122682   sqlite3_free(p);
   122683   *ppExpr = 0;
   122684   return SQLITE_NOMEM;
   122685 }
   122686 
   122687 /*
   122688 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   122689 ** call fts3ExprParse(). So this forward declaration is required.
   122690 */
   122691 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   122692 
   122693 /*
   122694 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   122695 ** structure, or set to 0 if the end of the input buffer is reached.
   122696 **
   122697 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   122698 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   122699 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   122700 */
   122701 static int getNextNode(
   122702   ParseContext *pParse,                   /* fts3 query parse context */
   122703   const char *z, int n,                   /* Input string */
   122704   Fts3Expr **ppExpr,                      /* OUT: expression */
   122705   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122706 ){
   122707   static const struct Fts3Keyword {
   122708     char *z;                              /* Keyword text */
   122709     unsigned char n;                      /* Length of the keyword */
   122710     unsigned char parenOnly;              /* Only valid in paren mode */
   122711     unsigned char eType;                  /* Keyword code */
   122712   } aKeyword[] = {
   122713     { "OR" ,  2, 0, FTSQUERY_OR   },
   122714     { "AND",  3, 1, FTSQUERY_AND  },
   122715     { "NOT",  3, 1, FTSQUERY_NOT  },
   122716     { "NEAR", 4, 0, FTSQUERY_NEAR }
   122717   };
   122718   int ii;
   122719   int iCol;
   122720   int iColLen;
   122721   int rc;
   122722   Fts3Expr *pRet = 0;
   122723 
   122724   const char *zInput = z;
   122725   int nInput = n;
   122726 
   122727   pParse->isNot = 0;
   122728 
   122729   /* Skip over any whitespace before checking for a keyword, an open or
   122730   ** close bracket, or a quoted string.
   122731   */
   122732   while( nInput>0 && fts3isspace(*zInput) ){
   122733     nInput--;
   122734     zInput++;
   122735   }
   122736   if( nInput==0 ){
   122737     return SQLITE_DONE;
   122738   }
   122739 
   122740   /* See if we are dealing with a keyword. */
   122741   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   122742     const struct Fts3Keyword *pKey = &aKeyword[ii];
   122743 
   122744     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   122745       continue;
   122746     }
   122747 
   122748     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   122749       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   122750       int nKey = pKey->n;
   122751       char cNext;
   122752 
   122753       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   122754       if( pKey->eType==FTSQUERY_NEAR ){
   122755         assert( nKey==4 );
   122756         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   122757           nNear = 0;
   122758           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   122759             nNear = nNear * 10 + (zInput[nKey] - '0');
   122760           }
   122761         }
   122762       }
   122763 
   122764       /* At this point this is probably a keyword. But for that to be true,
   122765       ** the next byte must contain either whitespace, an open or close
   122766       ** parenthesis, a quote character, or EOF.
   122767       */
   122768       cNext = zInput[nKey];
   122769       if( fts3isspace(cNext)
   122770        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   122771       ){
   122772         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   122773         if( !pRet ){
   122774           return SQLITE_NOMEM;
   122775         }
   122776         pRet->eType = pKey->eType;
   122777         pRet->nNear = nNear;
   122778         *ppExpr = pRet;
   122779         *pnConsumed = (int)((zInput - z) + nKey);
   122780         return SQLITE_OK;
   122781       }
   122782 
   122783       /* Turns out that wasn't a keyword after all. This happens if the
   122784       ** user has supplied a token such as "ORacle". Continue.
   122785       */
   122786     }
   122787   }
   122788 
   122789   /* Check for an open bracket. */
   122790   if( sqlite3_fts3_enable_parentheses ){
   122791     if( *zInput=='(' ){
   122792       int nConsumed;
   122793       pParse->nNest++;
   122794       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
   122795       if( rc==SQLITE_OK && !*ppExpr ){
   122796         rc = SQLITE_DONE;
   122797       }
   122798       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
   122799       return rc;
   122800     }
   122801 
   122802     /* Check for a close bracket. */
   122803     if( *zInput==')' ){
   122804       pParse->nNest--;
   122805       *pnConsumed = (int)((zInput - z) + 1);
   122806       return SQLITE_DONE;
   122807     }
   122808   }
   122809 
   122810   /* See if we are dealing with a quoted phrase. If this is the case, then
   122811   ** search for the closing quote and pass the whole string to getNextString()
   122812   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   122813   ** a quote character embedded in a string.
   122814   */
   122815   if( *zInput=='"' ){
   122816     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   122817     *pnConsumed = (int)((zInput - z) + ii + 1);
   122818     if( ii==nInput ){
   122819       return SQLITE_ERROR;
   122820     }
   122821     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   122822   }
   122823 
   122824 
   122825   /* If control flows to this point, this must be a regular token, or
   122826   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   122827   ** interface. Before doing so, figure out if there is an explicit
   122828   ** column specifier for the token.
   122829   **
   122830   ** TODO: Strangely, it is not possible to associate a column specifier
   122831   ** with a quoted phrase, only with a single token. Not sure if this was
   122832   ** an implementation artifact or an intentional decision when fts3 was
   122833   ** first implemented. Whichever it was, this module duplicates the
   122834   ** limitation.
   122835   */
   122836   iCol = pParse->iDefaultCol;
   122837   iColLen = 0;
   122838   for(ii=0; ii<pParse->nCol; ii++){
   122839     const char *zStr = pParse->azCol[ii];
   122840     int nStr = (int)strlen(zStr);
   122841     if( nInput>nStr && zInput[nStr]==':'
   122842      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   122843     ){
   122844       iCol = ii;
   122845       iColLen = (int)((zInput - z) + nStr + 1);
   122846       break;
   122847     }
   122848   }
   122849   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   122850   *pnConsumed += iColLen;
   122851   return rc;
   122852 }
   122853 
   122854 /*
   122855 ** The argument is an Fts3Expr structure for a binary operator (any type
   122856 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   122857 ** precedence of the operator. Lower values have a higher precedence (i.e.
   122858 ** group more tightly). For example, in the C language, the == operator
   122859 ** groups more tightly than ||, and would therefore have a higher precedence.
   122860 **
   122861 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   122862 ** is defined), the order of the operators in precedence from highest to
   122863 ** lowest is:
   122864 **
   122865 **   NEAR
   122866 **   NOT
   122867 **   AND (including implicit ANDs)
   122868 **   OR
   122869 **
   122870 ** Note that when using the old query syntax, the OR operator has a higher
   122871 ** precedence than the AND operator.
   122872 */
   122873 static int opPrecedence(Fts3Expr *p){
   122874   assert( p->eType!=FTSQUERY_PHRASE );
   122875   if( sqlite3_fts3_enable_parentheses ){
   122876     return p->eType;
   122877   }else if( p->eType==FTSQUERY_NEAR ){
   122878     return 1;
   122879   }else if( p->eType==FTSQUERY_OR ){
   122880     return 2;
   122881   }
   122882   assert( p->eType==FTSQUERY_AND );
   122883   return 3;
   122884 }
   122885 
   122886 /*
   122887 ** Argument ppHead contains a pointer to the current head of a query
   122888 ** expression tree being parsed. pPrev is the expression node most recently
   122889 ** inserted into the tree. This function adds pNew, which is always a binary
   122890 ** operator node, into the expression tree based on the relative precedence
   122891 ** of pNew and the existing nodes of the tree. This may result in the head
   122892 ** of the tree changing, in which case *ppHead is set to the new root node.
   122893 */
   122894 static void insertBinaryOperator(
   122895   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   122896   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   122897   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   122898 ){
   122899   Fts3Expr *pSplit = pPrev;
   122900   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   122901     pSplit = pSplit->pParent;
   122902   }
   122903 
   122904   if( pSplit->pParent ){
   122905     assert( pSplit->pParent->pRight==pSplit );
   122906     pSplit->pParent->pRight = pNew;
   122907     pNew->pParent = pSplit->pParent;
   122908   }else{
   122909     *ppHead = pNew;
   122910   }
   122911   pNew->pLeft = pSplit;
   122912   pSplit->pParent = pNew;
   122913 }
   122914 
   122915 /*
   122916 ** Parse the fts3 query expression found in buffer z, length n. This function
   122917 ** returns either when the end of the buffer is reached or an unmatched
   122918 ** closing bracket - ')' - is encountered.
   122919 **
   122920 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   122921 ** parsed form of the expression and *pnConsumed is set to the number of
   122922 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   122923 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   122924 */
   122925 static int fts3ExprParse(
   122926   ParseContext *pParse,                   /* fts3 query parse context */
   122927   const char *z, int n,                   /* Text of MATCH query */
   122928   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   122929   int *pnConsumed                         /* OUT: Number of bytes consumed */
   122930 ){
   122931   Fts3Expr *pRet = 0;
   122932   Fts3Expr *pPrev = 0;
   122933   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   122934   int nIn = n;
   122935   const char *zIn = z;
   122936   int rc = SQLITE_OK;
   122937   int isRequirePhrase = 1;
   122938 
   122939   while( rc==SQLITE_OK ){
   122940     Fts3Expr *p = 0;
   122941     int nByte = 0;
   122942     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   122943     if( rc==SQLITE_OK ){
   122944       int isPhrase;
   122945 
   122946       if( !sqlite3_fts3_enable_parentheses
   122947        && p->eType==FTSQUERY_PHRASE && pParse->isNot
   122948       ){
   122949         /* Create an implicit NOT operator. */
   122950         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   122951         if( !pNot ){
   122952           sqlite3Fts3ExprFree(p);
   122953           rc = SQLITE_NOMEM;
   122954           goto exprparse_out;
   122955         }
   122956         pNot->eType = FTSQUERY_NOT;
   122957         pNot->pRight = p;
   122958         if( pNotBranch ){
   122959           pNot->pLeft = pNotBranch;
   122960         }
   122961         pNotBranch = pNot;
   122962         p = pPrev;
   122963       }else{
   122964         int eType = p->eType;
   122965         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   122966 
   122967         /* The isRequirePhrase variable is set to true if a phrase or
   122968         ** an expression contained in parenthesis is required. If a
   122969         ** binary operator (AND, OR, NOT or NEAR) is encounted when
   122970         ** isRequirePhrase is set, this is a syntax error.
   122971         */
   122972         if( !isPhrase && isRequirePhrase ){
   122973           sqlite3Fts3ExprFree(p);
   122974           rc = SQLITE_ERROR;
   122975           goto exprparse_out;
   122976         }
   122977 
   122978         if( isPhrase && !isRequirePhrase ){
   122979           /* Insert an implicit AND operator. */
   122980           Fts3Expr *pAnd;
   122981           assert( pRet && pPrev );
   122982           pAnd = fts3MallocZero(sizeof(Fts3Expr));
   122983           if( !pAnd ){
   122984             sqlite3Fts3ExprFree(p);
   122985             rc = SQLITE_NOMEM;
   122986             goto exprparse_out;
   122987           }
   122988           pAnd->eType = FTSQUERY_AND;
   122989           insertBinaryOperator(&pRet, pPrev, pAnd);
   122990           pPrev = pAnd;
   122991         }
   122992 
   122993         /* This test catches attempts to make either operand of a NEAR
   122994         ** operator something other than a phrase. For example, either of
   122995         ** the following:
   122996         **
   122997         **    (bracketed expression) NEAR phrase
   122998         **    phrase NEAR (bracketed expression)
   122999         **
   123000         ** Return an error in either case.
   123001         */
   123002         if( pPrev && (
   123003             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   123004          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   123005         )){
   123006           sqlite3Fts3ExprFree(p);
   123007           rc = SQLITE_ERROR;
   123008           goto exprparse_out;
   123009         }
   123010 
   123011         if( isPhrase ){
   123012           if( pRet ){
   123013             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   123014             pPrev->pRight = p;
   123015             p->pParent = pPrev;
   123016           }else{
   123017             pRet = p;
   123018           }
   123019         }else{
   123020           insertBinaryOperator(&pRet, pPrev, p);
   123021         }
   123022         isRequirePhrase = !isPhrase;
   123023       }
   123024       assert( nByte>0 );
   123025     }
   123026     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   123027     nIn -= nByte;
   123028     zIn += nByte;
   123029     pPrev = p;
   123030   }
   123031 
   123032   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   123033     rc = SQLITE_ERROR;
   123034   }
   123035 
   123036   if( rc==SQLITE_DONE ){
   123037     rc = SQLITE_OK;
   123038     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   123039       if( !pRet ){
   123040         rc = SQLITE_ERROR;
   123041       }else{
   123042         Fts3Expr *pIter = pNotBranch;
   123043         while( pIter->pLeft ){
   123044           pIter = pIter->pLeft;
   123045         }
   123046         pIter->pLeft = pRet;
   123047         pRet = pNotBranch;
   123048       }
   123049     }
   123050   }
   123051   *pnConsumed = n - nIn;
   123052 
   123053 exprparse_out:
   123054   if( rc!=SQLITE_OK ){
   123055     sqlite3Fts3ExprFree(pRet);
   123056     sqlite3Fts3ExprFree(pNotBranch);
   123057     pRet = 0;
   123058   }
   123059   *ppExpr = pRet;
   123060   return rc;
   123061 }
   123062 
   123063 /*
   123064 ** Parameters z and n contain a pointer to and length of a buffer containing
   123065 ** an fts3 query expression, respectively. This function attempts to parse the
   123066 ** query expression and create a tree of Fts3Expr structures representing the
   123067 ** parsed expression. If successful, *ppExpr is set to point to the head
   123068 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   123069 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   123070 ** error) is returned and *ppExpr is set to 0.
   123071 **
   123072 ** If parameter n is a negative number, then z is assumed to point to a
   123073 ** nul-terminated string and the length is determined using strlen().
   123074 **
   123075 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   123076 ** use to normalize query tokens while parsing the expression. The azCol[]
   123077 ** array, which is assumed to contain nCol entries, should contain the names
   123078 ** of each column in the target fts3 table, in order from left to right.
   123079 ** Column names must be nul-terminated strings.
   123080 **
   123081 ** The iDefaultCol parameter should be passed the index of the table column
   123082 ** that appears on the left-hand-side of the MATCH operator (the default
   123083 ** column to match against for tokens for which a column name is not explicitly
   123084 ** specified as part of the query string), or -1 if tokens may by default
   123085 ** match any table column.
   123086 */
   123087 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   123088   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   123089   int iLangid,                        /* Language id for tokenizer */
   123090   char **azCol,                       /* Array of column names for fts3 table */
   123091   int bFts4,                          /* True to allow FTS4-only syntax */
   123092   int nCol,                           /* Number of entries in azCol[] */
   123093   int iDefaultCol,                    /* Default column to query */
   123094   const char *z, int n,               /* Text of MATCH query */
   123095   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   123096 ){
   123097   int nParsed;
   123098   int rc;
   123099   ParseContext sParse;
   123100 
   123101   memset(&sParse, 0, sizeof(ParseContext));
   123102   sParse.pTokenizer = pTokenizer;
   123103   sParse.iLangid = iLangid;
   123104   sParse.azCol = (const char **)azCol;
   123105   sParse.nCol = nCol;
   123106   sParse.iDefaultCol = iDefaultCol;
   123107   sParse.bFts4 = bFts4;
   123108   if( z==0 ){
   123109     *ppExpr = 0;
   123110     return SQLITE_OK;
   123111   }
   123112   if( n<0 ){
   123113     n = (int)strlen(z);
   123114   }
   123115   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   123116 
   123117   /* Check for mismatched parenthesis */
   123118   if( rc==SQLITE_OK && sParse.nNest ){
   123119     rc = SQLITE_ERROR;
   123120     sqlite3Fts3ExprFree(*ppExpr);
   123121     *ppExpr = 0;
   123122   }
   123123 
   123124   return rc;
   123125 }
   123126 
   123127 /*
   123128 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   123129 */
   123130 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
   123131   if( p ){
   123132     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
   123133     sqlite3Fts3ExprFree(p->pLeft);
   123134     sqlite3Fts3ExprFree(p->pRight);
   123135     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
   123136     sqlite3_free(p->aMI);
   123137     sqlite3_free(p);
   123138   }
   123139 }
   123140 
   123141 /****************************************************************************
   123142 *****************************************************************************
   123143 ** Everything after this point is just test code.
   123144 */
   123145 
   123146 #ifdef SQLITE_TEST
   123147 
   123148 /* #include <stdio.h> */
   123149 
   123150 /*
   123151 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   123152 */
   123153 static int queryTestTokenizer(
   123154   sqlite3 *db,
   123155   const char *zName,
   123156   const sqlite3_tokenizer_module **pp
   123157 ){
   123158   int rc;
   123159   sqlite3_stmt *pStmt;
   123160   const char zSql[] = "SELECT fts3_tokenizer(?)";
   123161 
   123162   *pp = 0;
   123163   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   123164   if( rc!=SQLITE_OK ){
   123165     return rc;
   123166   }
   123167 
   123168   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   123169   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   123170     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   123171       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   123172     }
   123173   }
   123174 
   123175   return sqlite3_finalize(pStmt);
   123176 }
   123177 
   123178 /*
   123179 ** Return a pointer to a buffer containing a text representation of the
   123180 ** expression passed as the first argument. The buffer is obtained from
   123181 ** sqlite3_malloc(). It is the responsibility of the caller to use
   123182 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   123183 ** NULL is returned.
   123184 **
   123185 ** If the second argument is not NULL, then its contents are prepended to
   123186 ** the returned expression text and then freed using sqlite3_free().
   123187 */
   123188 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   123189   switch( pExpr->eType ){
   123190     case FTSQUERY_PHRASE: {
   123191       Fts3Phrase *pPhrase = pExpr->pPhrase;
   123192       int i;
   123193       zBuf = sqlite3_mprintf(
   123194           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
   123195       for(i=0; zBuf && i<pPhrase->nToken; i++){
   123196         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   123197             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   123198             (pPhrase->aToken[i].isPrefix?"+":"")
   123199         );
   123200       }
   123201       return zBuf;
   123202     }
   123203 
   123204     case FTSQUERY_NEAR:
   123205       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   123206       break;
   123207     case FTSQUERY_NOT:
   123208       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   123209       break;
   123210     case FTSQUERY_AND:
   123211       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   123212       break;
   123213     case FTSQUERY_OR:
   123214       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   123215       break;
   123216   }
   123217 
   123218   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   123219   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   123220   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   123221 
   123222   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   123223   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   123224 
   123225   return zBuf;
   123226 }
   123227 
   123228 /*
   123229 ** This is the implementation of a scalar SQL function used to test the
   123230 ** expression parser. It should be called as follows:
   123231 **
   123232 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   123233 **
   123234 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   123235 ** to parse the query expression (see README.tokenizers). The second argument
   123236 ** is the query expression to parse. Each subsequent argument is the name
   123237 ** of a column of the fts3 table that the query expression may refer to.
   123238 ** For example:
   123239 **
   123240 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   123241 */
   123242 static void fts3ExprTest(
   123243   sqlite3_context *context,
   123244   int argc,
   123245   sqlite3_value **argv
   123246 ){
   123247   sqlite3_tokenizer_module const *pModule = 0;
   123248   sqlite3_tokenizer *pTokenizer = 0;
   123249   int rc;
   123250   char **azCol = 0;
   123251   const char *zExpr;
   123252   int nExpr;
   123253   int nCol;
   123254   int ii;
   123255   Fts3Expr *pExpr;
   123256   char *zBuf = 0;
   123257   sqlite3 *db = sqlite3_context_db_handle(context);
   123258 
   123259   if( argc<3 ){
   123260     sqlite3_result_error(context,
   123261         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   123262     );
   123263     return;
   123264   }
   123265 
   123266   rc = queryTestTokenizer(db,
   123267                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   123268   if( rc==SQLITE_NOMEM ){
   123269     sqlite3_result_error_nomem(context);
   123270     goto exprtest_out;
   123271   }else if( !pModule ){
   123272     sqlite3_result_error(context, "No such tokenizer module", -1);
   123273     goto exprtest_out;
   123274   }
   123275 
   123276   rc = pModule->xCreate(0, 0, &pTokenizer);
   123277   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   123278   if( rc==SQLITE_NOMEM ){
   123279     sqlite3_result_error_nomem(context);
   123280     goto exprtest_out;
   123281   }
   123282   pTokenizer->pModule = pModule;
   123283 
   123284   zExpr = (const char *)sqlite3_value_text(argv[1]);
   123285   nExpr = sqlite3_value_bytes(argv[1]);
   123286   nCol = argc-2;
   123287   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   123288   if( !azCol ){
   123289     sqlite3_result_error_nomem(context);
   123290     goto exprtest_out;
   123291   }
   123292   for(ii=0; ii<nCol; ii++){
   123293     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   123294   }
   123295 
   123296   rc = sqlite3Fts3ExprParse(
   123297       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
   123298   );
   123299   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   123300     sqlite3_result_error(context, "Error parsing expression", -1);
   123301   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   123302     sqlite3_result_error_nomem(context);
   123303   }else{
   123304     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   123305     sqlite3_free(zBuf);
   123306   }
   123307 
   123308   sqlite3Fts3ExprFree(pExpr);
   123309 
   123310 exprtest_out:
   123311   if( pModule && pTokenizer ){
   123312     rc = pModule->xDestroy(pTokenizer);
   123313   }
   123314   sqlite3_free(azCol);
   123315 }
   123316 
   123317 /*
   123318 ** Register the query expression parser test function fts3_exprtest()
   123319 ** with database connection db.
   123320 */
   123321 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   123322   return sqlite3_create_function(
   123323       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   123324   );
   123325 }
   123326 
   123327 #endif
   123328 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   123329 
   123330 /************** End of fts3_expr.c *******************************************/
   123331 /************** Begin file fts3_hash.c ***************************************/
   123332 /*
   123333 ** 2001 September 22
   123334 **
   123335 ** The author disclaims copyright to this source code.  In place of
   123336 ** a legal notice, here is a blessing:
   123337 **
   123338 **    May you do good and not evil.
   123339 **    May you find forgiveness for yourself and forgive others.
   123340 **    May you share freely, never taking more than you give.
   123341 **
   123342 *************************************************************************
   123343 ** This is the implementation of generic hash-tables used in SQLite.
   123344 ** We've modified it slightly to serve as a standalone hash table
   123345 ** implementation for the full-text indexing module.
   123346 */
   123347 
   123348 /*
   123349 ** The code in this file is only compiled if:
   123350 **
   123351 **     * The FTS3 module is being built as an extension
   123352 **       (in which case SQLITE_CORE is not defined), or
   123353 **
   123354 **     * The FTS3 module is being built into the core of
   123355 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   123356 */
   123357 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   123358 
   123359 /* #include <assert.h> */
   123360 /* #include <stdlib.h> */
   123361 /* #include <string.h> */
   123362 
   123363 
   123364 /*
   123365 ** Malloc and Free functions
   123366 */
   123367 static void *fts3HashMalloc(int n){
   123368   void *p = sqlite3_malloc(n);
   123369   if( p ){
   123370     memset(p, 0, n);
   123371   }
   123372   return p;
   123373 }
   123374 static void fts3HashFree(void *p){
   123375   sqlite3_free(p);
   123376 }
   123377 
   123378 /* Turn bulk memory into a hash table object by initializing the
   123379 ** fields of the Hash structure.
   123380 **
   123381 ** "pNew" is a pointer to the hash table that is to be initialized.
   123382 ** keyClass is one of the constants
   123383 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   123384 ** determines what kind of key the hash table will use.  "copyKey" is
   123385 ** true if the hash table should make its own private copy of keys and
   123386 ** false if it should just use the supplied pointer.
   123387 */
   123388 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   123389   assert( pNew!=0 );
   123390   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   123391   pNew->keyClass = keyClass;
   123392   pNew->copyKey = copyKey;
   123393   pNew->first = 0;
   123394   pNew->count = 0;
   123395   pNew->htsize = 0;
   123396   pNew->ht = 0;
   123397 }
   123398 
   123399 /* Remove all entries from a hash table.  Reclaim all memory.
   123400 ** Call this routine to delete a hash table or to reset a hash table
   123401 ** to the empty state.
   123402 */
   123403 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   123404   Fts3HashElem *elem;         /* For looping over all elements of the table */
   123405 
   123406   assert( pH!=0 );
   123407   elem = pH->first;
   123408   pH->first = 0;
   123409   fts3HashFree(pH->ht);
   123410   pH->ht = 0;
   123411   pH->htsize = 0;
   123412   while( elem ){
   123413     Fts3HashElem *next_elem = elem->next;
   123414     if( pH->copyKey && elem->pKey ){
   123415       fts3HashFree(elem->pKey);
   123416     }
   123417     fts3HashFree(elem);
   123418     elem = next_elem;
   123419   }
   123420   pH->count = 0;
   123421 }
   123422 
   123423 /*
   123424 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   123425 */
   123426 static int fts3StrHash(const void *pKey, int nKey){
   123427   const char *z = (const char *)pKey;
   123428   int h = 0;
   123429   if( nKey<=0 ) nKey = (int) strlen(z);
   123430   while( nKey > 0  ){
   123431     h = (h<<3) ^ h ^ *z++;
   123432     nKey--;
   123433   }
   123434   return h & 0x7fffffff;
   123435 }
   123436 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   123437   if( n1!=n2 ) return 1;
   123438   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   123439 }
   123440 
   123441 /*
   123442 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   123443 */
   123444 static int fts3BinHash(const void *pKey, int nKey){
   123445   int h = 0;
   123446   const char *z = (const char *)pKey;
   123447   while( nKey-- > 0 ){
   123448     h = (h<<3) ^ h ^ *(z++);
   123449   }
   123450   return h & 0x7fffffff;
   123451 }
   123452 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   123453   if( n1!=n2 ) return 1;
   123454   return memcmp(pKey1,pKey2,n1);
   123455 }
   123456 
   123457 /*
   123458 ** Return a pointer to the appropriate hash function given the key class.
   123459 **
   123460 ** The C syntax in this function definition may be unfamilar to some
   123461 ** programmers, so we provide the following additional explanation:
   123462 **
   123463 ** The name of the function is "ftsHashFunction".  The function takes a
   123464 ** single parameter "keyClass".  The return value of ftsHashFunction()
   123465 ** is a pointer to another function.  Specifically, the return value
   123466 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   123467 ** with types "const void*" and "int" and returns an "int".
   123468 */
   123469 static int (*ftsHashFunction(int keyClass))(const void*,int){
   123470   if( keyClass==FTS3_HASH_STRING ){
   123471     return &fts3StrHash;
   123472   }else{
   123473     assert( keyClass==FTS3_HASH_BINARY );
   123474     return &fts3BinHash;
   123475   }
   123476 }
   123477 
   123478 /*
   123479 ** Return a pointer to the appropriate hash function given the key class.
   123480 **
   123481 ** For help in interpreted the obscure C code in the function definition,
   123482 ** see the header comment on the previous function.
   123483 */
   123484 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   123485   if( keyClass==FTS3_HASH_STRING ){
   123486     return &fts3StrCompare;
   123487   }else{
   123488     assert( keyClass==FTS3_HASH_BINARY );
   123489     return &fts3BinCompare;
   123490   }
   123491 }
   123492 
   123493 /* Link an element into the hash table
   123494 */
   123495 static void fts3HashInsertElement(
   123496   Fts3Hash *pH,            /* The complete hash table */
   123497   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   123498   Fts3HashElem *pNew       /* The element to be inserted */
   123499 ){
   123500   Fts3HashElem *pHead;     /* First element already in pEntry */
   123501   pHead = pEntry->chain;
   123502   if( pHead ){
   123503     pNew->next = pHead;
   123504     pNew->prev = pHead->prev;
   123505     if( pHead->prev ){ pHead->prev->next = pNew; }
   123506     else             { pH->first = pNew; }
   123507     pHead->prev = pNew;
   123508   }else{
   123509     pNew->next = pH->first;
   123510     if( pH->first ){ pH->first->prev = pNew; }
   123511     pNew->prev = 0;
   123512     pH->first = pNew;
   123513   }
   123514   pEntry->count++;
   123515   pEntry->chain = pNew;
   123516 }
   123517 
   123518 
   123519 /* Resize the hash table so that it cantains "new_size" buckets.
   123520 ** "new_size" must be a power of 2.  The hash table might fail
   123521 ** to resize if sqliteMalloc() fails.
   123522 **
   123523 ** Return non-zero if a memory allocation error occurs.
   123524 */
   123525 static int fts3Rehash(Fts3Hash *pH, int new_size){
   123526   struct _fts3ht *new_ht;          /* The new hash table */
   123527   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   123528   int (*xHash)(const void*,int);   /* The hash function */
   123529 
   123530   assert( (new_size & (new_size-1))==0 );
   123531   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   123532   if( new_ht==0 ) return 1;
   123533   fts3HashFree(pH->ht);
   123534   pH->ht = new_ht;
   123535   pH->htsize = new_size;
   123536   xHash = ftsHashFunction(pH->keyClass);
   123537   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   123538     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   123539     next_elem = elem->next;
   123540     fts3HashInsertElement(pH, &new_ht[h], elem);
   123541   }
   123542   return 0;
   123543 }
   123544 
   123545 /* This function (for internal use only) locates an element in an
   123546 ** hash table that matches the given key.  The hash for this key has
   123547 ** already been computed and is passed as the 4th parameter.
   123548 */
   123549 static Fts3HashElem *fts3FindElementByHash(
   123550   const Fts3Hash *pH, /* The pH to be searched */
   123551   const void *pKey,   /* The key we are searching for */
   123552   int nKey,
   123553   int h               /* The hash for this key. */
   123554 ){
   123555   Fts3HashElem *elem;            /* Used to loop thru the element list */
   123556   int count;                     /* Number of elements left to test */
   123557   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   123558 
   123559   if( pH->ht ){
   123560     struct _fts3ht *pEntry = &pH->ht[h];
   123561     elem = pEntry->chain;
   123562     count = pEntry->count;
   123563     xCompare = ftsCompareFunction(pH->keyClass);
   123564     while( count-- && elem ){
   123565       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   123566         return elem;
   123567       }
   123568       elem = elem->next;
   123569     }
   123570   }
   123571   return 0;
   123572 }
   123573 
   123574 /* Remove a single entry from the hash table given a pointer to that
   123575 ** element and a hash on the element's key.
   123576 */
   123577 static void fts3RemoveElementByHash(
   123578   Fts3Hash *pH,         /* The pH containing "elem" */
   123579   Fts3HashElem* elem,   /* The element to be removed from the pH */
   123580   int h                 /* Hash value for the element */
   123581 ){
   123582   struct _fts3ht *pEntry;
   123583   if( elem->prev ){
   123584     elem->prev->next = elem->next;
   123585   }else{
   123586     pH->first = elem->next;
   123587   }
   123588   if( elem->next ){
   123589     elem->next->prev = elem->prev;
   123590   }
   123591   pEntry = &pH->ht[h];
   123592   if( pEntry->chain==elem ){
   123593     pEntry->chain = elem->next;
   123594   }
   123595   pEntry->count--;
   123596   if( pEntry->count<=0 ){
   123597     pEntry->chain = 0;
   123598   }
   123599   if( pH->copyKey && elem->pKey ){
   123600     fts3HashFree(elem->pKey);
   123601   }
   123602   fts3HashFree( elem );
   123603   pH->count--;
   123604   if( pH->count<=0 ){
   123605     assert( pH->first==0 );
   123606     assert( pH->count==0 );
   123607     fts3HashClear(pH);
   123608   }
   123609 }
   123610 
   123611 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   123612   const Fts3Hash *pH,
   123613   const void *pKey,
   123614   int nKey
   123615 ){
   123616   int h;                          /* A hash on key */
   123617   int (*xHash)(const void*,int);  /* The hash function */
   123618 
   123619   if( pH==0 || pH->ht==0 ) return 0;
   123620   xHash = ftsHashFunction(pH->keyClass);
   123621   assert( xHash!=0 );
   123622   h = (*xHash)(pKey,nKey);
   123623   assert( (pH->htsize & (pH->htsize-1))==0 );
   123624   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   123625 }
   123626 
   123627 /*
   123628 ** Attempt to locate an element of the hash table pH with a key
   123629 ** that matches pKey,nKey.  Return the data for this element if it is
   123630 ** found, or NULL if there is no match.
   123631 */
   123632 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   123633   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   123634 
   123635   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   123636   return pElem ? pElem->data : 0;
   123637 }
   123638 
   123639 /* Insert an element into the hash table pH.  The key is pKey,nKey
   123640 ** and the data is "data".
   123641 **
   123642 ** If no element exists with a matching key, then a new
   123643 ** element is created.  A copy of the key is made if the copyKey
   123644 ** flag is set.  NULL is returned.
   123645 **
   123646 ** If another element already exists with the same key, then the
   123647 ** new data replaces the old data and the old data is returned.
   123648 ** The key is not copied in this instance.  If a malloc fails, then
   123649 ** the new data is returned and the hash table is unchanged.
   123650 **
   123651 ** If the "data" parameter to this function is NULL, then the
   123652 ** element corresponding to "key" is removed from the hash table.
   123653 */
   123654 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   123655   Fts3Hash *pH,        /* The hash table to insert into */
   123656   const void *pKey,    /* The key */
   123657   int nKey,            /* Number of bytes in the key */
   123658   void *data           /* The data */
   123659 ){
   123660   int hraw;                 /* Raw hash value of the key */
   123661   int h;                    /* the hash of the key modulo hash table size */
   123662   Fts3HashElem *elem;       /* Used to loop thru the element list */
   123663   Fts3HashElem *new_elem;   /* New element added to the pH */
   123664   int (*xHash)(const void*,int);  /* The hash function */
   123665 
   123666   assert( pH!=0 );
   123667   xHash = ftsHashFunction(pH->keyClass);
   123668   assert( xHash!=0 );
   123669   hraw = (*xHash)(pKey, nKey);
   123670   assert( (pH->htsize & (pH->htsize-1))==0 );
   123671   h = hraw & (pH->htsize-1);
   123672   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   123673   if( elem ){
   123674     void *old_data = elem->data;
   123675     if( data==0 ){
   123676       fts3RemoveElementByHash(pH,elem,h);
   123677     }else{
   123678       elem->data = data;
   123679     }
   123680     return old_data;
   123681   }
   123682   if( data==0 ) return 0;
   123683   if( (pH->htsize==0 && fts3Rehash(pH,8))
   123684    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   123685   ){
   123686     pH->count = 0;
   123687     return data;
   123688   }
   123689   assert( pH->htsize>0 );
   123690   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   123691   if( new_elem==0 ) return data;
   123692   if( pH->copyKey && pKey!=0 ){
   123693     new_elem->pKey = fts3HashMalloc( nKey );
   123694     if( new_elem->pKey==0 ){
   123695       fts3HashFree(new_elem);
   123696       return data;
   123697     }
   123698     memcpy((void*)new_elem->pKey, pKey, nKey);
   123699   }else{
   123700     new_elem->pKey = (void*)pKey;
   123701   }
   123702   new_elem->nKey = nKey;
   123703   pH->count++;
   123704   assert( pH->htsize>0 );
   123705   assert( (pH->htsize & (pH->htsize-1))==0 );
   123706   h = hraw & (pH->htsize-1);
   123707   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   123708   new_elem->data = data;
   123709   return 0;
   123710 }
   123711 
   123712 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   123713 
   123714 /************** End of fts3_hash.c *******************************************/
   123715 /************** Begin file fts3_porter.c *************************************/
   123716 /*
   123717 ** 2006 September 30
   123718 **
   123719 ** The author disclaims copyright to this source code.  In place of
   123720 ** a legal notice, here is a blessing:
   123721 **
   123722 **    May you do good and not evil.
   123723 **    May you find forgiveness for yourself and forgive others.
   123724 **    May you share freely, never taking more than you give.
   123725 **
   123726 *************************************************************************
   123727 ** Implementation of the full-text-search tokenizer that implements
   123728 ** a Porter stemmer.
   123729 */
   123730 
   123731 /*
   123732 ** The code in this file is only compiled if:
   123733 **
   123734 **     * The FTS3 module is being built as an extension
   123735 **       (in which case SQLITE_CORE is not defined), or
   123736 **
   123737 **     * The FTS3 module is being built into the core of
   123738 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   123739 */
   123740 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   123741 
   123742 /* #include <assert.h> */
   123743 /* #include <stdlib.h> */
   123744 /* #include <stdio.h> */
   123745 /* #include <string.h> */
   123746 
   123747 
   123748 /*
   123749 ** Class derived from sqlite3_tokenizer
   123750 */
   123751 typedef struct porter_tokenizer {
   123752   sqlite3_tokenizer base;      /* Base class */
   123753 } porter_tokenizer;
   123754 
   123755 /*
   123756 ** Class derived from sqlite3_tokenizer_cursor
   123757 */
   123758 typedef struct porter_tokenizer_cursor {
   123759   sqlite3_tokenizer_cursor base;
   123760   const char *zInput;          /* input we are tokenizing */
   123761   int nInput;                  /* size of the input */
   123762   int iOffset;                 /* current position in zInput */
   123763   int iToken;                  /* index of next token to be returned */
   123764   char *zToken;                /* storage for current token */
   123765   int nAllocated;              /* space allocated to zToken buffer */
   123766 } porter_tokenizer_cursor;
   123767 
   123768 
   123769 /*
   123770 ** Create a new tokenizer instance.
   123771 */
   123772 static int porterCreate(
   123773   int argc, const char * const *argv,
   123774   sqlite3_tokenizer **ppTokenizer
   123775 ){
   123776   porter_tokenizer *t;
   123777 
   123778   UNUSED_PARAMETER(argc);
   123779   UNUSED_PARAMETER(argv);
   123780 
   123781   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   123782   if( t==NULL ) return SQLITE_NOMEM;
   123783   memset(t, 0, sizeof(*t));
   123784   *ppTokenizer = &t->base;
   123785   return SQLITE_OK;
   123786 }
   123787 
   123788 /*
   123789 ** Destroy a tokenizer
   123790 */
   123791 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   123792   sqlite3_free(pTokenizer);
   123793   return SQLITE_OK;
   123794 }
   123795 
   123796 /*
   123797 ** Prepare to begin tokenizing a particular string.  The input
   123798 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   123799 ** used to incrementally tokenize this string is returned in
   123800 ** *ppCursor.
   123801 */
   123802 static int porterOpen(
   123803   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   123804   const char *zInput, int nInput,        /* String to be tokenized */
   123805   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   123806 ){
   123807   porter_tokenizer_cursor *c;
   123808 
   123809   UNUSED_PARAMETER(pTokenizer);
   123810 
   123811   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   123812   if( c==NULL ) return SQLITE_NOMEM;
   123813 
   123814   c->zInput = zInput;
   123815   if( zInput==0 ){
   123816     c->nInput = 0;
   123817   }else if( nInput<0 ){
   123818     c->nInput = (int)strlen(zInput);
   123819   }else{
   123820     c->nInput = nInput;
   123821   }
   123822   c->iOffset = 0;                 /* start tokenizing at the beginning */
   123823   c->iToken = 0;
   123824   c->zToken = NULL;               /* no space allocated, yet. */
   123825   c->nAllocated = 0;
   123826 
   123827   *ppCursor = &c->base;
   123828   return SQLITE_OK;
   123829 }
   123830 
   123831 /*
   123832 ** Close a tokenization cursor previously opened by a call to
   123833 ** porterOpen() above.
   123834 */
   123835 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   123836   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   123837   sqlite3_free(c->zToken);
   123838   sqlite3_free(c);
   123839   return SQLITE_OK;
   123840 }
   123841 /*
   123842 ** Vowel or consonant
   123843 */
   123844 static const char cType[] = {
   123845    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   123846    1, 1, 1, 2, 1
   123847 };
   123848 
   123849 /*
   123850 ** isConsonant() and isVowel() determine if their first character in
   123851 ** the string they point to is a consonant or a vowel, according
   123852 ** to Porter ruls.
   123853 **
   123854 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   123855 ** 'Y' is a consonant unless it follows another consonant,
   123856 ** in which case it is a vowel.
   123857 **
   123858 ** In these routine, the letters are in reverse order.  So the 'y' rule
   123859 ** is that 'y' is a consonant unless it is followed by another
   123860 ** consonent.
   123861 */
   123862 static int isVowel(const char*);
   123863 static int isConsonant(const char *z){
   123864   int j;
   123865   char x = *z;
   123866   if( x==0 ) return 0;
   123867   assert( x>='a' && x<='z' );
   123868   j = cType[x-'a'];
   123869   if( j<2 ) return j;
   123870   return z[1]==0 || isVowel(z + 1);
   123871 }
   123872 static int isVowel(const char *z){
   123873   int j;
   123874   char x = *z;
   123875   if( x==0 ) return 0;
   123876   assert( x>='a' && x<='z' );
   123877   j = cType[x-'a'];
   123878   if( j<2 ) return 1-j;
   123879   return isConsonant(z + 1);
   123880 }
   123881 
   123882 /*
   123883 ** Let any sequence of one or more vowels be represented by V and let
   123884 ** C be sequence of one or more consonants.  Then every word can be
   123885 ** represented as:
   123886 **
   123887 **           [C] (VC){m} [V]
   123888 **
   123889 ** In prose:  A word is an optional consonant followed by zero or
   123890 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   123891 ** number of vowel consonant pairs.  This routine computes the value
   123892 ** of m for the first i bytes of a word.
   123893 **
   123894 ** Return true if the m-value for z is 1 or more.  In other words,
   123895 ** return true if z contains at least one vowel that is followed
   123896 ** by a consonant.
   123897 **
   123898 ** In this routine z[] is in reverse order.  So we are really looking
   123899 ** for an instance of of a consonant followed by a vowel.
   123900 */
   123901 static int m_gt_0(const char *z){
   123902   while( isVowel(z) ){ z++; }
   123903   if( *z==0 ) return 0;
   123904   while( isConsonant(z) ){ z++; }
   123905   return *z!=0;
   123906 }
   123907 
   123908 /* Like mgt0 above except we are looking for a value of m which is
   123909 ** exactly 1
   123910 */
   123911 static int m_eq_1(const char *z){
   123912   while( isVowel(z) ){ z++; }
   123913   if( *z==0 ) return 0;
   123914   while( isConsonant(z) ){ z++; }
   123915   if( *z==0 ) return 0;
   123916   while( isVowel(z) ){ z++; }
   123917   if( *z==0 ) return 1;
   123918   while( isConsonant(z) ){ z++; }
   123919   return *z==0;
   123920 }
   123921 
   123922 /* Like mgt0 above except we are looking for a value of m>1 instead
   123923 ** or m>0
   123924 */
   123925 static int m_gt_1(const char *z){
   123926   while( isVowel(z) ){ z++; }
   123927   if( *z==0 ) return 0;
   123928   while( isConsonant(z) ){ z++; }
   123929   if( *z==0 ) return 0;
   123930   while( isVowel(z) ){ z++; }
   123931   if( *z==0 ) return 0;
   123932   while( isConsonant(z) ){ z++; }
   123933   return *z!=0;
   123934 }
   123935 
   123936 /*
   123937 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   123938 */
   123939 static int hasVowel(const char *z){
   123940   while( isConsonant(z) ){ z++; }
   123941   return *z!=0;
   123942 }
   123943 
   123944 /*
   123945 ** Return TRUE if the word ends in a double consonant.
   123946 **
   123947 ** The text is reversed here. So we are really looking at
   123948 ** the first two characters of z[].
   123949 */
   123950 static int doubleConsonant(const char *z){
   123951   return isConsonant(z) && z[0]==z[1];
   123952 }
   123953 
   123954 /*
   123955 ** Return TRUE if the word ends with three letters which
   123956 ** are consonant-vowel-consonent and where the final consonant
   123957 ** is not 'w', 'x', or 'y'.
   123958 **
   123959 ** The word is reversed here.  So we are really checking the
   123960 ** first three letters and the first one cannot be in [wxy].
   123961 */
   123962 static int star_oh(const char *z){
   123963   return
   123964     isConsonant(z) &&
   123965     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   123966     isVowel(z+1) &&
   123967     isConsonant(z+2);
   123968 }
   123969 
   123970 /*
   123971 ** If the word ends with zFrom and xCond() is true for the stem
   123972 ** of the word that preceeds the zFrom ending, then change the
   123973 ** ending to zTo.
   123974 **
   123975 ** The input word *pz and zFrom are both in reverse order.  zTo
   123976 ** is in normal order.
   123977 **
   123978 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   123979 ** match.  Not that TRUE is returned even if xCond() fails and
   123980 ** no substitution occurs.
   123981 */
   123982 static int stem(
   123983   char **pz,             /* The word being stemmed (Reversed) */
   123984   const char *zFrom,     /* If the ending matches this... (Reversed) */
   123985   const char *zTo,       /* ... change the ending to this (not reversed) */
   123986   int (*xCond)(const char*)   /* Condition that must be true */
   123987 ){
   123988   char *z = *pz;
   123989   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   123990   if( *zFrom!=0 ) return 0;
   123991   if( xCond && !xCond(z) ) return 1;
   123992   while( *zTo ){
   123993     *(--z) = *(zTo++);
   123994   }
   123995   *pz = z;
   123996   return 1;
   123997 }
   123998 
   123999 /*
   124000 ** This is the fallback stemmer used when the porter stemmer is
   124001 ** inappropriate.  The input word is copied into the output with
   124002 ** US-ASCII case folding.  If the input word is too long (more
   124003 ** than 20 bytes if it contains no digits or more than 6 bytes if
   124004 ** it contains digits) then word is truncated to 20 or 6 bytes
   124005 ** by taking 10 or 3 bytes from the beginning and end.
   124006 */
   124007 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   124008   int i, mx, j;
   124009   int hasDigit = 0;
   124010   for(i=0; i<nIn; i++){
   124011     char c = zIn[i];
   124012     if( c>='A' && c<='Z' ){
   124013       zOut[i] = c - 'A' + 'a';
   124014     }else{
   124015       if( c>='0' && c<='9' ) hasDigit = 1;
   124016       zOut[i] = c;
   124017     }
   124018   }
   124019   mx = hasDigit ? 3 : 10;
   124020   if( nIn>mx*2 ){
   124021     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   124022       zOut[j] = zOut[i];
   124023     }
   124024     i = j;
   124025   }
   124026   zOut[i] = 0;
   124027   *pnOut = i;
   124028 }
   124029 
   124030 
   124031 /*
   124032 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   124033 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   124034 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   124035 **
   124036 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   124037 ** are converted to lower case.  Upper-case UTF characters are
   124038 ** unchanged.
   124039 **
   124040 ** Words that are longer than about 20 bytes are stemmed by retaining
   124041 ** a few bytes from the beginning and the end of the word.  If the
   124042 ** word contains digits, 3 bytes are taken from the beginning and
   124043 ** 3 bytes from the end.  For long words without digits, 10 bytes
   124044 ** are taken from each end.  US-ASCII case folding still applies.
   124045 **
   124046 ** If the input word contains not digits but does characters not
   124047 ** in [a-zA-Z] then no stemming is attempted and this routine just
   124048 ** copies the input into the input into the output with US-ASCII
   124049 ** case folding.
   124050 **
   124051 ** Stemming never increases the length of the word.  So there is
   124052 ** no chance of overflowing the zOut buffer.
   124053 */
   124054 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   124055   int i, j;
   124056   char zReverse[28];
   124057   char *z, *z2;
   124058   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   124059     /* The word is too big or too small for the porter stemmer.
   124060     ** Fallback to the copy stemmer */
   124061     copy_stemmer(zIn, nIn, zOut, pnOut);
   124062     return;
   124063   }
   124064   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   124065     char c = zIn[i];
   124066     if( c>='A' && c<='Z' ){
   124067       zReverse[j] = c + 'a' - 'A';
   124068     }else if( c>='a' && c<='z' ){
   124069       zReverse[j] = c;
   124070     }else{
   124071       /* The use of a character not in [a-zA-Z] means that we fallback
   124072       ** to the copy stemmer */
   124073       copy_stemmer(zIn, nIn, zOut, pnOut);
   124074       return;
   124075     }
   124076   }
   124077   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   124078   z = &zReverse[j+1];
   124079 
   124080 
   124081   /* Step 1a */
   124082   if( z[0]=='s' ){
   124083     if(
   124084      !stem(&z, "sess", "ss", 0) &&
   124085      !stem(&z, "sei", "i", 0)  &&
   124086      !stem(&z, "ss", "ss", 0)
   124087     ){
   124088       z++;
   124089     }
   124090   }
   124091 
   124092   /* Step 1b */
   124093   z2 = z;
   124094   if( stem(&z, "dee", "ee", m_gt_0) ){
   124095     /* Do nothing.  The work was all in the test */
   124096   }else if(
   124097      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   124098       && z!=z2
   124099   ){
   124100      if( stem(&z, "ta", "ate", 0) ||
   124101          stem(&z, "lb", "ble", 0) ||
   124102          stem(&z, "zi", "ize", 0) ){
   124103        /* Do nothing.  The work was all in the test */
   124104      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   124105        z++;
   124106      }else if( m_eq_1(z) && star_oh(z) ){
   124107        *(--z) = 'e';
   124108      }
   124109   }
   124110 
   124111   /* Step 1c */
   124112   if( z[0]=='y' && hasVowel(z+1) ){
   124113     z[0] = 'i';
   124114   }
   124115 
   124116   /* Step 2 */
   124117   switch( z[1] ){
   124118    case 'a':
   124119      stem(&z, "lanoita", "ate", m_gt_0) ||
   124120      stem(&z, "lanoit", "tion", m_gt_0);
   124121      break;
   124122    case 'c':
   124123      stem(&z, "icne", "ence", m_gt_0) ||
   124124      stem(&z, "icna", "ance", m_gt_0);
   124125      break;
   124126    case 'e':
   124127      stem(&z, "rezi", "ize", m_gt_0);
   124128      break;
   124129    case 'g':
   124130      stem(&z, "igol", "log", m_gt_0);
   124131      break;
   124132    case 'l':
   124133      stem(&z, "ilb", "ble", m_gt_0) ||
   124134      stem(&z, "illa", "al", m_gt_0) ||
   124135      stem(&z, "iltne", "ent", m_gt_0) ||
   124136      stem(&z, "ile", "e", m_gt_0) ||
   124137      stem(&z, "ilsuo", "ous", m_gt_0);
   124138      break;
   124139    case 'o':
   124140      stem(&z, "noitazi", "ize", m_gt_0) ||
   124141      stem(&z, "noita", "ate", m_gt_0) ||
   124142      stem(&z, "rota", "ate", m_gt_0);
   124143      break;
   124144    case 's':
   124145      stem(&z, "msila", "al", m_gt_0) ||
   124146      stem(&z, "ssenevi", "ive", m_gt_0) ||
   124147      stem(&z, "ssenluf", "ful", m_gt_0) ||
   124148      stem(&z, "ssensuo", "ous", m_gt_0);
   124149      break;
   124150    case 't':
   124151      stem(&z, "itila", "al", m_gt_0) ||
   124152      stem(&z, "itivi", "ive", m_gt_0) ||
   124153      stem(&z, "itilib", "ble", m_gt_0);
   124154      break;
   124155   }
   124156 
   124157   /* Step 3 */
   124158   switch( z[0] ){
   124159    case 'e':
   124160      stem(&z, "etaci", "ic", m_gt_0) ||
   124161      stem(&z, "evita", "", m_gt_0)   ||
   124162      stem(&z, "ezila", "al", m_gt_0);
   124163      break;
   124164    case 'i':
   124165      stem(&z, "itici", "ic", m_gt_0);
   124166      break;
   124167    case 'l':
   124168      stem(&z, "laci", "ic", m_gt_0) ||
   124169      stem(&z, "luf", "", m_gt_0);
   124170      break;
   124171    case 's':
   124172      stem(&z, "ssen", "", m_gt_0);
   124173      break;
   124174   }
   124175 
   124176   /* Step 4 */
   124177   switch( z[1] ){
   124178    case 'a':
   124179      if( z[0]=='l' && m_gt_1(z+2) ){
   124180        z += 2;
   124181      }
   124182      break;
   124183    case 'c':
   124184      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   124185        z += 4;
   124186      }
   124187      break;
   124188    case 'e':
   124189      if( z[0]=='r' && m_gt_1(z+2) ){
   124190        z += 2;
   124191      }
   124192      break;
   124193    case 'i':
   124194      if( z[0]=='c' && m_gt_1(z+2) ){
   124195        z += 2;
   124196      }
   124197      break;
   124198    case 'l':
   124199      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   124200        z += 4;
   124201      }
   124202      break;
   124203    case 'n':
   124204      if( z[0]=='t' ){
   124205        if( z[2]=='a' ){
   124206          if( m_gt_1(z+3) ){
   124207            z += 3;
   124208          }
   124209        }else if( z[2]=='e' ){
   124210          stem(&z, "tneme", "", m_gt_1) ||
   124211          stem(&z, "tnem", "", m_gt_1) ||
   124212          stem(&z, "tne", "", m_gt_1);
   124213        }
   124214      }
   124215      break;
   124216    case 'o':
   124217      if( z[0]=='u' ){
   124218        if( m_gt_1(z+2) ){
   124219          z += 2;
   124220        }
   124221      }else if( z[3]=='s' || z[3]=='t' ){
   124222        stem(&z, "noi", "", m_gt_1);
   124223      }
   124224      break;
   124225    case 's':
   124226      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   124227        z += 3;
   124228      }
   124229      break;
   124230    case 't':
   124231      stem(&z, "eta", "", m_gt_1) ||
   124232      stem(&z, "iti", "", m_gt_1);
   124233      break;
   124234    case 'u':
   124235      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   124236        z += 3;
   124237      }
   124238      break;
   124239    case 'v':
   124240    case 'z':
   124241      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   124242        z += 3;
   124243      }
   124244      break;
   124245   }
   124246 
   124247   /* Step 5a */
   124248   if( z[0]=='e' ){
   124249     if( m_gt_1(z+1) ){
   124250       z++;
   124251     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   124252       z++;
   124253     }
   124254   }
   124255 
   124256   /* Step 5b */
   124257   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   124258     z++;
   124259   }
   124260 
   124261   /* z[] is now the stemmed word in reverse order.  Flip it back
   124262   ** around into forward order and return.
   124263   */
   124264   *pnOut = i = (int)strlen(z);
   124265   zOut[i] = 0;
   124266   while( *z ){
   124267     zOut[--i] = *(z++);
   124268   }
   124269 }
   124270 
   124271 /*
   124272 ** Characters that can be part of a token.  We assume any character
   124273 ** whose value is greater than 0x80 (any UTF character) can be
   124274 ** part of a token.  In other words, delimiters all must have
   124275 ** values of 0x7f or lower.
   124276 */
   124277 static const char porterIdChar[] = {
   124278 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   124279     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   124280     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   124281     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   124282     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   124283     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   124284 };
   124285 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   124286 
   124287 /*
   124288 ** Extract the next token from a tokenization cursor.  The cursor must
   124289 ** have been opened by a prior call to porterOpen().
   124290 */
   124291 static int porterNext(
   124292   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   124293   const char **pzToken,               /* OUT: *pzToken is the token text */
   124294   int *pnBytes,                       /* OUT: Number of bytes in token */
   124295   int *piStartOffset,                 /* OUT: Starting offset of token */
   124296   int *piEndOffset,                   /* OUT: Ending offset of token */
   124297   int *piPosition                     /* OUT: Position integer of token */
   124298 ){
   124299   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   124300   const char *z = c->zInput;
   124301 
   124302   while( c->iOffset<c->nInput ){
   124303     int iStartOffset, ch;
   124304 
   124305     /* Scan past delimiter characters */
   124306     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   124307       c->iOffset++;
   124308     }
   124309 
   124310     /* Count non-delimiter characters. */
   124311     iStartOffset = c->iOffset;
   124312     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   124313       c->iOffset++;
   124314     }
   124315 
   124316     if( c->iOffset>iStartOffset ){
   124317       int n = c->iOffset-iStartOffset;
   124318       if( n>c->nAllocated ){
   124319         char *pNew;
   124320         c->nAllocated = n+20;
   124321         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   124322         if( !pNew ) return SQLITE_NOMEM;
   124323         c->zToken = pNew;
   124324       }
   124325       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   124326       *pzToken = c->zToken;
   124327       *piStartOffset = iStartOffset;
   124328       *piEndOffset = c->iOffset;
   124329       *piPosition = c->iToken++;
   124330       return SQLITE_OK;
   124331     }
   124332   }
   124333   return SQLITE_DONE;
   124334 }
   124335 
   124336 /*
   124337 ** The set of routines that implement the porter-stemmer tokenizer
   124338 */
   124339 static const sqlite3_tokenizer_module porterTokenizerModule = {
   124340   0,
   124341   porterCreate,
   124342   porterDestroy,
   124343   porterOpen,
   124344   porterClose,
   124345   porterNext,
   124346   0
   124347 };
   124348 
   124349 /*
   124350 ** Allocate a new porter tokenizer.  Return a pointer to the new
   124351 ** tokenizer in *ppModule
   124352 */
   124353 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   124354   sqlite3_tokenizer_module const**ppModule
   124355 ){
   124356   *ppModule = &porterTokenizerModule;
   124357 }
   124358 
   124359 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   124360 
   124361 /************** End of fts3_porter.c *****************************************/
   124362 /************** Begin file fts3_tokenizer.c **********************************/
   124363 /*
   124364 ** 2007 June 22
   124365 **
   124366 ** The author disclaims copyright to this source code.  In place of
   124367 ** a legal notice, here is a blessing:
   124368 **
   124369 **    May you do good and not evil.
   124370 **    May you find forgiveness for yourself and forgive others.
   124371 **    May you share freely, never taking more than you give.
   124372 **
   124373 ******************************************************************************
   124374 **
   124375 ** This is part of an SQLite module implementing full-text search.
   124376 ** This particular file implements the generic tokenizer interface.
   124377 */
   124378 
   124379 /*
   124380 ** The code in this file is only compiled if:
   124381 **
   124382 **     * The FTS3 module is being built as an extension
   124383 **       (in which case SQLITE_CORE is not defined), or
   124384 **
   124385 **     * The FTS3 module is being built into the core of
   124386 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   124387 */
   124388 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   124389 
   124390 /* #include <assert.h> */
   124391 /* #include <string.h> */
   124392 
   124393 /*
   124394 ** Implementation of the SQL scalar function for accessing the underlying
   124395 ** hash table. This function may be called as follows:
   124396 **
   124397 **   SELECT <function-name>(<key-name>);
   124398 **   SELECT <function-name>(<key-name>, <pointer>);
   124399 **
   124400 ** where <function-name> is the name passed as the second argument
   124401 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   124402 **
   124403 ** If the <pointer> argument is specified, it must be a blob value
   124404 ** containing a pointer to be stored as the hash data corresponding
   124405 ** to the string <key-name>. If <pointer> is not specified, then
   124406 ** the string <key-name> must already exist in the has table. Otherwise,
   124407 ** an error is returned.
   124408 **
   124409 ** Whether or not the <pointer> argument is specified, the value returned
   124410 ** is a blob containing the pointer stored as the hash data corresponding
   124411 ** to string <key-name> (after the hash-table is updated, if applicable).
   124412 */
   124413 static void scalarFunc(
   124414   sqlite3_context *context,
   124415   int argc,
   124416   sqlite3_value **argv
   124417 ){
   124418   Fts3Hash *pHash;
   124419   void *pPtr = 0;
   124420   const unsigned char *zName;
   124421   int nName;
   124422 
   124423   assert( argc==1 || argc==2 );
   124424 
   124425   pHash = (Fts3Hash *)sqlite3_user_data(context);
   124426 
   124427   zName = sqlite3_value_text(argv[0]);
   124428   nName = sqlite3_value_bytes(argv[0])+1;
   124429 
   124430   if( argc==2 ){
   124431     void *pOld;
   124432     int n = sqlite3_value_bytes(argv[1]);
   124433     if( n!=sizeof(pPtr) ){
   124434       sqlite3_result_error(context, "argument type mismatch", -1);
   124435       return;
   124436     }
   124437     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   124438     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   124439     if( pOld==pPtr ){
   124440       sqlite3_result_error(context, "out of memory", -1);
   124441       return;
   124442     }
   124443   }else{
   124444     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   124445     if( !pPtr ){
   124446       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   124447       sqlite3_result_error(context, zErr, -1);
   124448       sqlite3_free(zErr);
   124449       return;
   124450     }
   124451   }
   124452 
   124453   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   124454 }
   124455 
   124456 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   124457   static const char isFtsIdChar[] = {
   124458       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   124459       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   124460       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   124461       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   124462       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   124463       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   124464       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   124465       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   124466   };
   124467   return (c&0x80 || isFtsIdChar[(int)(c)]);
   124468 }
   124469 
   124470 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   124471   const char *z1;
   124472   const char *z2 = 0;
   124473 
   124474   /* Find the start of the next token. */
   124475   z1 = zStr;
   124476   while( z2==0 ){
   124477     char c = *z1;
   124478     switch( c ){
   124479       case '\0': return 0;        /* No more tokens here */
   124480       case '\'':
   124481       case '"':
   124482       case '`': {
   124483         z2 = z1;
   124484         while( *++z2 && (*z2!=c || *++z2==c) );
   124485         break;
   124486       }
   124487       case '[':
   124488         z2 = &z1[1];
   124489         while( *z2 && z2[0]!=']' ) z2++;
   124490         if( *z2 ) z2++;
   124491         break;
   124492 
   124493       default:
   124494         if( sqlite3Fts3IsIdChar(*z1) ){
   124495           z2 = &z1[1];
   124496           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   124497         }else{
   124498           z1++;
   124499         }
   124500     }
   124501   }
   124502 
   124503   *pn = (int)(z2-z1);
   124504   return z1;
   124505 }
   124506 
   124507 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   124508   Fts3Hash *pHash,                /* Tokenizer hash table */
   124509   const char *zArg,               /* Tokenizer name */
   124510   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   124511   char **pzErr                    /* OUT: Set to malloced error message */
   124512 ){
   124513   int rc;
   124514   char *z = (char *)zArg;
   124515   int n = 0;
   124516   char *zCopy;
   124517   char *zEnd;                     /* Pointer to nul-term of zCopy */
   124518   sqlite3_tokenizer_module *m;
   124519 
   124520   zCopy = sqlite3_mprintf("%s", zArg);
   124521   if( !zCopy ) return SQLITE_NOMEM;
   124522   zEnd = &zCopy[strlen(zCopy)];
   124523 
   124524   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   124525   z[n] = '\0';
   124526   sqlite3Fts3Dequote(z);
   124527 
   124528   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   124529   if( !m ){
   124530     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   124531     rc = SQLITE_ERROR;
   124532   }else{
   124533     char const **aArg = 0;
   124534     int iArg = 0;
   124535     z = &z[n+1];
   124536     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   124537       int nNew = sizeof(char *)*(iArg+1);
   124538       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   124539       if( !aNew ){
   124540         sqlite3_free(zCopy);
   124541         sqlite3_free((void *)aArg);
   124542         return SQLITE_NOMEM;
   124543       }
   124544       aArg = aNew;
   124545       aArg[iArg++] = z;
   124546       z[n] = '\0';
   124547       sqlite3Fts3Dequote(z);
   124548       z = &z[n+1];
   124549     }
   124550     rc = m->xCreate(iArg, aArg, ppTok);
   124551     assert( rc!=SQLITE_OK || *ppTok );
   124552     if( rc!=SQLITE_OK ){
   124553       *pzErr = sqlite3_mprintf("unknown tokenizer");
   124554     }else{
   124555       (*ppTok)->pModule = m;
   124556     }
   124557     sqlite3_free((void *)aArg);
   124558   }
   124559 
   124560   sqlite3_free(zCopy);
   124561   return rc;
   124562 }
   124563 
   124564 
   124565 #ifdef SQLITE_TEST
   124566 
   124567 /* #include <tcl.h> */
   124568 /* #include <string.h> */
   124569 
   124570 /*
   124571 ** Implementation of a special SQL scalar function for testing tokenizers
   124572 ** designed to be used in concert with the Tcl testing framework. This
   124573 ** function must be called with two arguments:
   124574 **
   124575 **   SELECT <function-name>(<key-name>, <input-string>);
   124576 **   SELECT <function-name>(<key-name>, <pointer>);
   124577 **
   124578 ** where <function-name> is the name passed as the second argument
   124579 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   124580 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   124581 **
   124582 ** The return value is a string that may be interpreted as a Tcl
   124583 ** list. For each token in the <input-string>, three elements are
   124584 ** added to the returned list. The first is the token position, the
   124585 ** second is the token text (folded, stemmed, etc.) and the third is the
   124586 ** substring of <input-string> associated with the token. For example,
   124587 ** using the built-in "simple" tokenizer:
   124588 **
   124589 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   124590 **
   124591 ** will return the string:
   124592 **
   124593 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   124594 **
   124595 */
   124596 static void testFunc(
   124597   sqlite3_context *context,
   124598   int argc,
   124599   sqlite3_value **argv
   124600 ){
   124601   Fts3Hash *pHash;
   124602   sqlite3_tokenizer_module *p;
   124603   sqlite3_tokenizer *pTokenizer = 0;
   124604   sqlite3_tokenizer_cursor *pCsr = 0;
   124605 
   124606   const char *zErr = 0;
   124607 
   124608   const char *zName;
   124609   int nName;
   124610   const char *zInput;
   124611   int nInput;
   124612 
   124613   const char *zArg = 0;
   124614 
   124615   const char *zToken;
   124616   int nToken;
   124617   int iStart;
   124618   int iEnd;
   124619   int iPos;
   124620 
   124621   Tcl_Obj *pRet;
   124622 
   124623   assert( argc==2 || argc==3 );
   124624 
   124625   nName = sqlite3_value_bytes(argv[0]);
   124626   zName = (const char *)sqlite3_value_text(argv[0]);
   124627   nInput = sqlite3_value_bytes(argv[argc-1]);
   124628   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   124629 
   124630   if( argc==3 ){
   124631     zArg = (const char *)sqlite3_value_text(argv[1]);
   124632   }
   124633 
   124634   pHash = (Fts3Hash *)sqlite3_user_data(context);
   124635   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   124636 
   124637   if( !p ){
   124638     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   124639     sqlite3_result_error(context, zErr, -1);
   124640     sqlite3_free(zErr);
   124641     return;
   124642   }
   124643 
   124644   pRet = Tcl_NewObj();
   124645   Tcl_IncrRefCount(pRet);
   124646 
   124647   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
   124648     zErr = "error in xCreate()";
   124649     goto finish;
   124650   }
   124651   pTokenizer->pModule = p;
   124652   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
   124653     zErr = "error in xOpen()";
   124654     goto finish;
   124655   }
   124656 
   124657   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   124658     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   124659     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   124660     zToken = &zInput[iStart];
   124661     nToken = iEnd-iStart;
   124662     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   124663   }
   124664 
   124665   if( SQLITE_OK!=p->xClose(pCsr) ){
   124666     zErr = "error in xClose()";
   124667     goto finish;
   124668   }
   124669   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   124670     zErr = "error in xDestroy()";
   124671     goto finish;
   124672   }
   124673 
   124674 finish:
   124675   if( zErr ){
   124676     sqlite3_result_error(context, zErr, -1);
   124677   }else{
   124678     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   124679   }
   124680   Tcl_DecrRefCount(pRet);
   124681 }
   124682 
   124683 static
   124684 int registerTokenizer(
   124685   sqlite3 *db,
   124686   char *zName,
   124687   const sqlite3_tokenizer_module *p
   124688 ){
   124689   int rc;
   124690   sqlite3_stmt *pStmt;
   124691   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   124692 
   124693   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   124694   if( rc!=SQLITE_OK ){
   124695     return rc;
   124696   }
   124697 
   124698   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   124699   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   124700   sqlite3_step(pStmt);
   124701 
   124702   return sqlite3_finalize(pStmt);
   124703 }
   124704 
   124705 static
   124706 int queryTokenizer(
   124707   sqlite3 *db,
   124708   char *zName,
   124709   const sqlite3_tokenizer_module **pp
   124710 ){
   124711   int rc;
   124712   sqlite3_stmt *pStmt;
   124713   const char zSql[] = "SELECT fts3_tokenizer(?)";
   124714 
   124715   *pp = 0;
   124716   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   124717   if( rc!=SQLITE_OK ){
   124718     return rc;
   124719   }
   124720 
   124721   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   124722   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   124723     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   124724       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   124725     }
   124726   }
   124727 
   124728   return sqlite3_finalize(pStmt);
   124729 }
   124730 
   124731 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   124732 
   124733 /*
   124734 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   124735 ** This function is used for testing only, it is not included in the
   124736 ** build unless SQLITE_TEST is defined.
   124737 **
   124738 ** The purpose of this is to test that the fts3_tokenizer() function
   124739 ** can be used as designed by the C-code in the queryTokenizer and
   124740 ** registerTokenizer() functions above. These two functions are repeated
   124741 ** in the README.tokenizer file as an example, so it is important to
   124742 ** test them.
   124743 **
   124744 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   124745 ** function with no arguments. An assert() will fail if a problem is
   124746 ** detected. i.e.:
   124747 **
   124748 **     SELECT fts3_tokenizer_internal_test();
   124749 **
   124750 */
   124751 static void intTestFunc(
   124752   sqlite3_context *context,
   124753   int argc,
   124754   sqlite3_value **argv
   124755 ){
   124756   int rc;
   124757   const sqlite3_tokenizer_module *p1;
   124758   const sqlite3_tokenizer_module *p2;
   124759   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   124760 
   124761   UNUSED_PARAMETER(argc);
   124762   UNUSED_PARAMETER(argv);
   124763 
   124764   /* Test the query function */
   124765   sqlite3Fts3SimpleTokenizerModule(&p1);
   124766   rc = queryTokenizer(db, "simple", &p2);
   124767   assert( rc==SQLITE_OK );
   124768   assert( p1==p2 );
   124769   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   124770   assert( rc==SQLITE_ERROR );
   124771   assert( p2==0 );
   124772   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   124773 
   124774   /* Test the storage function */
   124775   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   124776   assert( rc==SQLITE_OK );
   124777   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   124778   assert( rc==SQLITE_OK );
   124779   assert( p2==p1 );
   124780 
   124781   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   124782 }
   124783 
   124784 #endif
   124785 
   124786 /*
   124787 ** Set up SQL objects in database db used to access the contents of
   124788 ** the hash table pointed to by argument pHash. The hash table must
   124789 ** been initialised to use string keys, and to take a private copy
   124790 ** of the key when a value is inserted. i.e. by a call similar to:
   124791 **
   124792 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   124793 **
   124794 ** This function adds a scalar function (see header comment above
   124795 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   124796 ** defined at compilation time, a temporary virtual table (see header
   124797 ** comment above struct HashTableVtab) to the database schema. Both
   124798 ** provide read/write access to the contents of *pHash.
   124799 **
   124800 ** The third argument to this function, zName, is used as the name
   124801 ** of both the scalar and, if created, the virtual table.
   124802 */
   124803 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   124804   sqlite3 *db,
   124805   Fts3Hash *pHash,
   124806   const char *zName
   124807 ){
   124808   int rc = SQLITE_OK;
   124809   void *p = (void *)pHash;
   124810   const int any = SQLITE_ANY;
   124811 
   124812 #ifdef SQLITE_TEST
   124813   char *zTest = 0;
   124814   char *zTest2 = 0;
   124815   void *pdb = (void *)db;
   124816   zTest = sqlite3_mprintf("%s_test", zName);
   124817   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   124818   if( !zTest || !zTest2 ){
   124819     rc = SQLITE_NOMEM;
   124820   }
   124821 #endif
   124822 
   124823   if( SQLITE_OK==rc ){
   124824     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
   124825   }
   124826   if( SQLITE_OK==rc ){
   124827     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
   124828   }
   124829 #ifdef SQLITE_TEST
   124830   if( SQLITE_OK==rc ){
   124831     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
   124832   }
   124833   if( SQLITE_OK==rc ){
   124834     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
   124835   }
   124836   if( SQLITE_OK==rc ){
   124837     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   124838   }
   124839 #endif
   124840 
   124841 #ifdef SQLITE_TEST
   124842   sqlite3_free(zTest);
   124843   sqlite3_free(zTest2);
   124844 #endif
   124845 
   124846   return rc;
   124847 }
   124848 
   124849 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   124850 
   124851 /************** End of fts3_tokenizer.c **************************************/
   124852 /************** Begin file fts3_tokenizer1.c *********************************/
   124853 /*
   124854 ** 2006 Oct 10
   124855 **
   124856 ** The author disclaims copyright to this source code.  In place of
   124857 ** a legal notice, here is a blessing:
   124858 **
   124859 **    May you do good and not evil.
   124860 **    May you find forgiveness for yourself and forgive others.
   124861 **    May you share freely, never taking more than you give.
   124862 **
   124863 ******************************************************************************
   124864 **
   124865 ** Implementation of the "simple" full-text-search tokenizer.
   124866 */
   124867 
   124868 /*
   124869 ** The code in this file is only compiled if:
   124870 **
   124871 **     * The FTS3 module is being built as an extension
   124872 **       (in which case SQLITE_CORE is not defined), or
   124873 **
   124874 **     * The FTS3 module is being built into the core of
   124875 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   124876 */
   124877 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   124878 
   124879 /* #include <assert.h> */
   124880 /* #include <stdlib.h> */
   124881 /* #include <stdio.h> */
   124882 /* #include <string.h> */
   124883 
   124884 
   124885 typedef struct simple_tokenizer {
   124886   sqlite3_tokenizer base;
   124887   char delim[128];             /* flag ASCII delimiters */
   124888 } simple_tokenizer;
   124889 
   124890 typedef struct simple_tokenizer_cursor {
   124891   sqlite3_tokenizer_cursor base;
   124892   const char *pInput;          /* input we are tokenizing */
   124893   int nBytes;                  /* size of the input */
   124894   int iOffset;                 /* current position in pInput */
   124895   int iToken;                  /* index of next token to be returned */
   124896   char *pToken;                /* storage for current token */
   124897   int nTokenAllocated;         /* space allocated to zToken buffer */
   124898 } simple_tokenizer_cursor;
   124899 
   124900 
   124901 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   124902   return c<0x80 && t->delim[c];
   124903 }
   124904 static int fts3_isalnum(int x){
   124905   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   124906 }
   124907 
   124908 /*
   124909 ** Create a new tokenizer instance.
   124910 */
   124911 static int simpleCreate(
   124912   int argc, const char * const *argv,
   124913   sqlite3_tokenizer **ppTokenizer
   124914 ){
   124915   simple_tokenizer *t;
   124916 
   124917   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   124918   if( t==NULL ) return SQLITE_NOMEM;
   124919   memset(t, 0, sizeof(*t));
   124920 
   124921   /* TODO(shess) Delimiters need to remain the same from run to run,
   124922   ** else we need to reindex.  One solution would be a meta-table to
   124923   ** track such information in the database, then we'd only want this
   124924   ** information on the initial create.
   124925   */
   124926   if( argc>1 ){
   124927     int i, n = (int)strlen(argv[1]);
   124928     for(i=0; i<n; i++){
   124929       unsigned char ch = argv[1][i];
   124930       /* We explicitly don't support UTF-8 delimiters for now. */
   124931       if( ch>=0x80 ){
   124932         sqlite3_free(t);
   124933         return SQLITE_ERROR;
   124934       }
   124935       t->delim[ch] = 1;
   124936     }
   124937   } else {
   124938     /* Mark non-alphanumeric ASCII characters as delimiters */
   124939     int i;
   124940     for(i=1; i<0x80; i++){
   124941       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   124942     }
   124943   }
   124944 
   124945   *ppTokenizer = &t->base;
   124946   return SQLITE_OK;
   124947 }
   124948 
   124949 /*
   124950 ** Destroy a tokenizer
   124951 */
   124952 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   124953   sqlite3_free(pTokenizer);
   124954   return SQLITE_OK;
   124955 }
   124956 
   124957 /*
   124958 ** Prepare to begin tokenizing a particular string.  The input
   124959 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   124960 ** used to incrementally tokenize this string is returned in
   124961 ** *ppCursor.
   124962 */
   124963 static int simpleOpen(
   124964   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   124965   const char *pInput, int nBytes,        /* String to be tokenized */
   124966   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   124967 ){
   124968   simple_tokenizer_cursor *c;
   124969 
   124970   UNUSED_PARAMETER(pTokenizer);
   124971 
   124972   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   124973   if( c==NULL ) return SQLITE_NOMEM;
   124974 
   124975   c->pInput = pInput;
   124976   if( pInput==0 ){
   124977     c->nBytes = 0;
   124978   }else if( nBytes<0 ){
   124979     c->nBytes = (int)strlen(pInput);
   124980   }else{
   124981     c->nBytes = nBytes;
   124982   }
   124983   c->iOffset = 0;                 /* start tokenizing at the beginning */
   124984   c->iToken = 0;
   124985   c->pToken = NULL;               /* no space allocated, yet. */
   124986   c->nTokenAllocated = 0;
   124987 
   124988   *ppCursor = &c->base;
   124989   return SQLITE_OK;
   124990 }
   124991 
   124992 /*
   124993 ** Close a tokenization cursor previously opened by a call to
   124994 ** simpleOpen() above.
   124995 */
   124996 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   124997   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   124998   sqlite3_free(c->pToken);
   124999   sqlite3_free(c);
   125000   return SQLITE_OK;
   125001 }
   125002 
   125003 /*
   125004 ** Extract the next token from a tokenization cursor.  The cursor must
   125005 ** have been opened by a prior call to simpleOpen().
   125006 */
   125007 static int simpleNext(
   125008   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   125009   const char **ppToken,               /* OUT: *ppToken is the token text */
   125010   int *pnBytes,                       /* OUT: Number of bytes in token */
   125011   int *piStartOffset,                 /* OUT: Starting offset of token */
   125012   int *piEndOffset,                   /* OUT: Ending offset of token */
   125013   int *piPosition                     /* OUT: Position integer of token */
   125014 ){
   125015   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   125016   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   125017   unsigned char *p = (unsigned char *)c->pInput;
   125018 
   125019   while( c->iOffset<c->nBytes ){
   125020     int iStartOffset;
   125021 
   125022     /* Scan past delimiter characters */
   125023     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   125024       c->iOffset++;
   125025     }
   125026 
   125027     /* Count non-delimiter characters. */
   125028     iStartOffset = c->iOffset;
   125029     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   125030       c->iOffset++;
   125031     }
   125032 
   125033     if( c->iOffset>iStartOffset ){
   125034       int i, n = c->iOffset-iStartOffset;
   125035       if( n>c->nTokenAllocated ){
   125036         char *pNew;
   125037         c->nTokenAllocated = n+20;
   125038         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   125039         if( !pNew ) return SQLITE_NOMEM;
   125040         c->pToken = pNew;
   125041       }
   125042       for(i=0; i<n; i++){
   125043         /* TODO(shess) This needs expansion to handle UTF-8
   125044         ** case-insensitivity.
   125045         */
   125046         unsigned char ch = p[iStartOffset+i];
   125047         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   125048       }
   125049       *ppToken = c->pToken;
   125050       *pnBytes = n;
   125051       *piStartOffset = iStartOffset;
   125052       *piEndOffset = c->iOffset;
   125053       *piPosition = c->iToken++;
   125054 
   125055       return SQLITE_OK;
   125056     }
   125057   }
   125058   return SQLITE_DONE;
   125059 }
   125060 
   125061 /*
   125062 ** The set of routines that implement the simple tokenizer
   125063 */
   125064 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   125065   0,
   125066   simpleCreate,
   125067   simpleDestroy,
   125068   simpleOpen,
   125069   simpleClose,
   125070   simpleNext,
   125071   0,
   125072 };
   125073 
   125074 /*
   125075 ** Allocate a new simple tokenizer.  Return a pointer to the new
   125076 ** tokenizer in *ppModule
   125077 */
   125078 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   125079   sqlite3_tokenizer_module const**ppModule
   125080 ){
   125081   *ppModule = &simpleTokenizerModule;
   125082 }
   125083 
   125084 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   125085 
   125086 /************** End of fts3_tokenizer1.c *************************************/
   125087 /************** Begin file fts3_write.c **************************************/
   125088 /*
   125089 ** 2009 Oct 23
   125090 **
   125091 ** The author disclaims copyright to this source code.  In place of
   125092 ** a legal notice, here is a blessing:
   125093 **
   125094 **    May you do good and not evil.
   125095 **    May you find forgiveness for yourself and forgive others.
   125096 **    May you share freely, never taking more than you give.
   125097 **
   125098 ******************************************************************************
   125099 **
   125100 ** This file is part of the SQLite FTS3 extension module. Specifically,
   125101 ** this file contains code to insert, update and delete rows from FTS3
   125102 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   125103 ** of the sub-routines used to merge segments are also used by the query
   125104 ** code in fts3.c.
   125105 */
   125106 
   125107 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   125108 
   125109 /* #include <string.h> */
   125110 /* #include <assert.h> */
   125111 /* #include <stdlib.h> */
   125112 
   125113 /*
   125114 ** When full-text index nodes are loaded from disk, the buffer that they
   125115 ** are loaded into has the following number of bytes of padding at the end
   125116 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   125117 ** of 920 bytes is allocated for it.
   125118 **
   125119 ** This means that if we have a pointer into a buffer containing node data,
   125120 ** it is always safe to read up to two varints from it without risking an
   125121 ** overread, even if the node data is corrupted.
   125122 */
   125123 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   125124 
   125125 /*
   125126 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
   125127 ** memory incrementally instead of all at once. This can be a big performance
   125128 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
   125129 ** method before retrieving all query results (as may happen, for example,
   125130 ** if a query has a LIMIT clause).
   125131 **
   125132 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
   125133 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
   125134 ** The code is written so that the hard lower-limit for each of these values
   125135 ** is 1. Clearly such small values would be inefficient, but can be useful
   125136 ** for testing purposes.
   125137 **
   125138 ** If this module is built with SQLITE_TEST defined, these constants may
   125139 ** be overridden at runtime for testing purposes. File fts3_test.c contains
   125140 ** a Tcl interface to read and write the values.
   125141 */
   125142 #ifdef SQLITE_TEST
   125143 int test_fts3_node_chunksize = (4*1024);
   125144 int test_fts3_node_chunk_threshold = (4*1024)*4;
   125145 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
   125146 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
   125147 #else
   125148 # define FTS3_NODE_CHUNKSIZE (4*1024)
   125149 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
   125150 #endif
   125151 
   125152 typedef struct PendingList PendingList;
   125153 typedef struct SegmentNode SegmentNode;
   125154 typedef struct SegmentWriter SegmentWriter;
   125155 
   125156 /*
   125157 ** An instance of the following data structure is used to build doclists
   125158 ** incrementally. See function fts3PendingListAppend() for details.
   125159 */
   125160 struct PendingList {
   125161   int nData;
   125162   char *aData;
   125163   int nSpace;
   125164   sqlite3_int64 iLastDocid;
   125165   sqlite3_int64 iLastCol;
   125166   sqlite3_int64 iLastPos;
   125167 };
   125168 
   125169 
   125170 /*
   125171 ** Each cursor has a (possibly empty) linked list of the following objects.
   125172 */
   125173 struct Fts3DeferredToken {
   125174   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   125175   int iCol;                       /* Column token must occur in */
   125176   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   125177   PendingList *pList;             /* Doclist is assembled here */
   125178 };
   125179 
   125180 /*
   125181 ** An instance of this structure is used to iterate through the terms on
   125182 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   125183 ** this structure are only manipulated by code in this file, opaque handles
   125184 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   125185 ** terms when querying the full-text index. See functions:
   125186 **
   125187 **   sqlite3Fts3SegReaderNew()
   125188 **   sqlite3Fts3SegReaderFree()
   125189 **   sqlite3Fts3SegReaderIterate()
   125190 **
   125191 ** Methods used to manipulate Fts3SegReader structures:
   125192 **
   125193 **   fts3SegReaderNext()
   125194 **   fts3SegReaderFirstDocid()
   125195 **   fts3SegReaderNextDocid()
   125196 */
   125197 struct Fts3SegReader {
   125198   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   125199   int bLookup;                    /* True for a lookup only */
   125200 
   125201   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   125202   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   125203   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   125204   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   125205 
   125206   char *aNode;                    /* Pointer to node data (or NULL) */
   125207   int nNode;                      /* Size of buffer at aNode (or 0) */
   125208   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
   125209   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
   125210 
   125211   Fts3HashElem **ppNextElem;
   125212 
   125213   /* Variables set by fts3SegReaderNext(). These may be read directly
   125214   ** by the caller. They are valid from the time SegmentReaderNew() returns
   125215   ** until SegmentReaderNext() returns something other than SQLITE_OK
   125216   ** (i.e. SQLITE_DONE).
   125217   */
   125218   int nTerm;                      /* Number of bytes in current term */
   125219   char *zTerm;                    /* Pointer to current term */
   125220   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   125221   char *aDoclist;                 /* Pointer to doclist of current entry */
   125222   int nDoclist;                   /* Size of doclist in current entry */
   125223 
   125224   /* The following variables are used by fts3SegReaderNextDocid() to iterate
   125225   ** through the current doclist (aDoclist/nDoclist).
   125226   */
   125227   char *pOffsetList;
   125228   int nOffsetList;                /* For descending pending seg-readers only */
   125229   sqlite3_int64 iDocid;
   125230 };
   125231 
   125232 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   125233 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
   125234 
   125235 /*
   125236 ** An instance of this structure is used to create a segment b-tree in the
   125237 ** database. The internal details of this type are only accessed by the
   125238 ** following functions:
   125239 **
   125240 **   fts3SegWriterAdd()
   125241 **   fts3SegWriterFlush()
   125242 **   fts3SegWriterFree()
   125243 */
   125244 struct SegmentWriter {
   125245   SegmentNode *pTree;             /* Pointer to interior tree structure */
   125246   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   125247   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   125248   char *zTerm;                    /* Pointer to previous term buffer */
   125249   int nTerm;                      /* Number of bytes in zTerm */
   125250   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   125251   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   125252   int nSize;                      /* Size of allocation at aData */
   125253   int nData;                      /* Bytes of data in aData */
   125254   char *aData;                    /* Pointer to block from malloc() */
   125255 };
   125256 
   125257 /*
   125258 ** Type SegmentNode is used by the following three functions to create
   125259 ** the interior part of the segment b+-tree structures (everything except
   125260 ** the leaf nodes). These functions and type are only ever used by code
   125261 ** within the fts3SegWriterXXX() family of functions described above.
   125262 **
   125263 **   fts3NodeAddTerm()
   125264 **   fts3NodeWrite()
   125265 **   fts3NodeFree()
   125266 **
   125267 ** When a b+tree is written to the database (either as a result of a merge
   125268 ** or the pending-terms table being flushed), leaves are written into the
   125269 ** database file as soon as they are completely populated. The interior of
   125270 ** the tree is assembled in memory and written out only once all leaves have
   125271 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
   125272 ** very large, meaning that the interior of the tree consumes relatively
   125273 ** little memory.
   125274 */
   125275 struct SegmentNode {
   125276   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   125277   SegmentNode *pRight;            /* Pointer to right-sibling */
   125278   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   125279   int nEntry;                     /* Number of terms written to node so far */
   125280   char *zTerm;                    /* Pointer to previous term buffer */
   125281   int nTerm;                      /* Number of bytes in zTerm */
   125282   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   125283   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   125284   int nData;                      /* Bytes of valid data so far */
   125285   char *aData;                    /* Node data */
   125286 };
   125287 
   125288 /*
   125289 ** Valid values for the second argument to fts3SqlStmt().
   125290 */
   125291 #define SQL_DELETE_CONTENT             0
   125292 #define SQL_IS_EMPTY                   1
   125293 #define SQL_DELETE_ALL_CONTENT         2
   125294 #define SQL_DELETE_ALL_SEGMENTS        3
   125295 #define SQL_DELETE_ALL_SEGDIR          4
   125296 #define SQL_DELETE_ALL_DOCSIZE         5
   125297 #define SQL_DELETE_ALL_STAT            6
   125298 #define SQL_SELECT_CONTENT_BY_ROWID    7
   125299 #define SQL_NEXT_SEGMENT_INDEX         8
   125300 #define SQL_INSERT_SEGMENTS            9
   125301 #define SQL_NEXT_SEGMENTS_ID          10
   125302 #define SQL_INSERT_SEGDIR             11
   125303 #define SQL_SELECT_LEVEL              12
   125304 #define SQL_SELECT_LEVEL_RANGE        13
   125305 #define SQL_SELECT_LEVEL_COUNT        14
   125306 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
   125307 #define SQL_DELETE_SEGDIR_LEVEL       16
   125308 #define SQL_DELETE_SEGMENTS_RANGE     17
   125309 #define SQL_CONTENT_INSERT            18
   125310 #define SQL_DELETE_DOCSIZE            19
   125311 #define SQL_REPLACE_DOCSIZE           20
   125312 #define SQL_SELECT_DOCSIZE            21
   125313 #define SQL_SELECT_DOCTOTAL           22
   125314 #define SQL_REPLACE_DOCTOTAL          23
   125315 
   125316 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
   125317 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
   125318 
   125319 #define SQL_DELETE_SEGDIR_RANGE       26
   125320 
   125321 #define SQL_SELECT_ALL_LANGID         27
   125322 
   125323 /*
   125324 ** This function is used to obtain an SQLite prepared statement handle
   125325 ** for the statement identified by the second argument. If successful,
   125326 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   125327 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   125328 **
   125329 ** If argument apVal is not NULL, then it must point to an array with
   125330 ** at least as many entries as the requested statement has bound
   125331 ** parameters. The values are bound to the statements parameters before
   125332 ** returning.
   125333 */
   125334 static int fts3SqlStmt(
   125335   Fts3Table *p,                   /* Virtual table handle */
   125336   int eStmt,                      /* One of the SQL_XXX constants above */
   125337   sqlite3_stmt **pp,              /* OUT: Statement handle */
   125338   sqlite3_value **apVal           /* Values to bind to statement */
   125339 ){
   125340   const char *azSql[] = {
   125341 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   125342 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   125343 /* 2  */  "DELETE FROM %Q.'%q_content'",
   125344 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   125345 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   125346 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   125347 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   125348 /* 7  */  "SELECT %s WHERE rowid=?",
   125349 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   125350 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   125351 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   125352 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   125353 
   125354           /* Return segments in order from oldest to newest.*/
   125355 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   125356             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   125357 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   125358             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
   125359             "ORDER BY level DESC, idx ASC",
   125360 
   125361 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   125362 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   125363 
   125364 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   125365 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   125366 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
   125367 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   125368 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   125369 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   125370 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
   125371 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
   125372 /* 24 */  "",
   125373 /* 25 */  "",
   125374 
   125375 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
   125376 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
   125377 
   125378   };
   125379   int rc = SQLITE_OK;
   125380   sqlite3_stmt *pStmt;
   125381 
   125382   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   125383   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   125384 
   125385   pStmt = p->aStmt[eStmt];
   125386   if( !pStmt ){
   125387     char *zSql;
   125388     if( eStmt==SQL_CONTENT_INSERT ){
   125389       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
   125390     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
   125391       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
   125392     }else{
   125393       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   125394     }
   125395     if( !zSql ){
   125396       rc = SQLITE_NOMEM;
   125397     }else{
   125398       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   125399       sqlite3_free(zSql);
   125400       assert( rc==SQLITE_OK || pStmt==0 );
   125401       p->aStmt[eStmt] = pStmt;
   125402     }
   125403   }
   125404   if( apVal ){
   125405     int i;
   125406     int nParam = sqlite3_bind_parameter_count(pStmt);
   125407     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   125408       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   125409     }
   125410   }
   125411   *pp = pStmt;
   125412   return rc;
   125413 }
   125414 
   125415 static int fts3SelectDocsize(
   125416   Fts3Table *pTab,                /* FTS3 table handle */
   125417   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
   125418   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   125419   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125420 ){
   125421   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   125422   int rc;                         /* Return code */
   125423 
   125424   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
   125425 
   125426   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
   125427   if( rc==SQLITE_OK ){
   125428     if( eStmt==SQL_SELECT_DOCSIZE ){
   125429       sqlite3_bind_int64(pStmt, 1, iDocid);
   125430     }
   125431     rc = sqlite3_step(pStmt);
   125432     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
   125433       rc = sqlite3_reset(pStmt);
   125434       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
   125435       pStmt = 0;
   125436     }else{
   125437       rc = SQLITE_OK;
   125438     }
   125439   }
   125440 
   125441   *ppStmt = pStmt;
   125442   return rc;
   125443 }
   125444 
   125445 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   125446   Fts3Table *pTab,                /* Fts3 table handle */
   125447   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125448 ){
   125449   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
   125450 }
   125451 
   125452 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   125453   Fts3Table *pTab,                /* Fts3 table handle */
   125454   sqlite3_int64 iDocid,           /* Docid to read size data for */
   125455   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   125456 ){
   125457   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
   125458 }
   125459 
   125460 /*
   125461 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   125462 ** array apVal[] to the SQL statement identified by eStmt, the statement
   125463 ** is executed.
   125464 **
   125465 ** Returns SQLITE_OK if the statement is successfully executed, or an
   125466 ** SQLite error code otherwise.
   125467 */
   125468 static void fts3SqlExec(
   125469   int *pRC,                /* Result code */
   125470   Fts3Table *p,            /* The FTS3 table */
   125471   int eStmt,               /* Index of statement to evaluate */
   125472   sqlite3_value **apVal    /* Parameters to bind */
   125473 ){
   125474   sqlite3_stmt *pStmt;
   125475   int rc;
   125476   if( *pRC ) return;
   125477   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   125478   if( rc==SQLITE_OK ){
   125479     sqlite3_step(pStmt);
   125480     rc = sqlite3_reset(pStmt);
   125481   }
   125482   *pRC = rc;
   125483 }
   125484 
   125485 
   125486 /*
   125487 ** This function ensures that the caller has obtained a shared-cache
   125488 ** table-lock on the %_content table. This is required before reading
   125489 ** data from the fts3 table. If this lock is not acquired first, then
   125490 ** the caller may end up holding read-locks on the %_segments and %_segdir
   125491 ** tables, but no read-lock on the %_content table. If this happens
   125492 ** a second connection will be able to write to the fts3 table, but
   125493 ** attempting to commit those writes might return SQLITE_LOCKED or
   125494 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
   125495 ** write-locks on the %_segments and %_segdir ** tables).
   125496 **
   125497 ** We try to avoid this because if FTS3 returns any error when committing
   125498 ** a transaction, the whole transaction will be rolled back. And this is
   125499 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
   125500 ** still happen if the user reads data directly from the %_segments or
   125501 ** %_segdir tables instead of going through FTS3 though.
   125502 **
   125503 ** This reasoning does not apply to a content=xxx table.
   125504 */
   125505 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
   125506   int rc;                         /* Return code */
   125507   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
   125508 
   125509   if( p->zContentTbl==0 ){
   125510     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
   125511     if( rc==SQLITE_OK ){
   125512       sqlite3_bind_null(pStmt, 1);
   125513       sqlite3_step(pStmt);
   125514       rc = sqlite3_reset(pStmt);
   125515     }
   125516   }else{
   125517     rc = SQLITE_OK;
   125518   }
   125519 
   125520   return rc;
   125521 }
   125522 
   125523 /*
   125524 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
   125525 ** Within each language id, a separate index is maintained to store the
   125526 ** document terms, and each configured prefix size (configured the FTS
   125527 ** "prefix=" option). And each index consists of multiple levels ("relative
   125528 ** levels").
   125529 **
   125530 ** All three of these values (the language id, the specific index and the
   125531 ** level within the index) are encoded in 64-bit integer values stored
   125532 ** in the %_segdir table on disk. This function is used to convert three
   125533 ** separate component values into the single 64-bit integer value that
   125534 ** can be used to query the %_segdir table.
   125535 **
   125536 ** Specifically, each language-id/index combination is allocated 1024
   125537 ** 64-bit integer level values ("absolute levels"). The main terms index
   125538 ** for language-id 0 is allocate values 0-1023. The first prefix index
   125539 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
   125540 ** Language 1 indexes are allocated immediately following language 0.
   125541 **
   125542 ** So, for a system with nPrefix prefix indexes configured, the block of
   125543 ** absolute levels that corresponds to language-id iLangid and index
   125544 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
   125545 */
   125546 static sqlite3_int64 getAbsoluteLevel(
   125547   Fts3Table *p,
   125548   int iLangid,
   125549   int iIndex,
   125550   int iLevel
   125551 ){
   125552   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
   125553   assert( iLangid>=0 );
   125554   assert( p->nIndex>0 );
   125555   assert( iIndex>=0 && iIndex<p->nIndex );
   125556 
   125557   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
   125558   return iBase + iLevel;
   125559 }
   125560 
   125561 
   125562 /*
   125563 ** Set *ppStmt to a statement handle that may be used to iterate through
   125564 ** all rows in the %_segdir table, from oldest to newest. If successful,
   125565 ** return SQLITE_OK. If an error occurs while preparing the statement,
   125566 ** return an SQLite error code.
   125567 **
   125568 ** There is only ever one instance of this SQL statement compiled for
   125569 ** each FTS3 table.
   125570 **
   125571 ** The statement returns the following columns from the %_segdir table:
   125572 **
   125573 **   0: idx
   125574 **   1: start_block
   125575 **   2: leaves_end_block
   125576 **   3: end_block
   125577 **   4: root
   125578 */
   125579 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   125580   Fts3Table *p,                   /* FTS3 table */
   125581   int iLangid,                    /* Language being queried */
   125582   int iIndex,                     /* Index for p->aIndex[] */
   125583   int iLevel,                     /* Level to select (relative level) */
   125584   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
   125585 ){
   125586   int rc;
   125587   sqlite3_stmt *pStmt = 0;
   125588 
   125589   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
   125590   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   125591   assert( iIndex>=0 && iIndex<p->nIndex );
   125592 
   125593   if( iLevel<0 ){
   125594     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
   125595     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
   125596     if( rc==SQLITE_OK ){
   125597       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   125598       sqlite3_bind_int64(pStmt, 2,
   125599           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   125600       );
   125601     }
   125602   }else{
   125603     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
   125604     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
   125605     if( rc==SQLITE_OK ){
   125606       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
   125607     }
   125608   }
   125609   *ppStmt = pStmt;
   125610   return rc;
   125611 }
   125612 
   125613 
   125614 /*
   125615 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   125616 ** if successful, or an SQLite error code otherwise.
   125617 **
   125618 ** This function also serves to allocate the PendingList structure itself.
   125619 ** For example, to create a new PendingList structure containing two
   125620 ** varints:
   125621 **
   125622 **   PendingList *p = 0;
   125623 **   fts3PendingListAppendVarint(&p, 1);
   125624 **   fts3PendingListAppendVarint(&p, 2);
   125625 */
   125626 static int fts3PendingListAppendVarint(
   125627   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   125628   sqlite3_int64 i                 /* Value to append to data */
   125629 ){
   125630   PendingList *p = *pp;
   125631 
   125632   /* Allocate or grow the PendingList as required. */
   125633   if( !p ){
   125634     p = sqlite3_malloc(sizeof(*p) + 100);
   125635     if( !p ){
   125636       return SQLITE_NOMEM;
   125637     }
   125638     p->nSpace = 100;
   125639     p->aData = (char *)&p[1];
   125640     p->nData = 0;
   125641   }
   125642   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   125643     int nNew = p->nSpace * 2;
   125644     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   125645     if( !p ){
   125646       sqlite3_free(*pp);
   125647       *pp = 0;
   125648       return SQLITE_NOMEM;
   125649     }
   125650     p->nSpace = nNew;
   125651     p->aData = (char *)&p[1];
   125652   }
   125653 
   125654   /* Append the new serialized varint to the end of the list. */
   125655   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   125656   p->aData[p->nData] = '\0';
   125657   *pp = p;
   125658   return SQLITE_OK;
   125659 }
   125660 
   125661 /*
   125662 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   125663 ** is returned if the structure is sqlite3_realloced as part of adding
   125664 ** the entry. Otherwise, zero.
   125665 **
   125666 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   125667 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   125668 ** it is set to SQLITE_OK.
   125669 */
   125670 static int fts3PendingListAppend(
   125671   PendingList **pp,               /* IN/OUT: PendingList structure */
   125672   sqlite3_int64 iDocid,           /* Docid for entry to add */
   125673   sqlite3_int64 iCol,             /* Column for entry to add */
   125674   sqlite3_int64 iPos,             /* Position of term for entry to add */
   125675   int *pRc                        /* OUT: Return code */
   125676 ){
   125677   PendingList *p = *pp;
   125678   int rc = SQLITE_OK;
   125679 
   125680   assert( !p || p->iLastDocid<=iDocid );
   125681 
   125682   if( !p || p->iLastDocid!=iDocid ){
   125683     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   125684     if( p ){
   125685       assert( p->nData<p->nSpace );
   125686       assert( p->aData[p->nData]==0 );
   125687       p->nData++;
   125688     }
   125689     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   125690       goto pendinglistappend_out;
   125691     }
   125692     p->iLastCol = -1;
   125693     p->iLastPos = 0;
   125694     p->iLastDocid = iDocid;
   125695   }
   125696   if( iCol>0 && p->iLastCol!=iCol ){
   125697     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   125698      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   125699     ){
   125700       goto pendinglistappend_out;
   125701     }
   125702     p->iLastCol = iCol;
   125703     p->iLastPos = 0;
   125704   }
   125705   if( iCol>=0 ){
   125706     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   125707     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   125708     if( rc==SQLITE_OK ){
   125709       p->iLastPos = iPos;
   125710     }
   125711   }
   125712 
   125713  pendinglistappend_out:
   125714   *pRc = rc;
   125715   if( p!=*pp ){
   125716     *pp = p;
   125717     return 1;
   125718   }
   125719   return 0;
   125720 }
   125721 
   125722 /*
   125723 ** Free a PendingList object allocated by fts3PendingListAppend().
   125724 */
   125725 static void fts3PendingListDelete(PendingList *pList){
   125726   sqlite3_free(pList);
   125727 }
   125728 
   125729 /*
   125730 ** Add an entry to one of the pending-terms hash tables.
   125731 */
   125732 static int fts3PendingTermsAddOne(
   125733   Fts3Table *p,
   125734   int iCol,
   125735   int iPos,
   125736   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
   125737   const char *zToken,
   125738   int nToken
   125739 ){
   125740   PendingList *pList;
   125741   int rc = SQLITE_OK;
   125742 
   125743   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
   125744   if( pList ){
   125745     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   125746   }
   125747   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   125748     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
   125749       /* Malloc failed while inserting the new entry. This can only
   125750       ** happen if there was no previous entry for this token.
   125751       */
   125752       assert( 0==fts3HashFind(pHash, zToken, nToken) );
   125753       sqlite3_free(pList);
   125754       rc = SQLITE_NOMEM;
   125755     }
   125756   }
   125757   if( rc==SQLITE_OK ){
   125758     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   125759   }
   125760   return rc;
   125761 }
   125762 
   125763 /*
   125764 ** Tokenize the nul-terminated string zText and add all tokens to the
   125765 ** pending-terms hash-table. The docid used is that currently stored in
   125766 ** p->iPrevDocid, and the column is specified by argument iCol.
   125767 **
   125768 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   125769 */
   125770 static int fts3PendingTermsAdd(
   125771   Fts3Table *p,                   /* Table into which text will be inserted */
   125772   int iLangid,                    /* Language id to use */
   125773   const char *zText,              /* Text of document to be inserted */
   125774   int iCol,                       /* Column into which text is being inserted */
   125775   u32 *pnWord                     /* OUT: Number of tokens inserted */
   125776 ){
   125777   int rc;
   125778   int iStart;
   125779   int iEnd;
   125780   int iPos;
   125781   int nWord = 0;
   125782 
   125783   char const *zToken;
   125784   int nToken;
   125785 
   125786   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   125787   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   125788   sqlite3_tokenizer_cursor *pCsr;
   125789   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   125790       const char**,int*,int*,int*,int*);
   125791 
   125792   assert( pTokenizer && pModule );
   125793 
   125794   /* If the user has inserted a NULL value, this function may be called with
   125795   ** zText==0. In this case, add zero token entries to the hash table and
   125796   ** return early. */
   125797   if( zText==0 ){
   125798     *pnWord = 0;
   125799     return SQLITE_OK;
   125800   }
   125801 
   125802   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
   125803   if( rc!=SQLITE_OK ){
   125804     return rc;
   125805   }
   125806 
   125807   xNext = pModule->xNext;
   125808   while( SQLITE_OK==rc
   125809       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   125810   ){
   125811     int i;
   125812     if( iPos>=nWord ) nWord = iPos+1;
   125813 
   125814     /* Positions cannot be negative; we use -1 as a terminator internally.
   125815     ** Tokens must have a non-zero length.
   125816     */
   125817     if( iPos<0 || !zToken || nToken<=0 ){
   125818       rc = SQLITE_ERROR;
   125819       break;
   125820     }
   125821 
   125822     /* Add the term to the terms index */
   125823     rc = fts3PendingTermsAddOne(
   125824         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
   125825     );
   125826 
   125827     /* Add the term to each of the prefix indexes that it is not too
   125828     ** short for. */
   125829     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
   125830       struct Fts3Index *pIndex = &p->aIndex[i];
   125831       if( nToken<pIndex->nPrefix ) continue;
   125832       rc = fts3PendingTermsAddOne(
   125833           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
   125834       );
   125835     }
   125836   }
   125837 
   125838   pModule->xClose(pCsr);
   125839   *pnWord = nWord;
   125840   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   125841 }
   125842 
   125843 /*
   125844 ** Calling this function indicates that subsequent calls to
   125845 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   125846 ** contents of the document with docid iDocid.
   125847 */
   125848 static int fts3PendingTermsDocid(
   125849   Fts3Table *p,                   /* Full-text table handle */
   125850   int iLangid,                    /* Language id of row being written */
   125851   sqlite_int64 iDocid             /* Docid of row being written */
   125852 ){
   125853   assert( iLangid>=0 );
   125854 
   125855   /* TODO(shess) Explore whether partially flushing the buffer on
   125856   ** forced-flush would provide better performance.  I suspect that if
   125857   ** we ordered the doclists by size and flushed the largest until the
   125858   ** buffer was half empty, that would let the less frequent terms
   125859   ** generate longer doclists.
   125860   */
   125861   if( iDocid<=p->iPrevDocid
   125862    || p->iPrevLangid!=iLangid
   125863    || p->nPendingData>p->nMaxPendingData
   125864   ){
   125865     int rc = sqlite3Fts3PendingTermsFlush(p);
   125866     if( rc!=SQLITE_OK ) return rc;
   125867   }
   125868   p->iPrevDocid = iDocid;
   125869   p->iPrevLangid = iLangid;
   125870   return SQLITE_OK;
   125871 }
   125872 
   125873 /*
   125874 ** Discard the contents of the pending-terms hash tables.
   125875 */
   125876 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   125877   int i;
   125878   for(i=0; i<p->nIndex; i++){
   125879     Fts3HashElem *pElem;
   125880     Fts3Hash *pHash = &p->aIndex[i].hPending;
   125881     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
   125882       PendingList *pList = (PendingList *)fts3HashData(pElem);
   125883       fts3PendingListDelete(pList);
   125884     }
   125885     fts3HashClear(pHash);
   125886   }
   125887   p->nPendingData = 0;
   125888 }
   125889 
   125890 /*
   125891 ** This function is called by the xUpdate() method as part of an INSERT
   125892 ** operation. It adds entries for each term in the new record to the
   125893 ** pendingTerms hash table.
   125894 **
   125895 ** Argument apVal is the same as the similarly named argument passed to
   125896 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   125897 */
   125898 static int fts3InsertTerms(
   125899   Fts3Table *p,
   125900   int iLangid,
   125901   sqlite3_value **apVal,
   125902   u32 *aSz
   125903 ){
   125904   int i;                          /* Iterator variable */
   125905   for(i=2; i<p->nColumn+2; i++){
   125906     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   125907     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
   125908     if( rc!=SQLITE_OK ){
   125909       return rc;
   125910     }
   125911     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   125912   }
   125913   return SQLITE_OK;
   125914 }
   125915 
   125916 /*
   125917 ** This function is called by the xUpdate() method for an INSERT operation.
   125918 ** The apVal parameter is passed a copy of the apVal argument passed by
   125919 ** SQLite to the xUpdate() method. i.e:
   125920 **
   125921 **   apVal[0]                Not used for INSERT.
   125922 **   apVal[1]                rowid
   125923 **   apVal[2]                Left-most user-defined column
   125924 **   ...
   125925 **   apVal[p->nColumn+1]     Right-most user-defined column
   125926 **   apVal[p->nColumn+2]     Hidden column with same name as table
   125927 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   125928 **   apVal[p->nColumn+4]     Hidden languageid column
   125929 */
   125930 static int fts3InsertData(
   125931   Fts3Table *p,                   /* Full-text table */
   125932   sqlite3_value **apVal,          /* Array of values to insert */
   125933   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   125934 ){
   125935   int rc;                         /* Return code */
   125936   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   125937 
   125938   if( p->zContentTbl ){
   125939     sqlite3_value *pRowid = apVal[p->nColumn+3];
   125940     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
   125941       pRowid = apVal[1];
   125942     }
   125943     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
   125944       return SQLITE_CONSTRAINT;
   125945     }
   125946     *piDocid = sqlite3_value_int64(pRowid);
   125947     return SQLITE_OK;
   125948   }
   125949 
   125950   /* Locate the statement handle used to insert data into the %_content
   125951   ** table. The SQL for this statement is:
   125952   **
   125953   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   125954   **
   125955   ** The statement features N '?' variables, where N is the number of user
   125956   ** defined columns in the FTS3 table, plus one for the docid field.
   125957   */
   125958   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   125959   if( rc==SQLITE_OK && p->zLanguageid ){
   125960     rc = sqlite3_bind_int(
   125961         pContentInsert, p->nColumn+2,
   125962         sqlite3_value_int(apVal[p->nColumn+4])
   125963     );
   125964   }
   125965   if( rc!=SQLITE_OK ) return rc;
   125966 
   125967   /* There is a quirk here. The users INSERT statement may have specified
   125968   ** a value for the "rowid" field, for the "docid" field, or for both.
   125969   ** Which is a problem, since "rowid" and "docid" are aliases for the
   125970   ** same value. For example:
   125971   **
   125972   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   125973   **
   125974   ** In FTS3, this is an error. It is an error to specify non-NULL values
   125975   ** for both docid and some other rowid alias.
   125976   */
   125977   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   125978     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   125979      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   125980     ){
   125981       /* A rowid/docid conflict. */
   125982       return SQLITE_ERROR;
   125983     }
   125984     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   125985     if( rc!=SQLITE_OK ) return rc;
   125986   }
   125987 
   125988   /* Execute the statement to insert the record. Set *piDocid to the
   125989   ** new docid value.
   125990   */
   125991   sqlite3_step(pContentInsert);
   125992   rc = sqlite3_reset(pContentInsert);
   125993 
   125994   *piDocid = sqlite3_last_insert_rowid(p->db);
   125995   return rc;
   125996 }
   125997 
   125998 
   125999 
   126000 /*
   126001 ** Remove all data from the FTS3 table. Clear the hash table containing
   126002 ** pending terms.
   126003 */
   126004 static int fts3DeleteAll(Fts3Table *p, int bContent){
   126005   int rc = SQLITE_OK;             /* Return code */
   126006 
   126007   /* Discard the contents of the pending-terms hash table. */
   126008   sqlite3Fts3PendingTermsClear(p);
   126009 
   126010   /* Delete everything from the shadow tables. Except, leave %_content as
   126011   ** is if bContent is false.  */
   126012   assert( p->zContentTbl==0 || bContent==0 );
   126013   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   126014   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   126015   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   126016   if( p->bHasDocsize ){
   126017     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   126018   }
   126019   if( p->bHasStat ){
   126020     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   126021   }
   126022   return rc;
   126023 }
   126024 
   126025 /*
   126026 **
   126027 */
   126028 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
   126029   int iLangid = 0;
   126030   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
   126031   return iLangid;
   126032 }
   126033 
   126034 /*
   126035 ** The first element in the apVal[] array is assumed to contain the docid
   126036 ** (an integer) of a row about to be deleted. Remove all terms from the
   126037 ** full-text index.
   126038 */
   126039 static void fts3DeleteTerms(
   126040   int *pRC,               /* Result code */
   126041   Fts3Table *p,           /* The FTS table to delete from */
   126042   sqlite3_value *pRowid,  /* The docid to be deleted */
   126043   u32 *aSz                /* Sizes of deleted document written here */
   126044 ){
   126045   int rc;
   126046   sqlite3_stmt *pSelect;
   126047 
   126048   if( *pRC ) return;
   126049   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
   126050   if( rc==SQLITE_OK ){
   126051     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   126052       int i;
   126053       int iLangid = langidFromSelect(p, pSelect);
   126054       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
   126055       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
   126056         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   126057         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
   126058         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   126059       }
   126060       if( rc!=SQLITE_OK ){
   126061         sqlite3_reset(pSelect);
   126062         *pRC = rc;
   126063         return;
   126064       }
   126065     }
   126066     rc = sqlite3_reset(pSelect);
   126067   }else{
   126068     sqlite3_reset(pSelect);
   126069   }
   126070   *pRC = rc;
   126071 }
   126072 
   126073 /*
   126074 ** Forward declaration to account for the circular dependency between
   126075 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   126076 */
   126077 static int fts3SegmentMerge(Fts3Table *, int, int, int);
   126078 
   126079 /*
   126080 ** This function allocates a new level iLevel index in the segdir table.
   126081 ** Usually, indexes are allocated within a level sequentially starting
   126082 ** with 0, so the allocated index is one greater than the value returned
   126083 ** by:
   126084 **
   126085 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   126086 **
   126087 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   126088 ** level, they are merged into a single level (iLevel+1) segment and the
   126089 ** allocated index is 0.
   126090 **
   126091 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   126092 ** returned. Otherwise, an SQLite error code is returned.
   126093 */
   126094 static int fts3AllocateSegdirIdx(
   126095   Fts3Table *p,
   126096   int iLangid,                    /* Language id */
   126097   int iIndex,                     /* Index for p->aIndex */
   126098   int iLevel,
   126099   int *piIdx
   126100 ){
   126101   int rc;                         /* Return Code */
   126102   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   126103   int iNext = 0;                  /* Result of query pNextIdx */
   126104 
   126105   assert( iLangid>=0 );
   126106   assert( p->nIndex>=1 );
   126107 
   126108   /* Set variable iNext to the next available segdir index at level iLevel. */
   126109   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   126110   if( rc==SQLITE_OK ){
   126111     sqlite3_bind_int64(
   126112         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   126113     );
   126114     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   126115       iNext = sqlite3_column_int(pNextIdx, 0);
   126116     }
   126117     rc = sqlite3_reset(pNextIdx);
   126118   }
   126119 
   126120   if( rc==SQLITE_OK ){
   126121     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   126122     ** full, merge all segments in level iLevel into a single iLevel+1
   126123     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   126124     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   126125     */
   126126     if( iNext>=FTS3_MERGE_COUNT ){
   126127       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
   126128       *piIdx = 0;
   126129     }else{
   126130       *piIdx = iNext;
   126131     }
   126132   }
   126133 
   126134   return rc;
   126135 }
   126136 
   126137 /*
   126138 ** The %_segments table is declared as follows:
   126139 **
   126140 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   126141 **
   126142 ** This function reads data from a single row of the %_segments table. The
   126143 ** specific row is identified by the iBlockid parameter. If paBlob is not
   126144 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   126145 ** with the contents of the blob stored in the "block" column of the
   126146 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   126147 ** to the size of the blob in bytes before returning.
   126148 **
   126149 ** If an error occurs, or the table does not contain the specified row,
   126150 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   126151 ** paBlob is non-NULL, then it is the responsibility of the caller to
   126152 ** eventually free the returned buffer.
   126153 **
   126154 ** This function may leave an open sqlite3_blob* handle in the
   126155 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   126156 ** to this function. The handle may be closed by calling the
   126157 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   126158 ** performance improvement, but the blob handle should always be closed
   126159 ** before control is returned to the user (to prevent a lock being held
   126160 ** on the database file for longer than necessary). Thus, any virtual table
   126161 ** method (xFilter etc.) that may directly or indirectly call this function
   126162 ** must call sqlite3Fts3SegmentsClose() before returning.
   126163 */
   126164 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   126165   Fts3Table *p,                   /* FTS3 table handle */
   126166   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   126167   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   126168   int *pnBlob,                    /* OUT: Size of blob data */
   126169   int *pnLoad                     /* OUT: Bytes actually loaded */
   126170 ){
   126171   int rc;                         /* Return code */
   126172 
   126173   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   126174   assert( pnBlob);
   126175 
   126176   if( p->pSegments ){
   126177     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   126178   }else{
   126179     if( 0==p->zSegmentsTbl ){
   126180       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   126181       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   126182     }
   126183     rc = sqlite3_blob_open(
   126184        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   126185     );
   126186   }
   126187 
   126188   if( rc==SQLITE_OK ){
   126189     int nByte = sqlite3_blob_bytes(p->pSegments);
   126190     *pnBlob = nByte;
   126191     if( paBlob ){
   126192       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   126193       if( !aByte ){
   126194         rc = SQLITE_NOMEM;
   126195       }else{
   126196         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
   126197           nByte = FTS3_NODE_CHUNKSIZE;
   126198           *pnLoad = nByte;
   126199         }
   126200         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   126201         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   126202         if( rc!=SQLITE_OK ){
   126203           sqlite3_free(aByte);
   126204           aByte = 0;
   126205         }
   126206       }
   126207       *paBlob = aByte;
   126208     }
   126209   }
   126210 
   126211   return rc;
   126212 }
   126213 
   126214 /*
   126215 ** Close the blob handle at p->pSegments, if it is open. See comments above
   126216 ** the sqlite3Fts3ReadBlock() function for details.
   126217 */
   126218 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   126219   sqlite3_blob_close(p->pSegments);
   126220   p->pSegments = 0;
   126221 }
   126222 
   126223 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   126224   int nRead;                      /* Number of bytes to read */
   126225   int rc;                         /* Return code */
   126226 
   126227   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   126228   rc = sqlite3_blob_read(
   126229       pReader->pBlob,
   126230       &pReader->aNode[pReader->nPopulate],
   126231       nRead,
   126232       pReader->nPopulate
   126233   );
   126234 
   126235   if( rc==SQLITE_OK ){
   126236     pReader->nPopulate += nRead;
   126237     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
   126238     if( pReader->nPopulate==pReader->nNode ){
   126239       sqlite3_blob_close(pReader->pBlob);
   126240       pReader->pBlob = 0;
   126241       pReader->nPopulate = 0;
   126242     }
   126243   }
   126244   return rc;
   126245 }
   126246 
   126247 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   126248   int rc = SQLITE_OK;
   126249   assert( !pReader->pBlob
   126250        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   126251   );
   126252   while( pReader->pBlob && rc==SQLITE_OK
   126253      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   126254   ){
   126255     rc = fts3SegReaderIncrRead(pReader);
   126256   }
   126257   return rc;
   126258 }
   126259 
   126260 /*
   126261 ** Set an Fts3SegReader cursor to point at EOF.
   126262 */
   126263 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
   126264   if( !fts3SegReaderIsRootOnly(pSeg) ){
   126265     sqlite3_free(pSeg->aNode);
   126266     sqlite3_blob_close(pSeg->pBlob);
   126267     pSeg->pBlob = 0;
   126268   }
   126269   pSeg->aNode = 0;
   126270 }
   126271 
   126272 /*
   126273 ** Move the iterator passed as the first argument to the next term in the
   126274 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   126275 ** SQLITE_DONE. Otherwise, an SQLite error code.
   126276 */
   126277 static int fts3SegReaderNext(
   126278   Fts3Table *p,
   126279   Fts3SegReader *pReader,
   126280   int bIncr
   126281 ){
   126282   int rc;                         /* Return code of various sub-routines */
   126283   char *pNext;                    /* Cursor variable */
   126284   int nPrefix;                    /* Number of bytes in term prefix */
   126285   int nSuffix;                    /* Number of bytes in term suffix */
   126286 
   126287   if( !pReader->aDoclist ){
   126288     pNext = pReader->aNode;
   126289   }else{
   126290     pNext = &pReader->aDoclist[pReader->nDoclist];
   126291   }
   126292 
   126293   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   126294 
   126295     if( fts3SegReaderIsPending(pReader) ){
   126296       Fts3HashElem *pElem = *(pReader->ppNextElem);
   126297       if( pElem==0 ){
   126298         pReader->aNode = 0;
   126299       }else{
   126300         PendingList *pList = (PendingList *)fts3HashData(pElem);
   126301         pReader->zTerm = (char *)fts3HashKey(pElem);
   126302         pReader->nTerm = fts3HashKeysize(pElem);
   126303         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   126304         pReader->aNode = pReader->aDoclist = pList->aData;
   126305         pReader->ppNextElem++;
   126306         assert( pReader->aNode );
   126307       }
   126308       return SQLITE_OK;
   126309     }
   126310 
   126311     fts3SegReaderSetEof(pReader);
   126312 
   126313     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   126314     ** blocks have already been traversed.  */
   126315     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   126316     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   126317       return SQLITE_OK;
   126318     }
   126319 
   126320     rc = sqlite3Fts3ReadBlock(
   126321         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
   126322         (bIncr ? &pReader->nPopulate : 0)
   126323     );
   126324     if( rc!=SQLITE_OK ) return rc;
   126325     assert( pReader->pBlob==0 );
   126326     if( bIncr && pReader->nPopulate<pReader->nNode ){
   126327       pReader->pBlob = p->pSegments;
   126328       p->pSegments = 0;
   126329     }
   126330     pNext = pReader->aNode;
   126331   }
   126332 
   126333   assert( !fts3SegReaderIsPending(pReader) );
   126334 
   126335   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   126336   if( rc!=SQLITE_OK ) return rc;
   126337 
   126338   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   126339   ** safe (no risk of overread) even if the node data is corrupted. */
   126340   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
   126341   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
   126342   if( nPrefix<0 || nSuffix<=0
   126343    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   126344   ){
   126345     return FTS_CORRUPT_VTAB;
   126346   }
   126347 
   126348   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   126349     int nNew = (nPrefix+nSuffix)*2;
   126350     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   126351     if( !zNew ){
   126352       return SQLITE_NOMEM;
   126353     }
   126354     pReader->zTerm = zNew;
   126355     pReader->nTermAlloc = nNew;
   126356   }
   126357 
   126358   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
   126359   if( rc!=SQLITE_OK ) return rc;
   126360 
   126361   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   126362   pReader->nTerm = nPrefix+nSuffix;
   126363   pNext += nSuffix;
   126364   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
   126365   pReader->aDoclist = pNext;
   126366   pReader->pOffsetList = 0;
   126367 
   126368   /* Check that the doclist does not appear to extend past the end of the
   126369   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   126370   ** of these statements is untrue, then the data structure is corrupt.
   126371   */
   126372   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   126373    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
   126374   ){
   126375     return FTS_CORRUPT_VTAB;
   126376   }
   126377   return SQLITE_OK;
   126378 }
   126379 
   126380 /*
   126381 ** Set the SegReader to point to the first docid in the doclist associated
   126382 ** with the current term.
   126383 */
   126384 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
   126385   int rc = SQLITE_OK;
   126386   assert( pReader->aDoclist );
   126387   assert( !pReader->pOffsetList );
   126388   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   126389     u8 bEof = 0;
   126390     pReader->iDocid = 0;
   126391     pReader->nOffsetList = 0;
   126392     sqlite3Fts3DoclistPrev(0,
   126393         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
   126394         &pReader->iDocid, &pReader->nOffsetList, &bEof
   126395     );
   126396   }else{
   126397     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
   126398     if( rc==SQLITE_OK ){
   126399       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   126400       pReader->pOffsetList = &pReader->aDoclist[n];
   126401     }
   126402   }
   126403   return rc;
   126404 }
   126405 
   126406 /*
   126407 ** Advance the SegReader to point to the next docid in the doclist
   126408 ** associated with the current term.
   126409 **
   126410 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   126411 ** *ppOffsetList is set to point to the first column-offset list
   126412 ** in the doclist entry (i.e. immediately past the docid varint).
   126413 ** *pnOffsetList is set to the length of the set of column-offset
   126414 ** lists, not including the nul-terminator byte. For example:
   126415 */
   126416 static int fts3SegReaderNextDocid(
   126417   Fts3Table *pTab,
   126418   Fts3SegReader *pReader,         /* Reader to advance to next docid */
   126419   char **ppOffsetList,            /* OUT: Pointer to current position-list */
   126420   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
   126421 ){
   126422   int rc = SQLITE_OK;
   126423   char *p = pReader->pOffsetList;
   126424   char c = 0;
   126425 
   126426   assert( p );
   126427 
   126428   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
   126429     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
   126430     ** Pending-terms doclists are always built up in ascending order, so
   126431     ** we have to iterate through them backwards here. */
   126432     u8 bEof = 0;
   126433     if( ppOffsetList ){
   126434       *ppOffsetList = pReader->pOffsetList;
   126435       *pnOffsetList = pReader->nOffsetList - 1;
   126436     }
   126437     sqlite3Fts3DoclistPrev(0,
   126438         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
   126439         &pReader->nOffsetList, &bEof
   126440     );
   126441     if( bEof ){
   126442       pReader->pOffsetList = 0;
   126443     }else{
   126444       pReader->pOffsetList = p;
   126445     }
   126446   }else{
   126447     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
   126448 
   126449     /* Pointer p currently points at the first byte of an offset list. The
   126450     ** following block advances it to point one byte past the end of
   126451     ** the same offset list. */
   126452     while( 1 ){
   126453 
   126454       /* The following line of code (and the "p++" below the while() loop) is
   126455       ** normally all that is required to move pointer p to the desired
   126456       ** position. The exception is if this node is being loaded from disk
   126457       ** incrementally and pointer "p" now points to the first byte passed
   126458       ** the populated part of pReader->aNode[].
   126459       */
   126460       while( *p | c ) c = *p++ & 0x80;
   126461       assert( *p==0 );
   126462 
   126463       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
   126464       rc = fts3SegReaderIncrRead(pReader);
   126465       if( rc!=SQLITE_OK ) return rc;
   126466     }
   126467     p++;
   126468 
   126469     /* If required, populate the output variables with a pointer to and the
   126470     ** size of the previous offset-list.
   126471     */
   126472     if( ppOffsetList ){
   126473       *ppOffsetList = pReader->pOffsetList;
   126474       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   126475     }
   126476 
   126477     while( p<pEnd && *p==0 ) p++;
   126478 
   126479     /* If there are no more entries in the doclist, set pOffsetList to
   126480     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   126481     ** Fts3SegReader.pOffsetList to point to the next offset list before
   126482     ** returning.
   126483     */
   126484     if( p>=pEnd ){
   126485       pReader->pOffsetList = 0;
   126486     }else{
   126487       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
   126488       if( rc==SQLITE_OK ){
   126489         sqlite3_int64 iDelta;
   126490         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   126491         if( pTab->bDescIdx ){
   126492           pReader->iDocid -= iDelta;
   126493         }else{
   126494           pReader->iDocid += iDelta;
   126495         }
   126496       }
   126497     }
   126498   }
   126499 
   126500   return SQLITE_OK;
   126501 }
   126502 
   126503 
   126504 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
   126505   Fts3Cursor *pCsr,
   126506   Fts3MultiSegReader *pMsr,
   126507   int *pnOvfl
   126508 ){
   126509   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   126510   int nOvfl = 0;
   126511   int ii;
   126512   int rc = SQLITE_OK;
   126513   int pgsz = p->nPgsz;
   126514 
   126515   assert( p->bHasStat );
   126516   assert( pgsz>0 );
   126517 
   126518   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
   126519     Fts3SegReader *pReader = pMsr->apSegment[ii];
   126520     if( !fts3SegReaderIsPending(pReader)
   126521      && !fts3SegReaderIsRootOnly(pReader)
   126522     ){
   126523       sqlite3_int64 jj;
   126524       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
   126525         int nBlob;
   126526         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
   126527         if( rc!=SQLITE_OK ) break;
   126528         if( (nBlob+35)>pgsz ){
   126529           nOvfl += (nBlob + 34)/pgsz;
   126530         }
   126531       }
   126532     }
   126533   }
   126534   *pnOvfl = nOvfl;
   126535   return rc;
   126536 }
   126537 
   126538 /*
   126539 ** Free all allocations associated with the iterator passed as the
   126540 ** second argument.
   126541 */
   126542 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   126543   if( pReader && !fts3SegReaderIsPending(pReader) ){
   126544     sqlite3_free(pReader->zTerm);
   126545     if( !fts3SegReaderIsRootOnly(pReader) ){
   126546       sqlite3_free(pReader->aNode);
   126547       sqlite3_blob_close(pReader->pBlob);
   126548     }
   126549   }
   126550   sqlite3_free(pReader);
   126551 }
   126552 
   126553 /*
   126554 ** Allocate a new SegReader object.
   126555 */
   126556 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   126557   int iAge,                       /* Segment "age". */
   126558   int bLookup,                    /* True for a lookup only */
   126559   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   126560   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   126561   sqlite3_int64 iEndBlock,        /* Final block of segment */
   126562   const char *zRoot,              /* Buffer containing root node */
   126563   int nRoot,                      /* Size of buffer containing root node */
   126564   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   126565 ){
   126566   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   126567   int nExtra = 0;                 /* Bytes to allocate segment root node */
   126568 
   126569   assert( iStartLeaf<=iEndLeaf );
   126570   if( iStartLeaf==0 ){
   126571     nExtra = nRoot + FTS3_NODE_PADDING;
   126572   }
   126573 
   126574   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   126575   if( !pReader ){
   126576     return SQLITE_NOMEM;
   126577   }
   126578   memset(pReader, 0, sizeof(Fts3SegReader));
   126579   pReader->iIdx = iAge;
   126580   pReader->bLookup = bLookup;
   126581   pReader->iStartBlock = iStartLeaf;
   126582   pReader->iLeafEndBlock = iEndLeaf;
   126583   pReader->iEndBlock = iEndBlock;
   126584 
   126585   if( nExtra ){
   126586     /* The entire segment is stored in the root node. */
   126587     pReader->aNode = (char *)&pReader[1];
   126588     pReader->nNode = nRoot;
   126589     memcpy(pReader->aNode, zRoot, nRoot);
   126590     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   126591   }else{
   126592     pReader->iCurrentBlock = iStartLeaf-1;
   126593   }
   126594   *ppReader = pReader;
   126595   return SQLITE_OK;
   126596 }
   126597 
   126598 /*
   126599 ** This is a comparison function used as a qsort() callback when sorting
   126600 ** an array of pending terms by term. This occurs as part of flushing
   126601 ** the contents of the pending-terms hash table to the database.
   126602 */
   126603 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   126604   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   126605   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   126606   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   126607   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   126608 
   126609   int n = (n1<n2 ? n1 : n2);
   126610   int c = memcmp(z1, z2, n);
   126611   if( c==0 ){
   126612     c = n1 - n2;
   126613   }
   126614   return c;
   126615 }
   126616 
   126617 /*
   126618 ** This function is used to allocate an Fts3SegReader that iterates through
   126619 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   126620 **
   126621 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
   126622 ** through each term in the pending-terms table. Or, if isPrefixIter is
   126623 ** non-zero, it iterates through each term and its prefixes. For example, if
   126624 ** the pending terms hash table contains the terms "sqlite", "mysql" and
   126625 ** "firebird", then the iterator visits the following 'terms' (in the order
   126626 ** shown):
   126627 **
   126628 **   f fi fir fire fireb firebi firebir firebird
   126629 **   m my mys mysq mysql
   126630 **   s sq sql sqli sqlit sqlite
   126631 **
   126632 ** Whereas if isPrefixIter is zero, the terms visited are:
   126633 **
   126634 **   firebird mysql sqlite
   126635 */
   126636 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   126637   Fts3Table *p,                   /* Virtual table handle */
   126638   int iIndex,                     /* Index for p->aIndex */
   126639   const char *zTerm,              /* Term to search for */
   126640   int nTerm,                      /* Size of buffer zTerm */
   126641   int bPrefix,                    /* True for a prefix iterator */
   126642   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   126643 ){
   126644   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   126645   Fts3HashElem *pE;               /* Iterator variable */
   126646   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   126647   int nElem = 0;                  /* Size of array at aElem */
   126648   int rc = SQLITE_OK;             /* Return Code */
   126649   Fts3Hash *pHash;
   126650 
   126651   pHash = &p->aIndex[iIndex].hPending;
   126652   if( bPrefix ){
   126653     int nAlloc = 0;               /* Size of allocated array at aElem */
   126654 
   126655     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
   126656       char *zKey = (char *)fts3HashKey(pE);
   126657       int nKey = fts3HashKeysize(pE);
   126658       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   126659         if( nElem==nAlloc ){
   126660           Fts3HashElem **aElem2;
   126661           nAlloc += 16;
   126662           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   126663               aElem, nAlloc*sizeof(Fts3HashElem *)
   126664           );
   126665           if( !aElem2 ){
   126666             rc = SQLITE_NOMEM;
   126667             nElem = 0;
   126668             break;
   126669           }
   126670           aElem = aElem2;
   126671         }
   126672 
   126673         aElem[nElem++] = pE;
   126674       }
   126675     }
   126676 
   126677     /* If more than one term matches the prefix, sort the Fts3HashElem
   126678     ** objects in term order using qsort(). This uses the same comparison
   126679     ** callback as is used when flushing terms to disk.
   126680     */
   126681     if( nElem>1 ){
   126682       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   126683     }
   126684 
   126685   }else{
   126686     /* The query is a simple term lookup that matches at most one term in
   126687     ** the index. All that is required is a straight hash-lookup.
   126688     **
   126689     ** Because the stack address of pE may be accessed via the aElem pointer
   126690     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
   126691     ** within this entire function, not just this "else{...}" block.
   126692     */
   126693     pE = fts3HashFindElem(pHash, zTerm, nTerm);
   126694     if( pE ){
   126695       aElem = &pE;
   126696       nElem = 1;
   126697     }
   126698   }
   126699 
   126700   if( nElem>0 ){
   126701     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   126702     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   126703     if( !pReader ){
   126704       rc = SQLITE_NOMEM;
   126705     }else{
   126706       memset(pReader, 0, nByte);
   126707       pReader->iIdx = 0x7FFFFFFF;
   126708       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   126709       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   126710     }
   126711   }
   126712 
   126713   if( bPrefix ){
   126714     sqlite3_free(aElem);
   126715   }
   126716   *ppReader = pReader;
   126717   return rc;
   126718 }
   126719 
   126720 /*
   126721 ** Compare the entries pointed to by two Fts3SegReader structures.
   126722 ** Comparison is as follows:
   126723 **
   126724 **   1) EOF is greater than not EOF.
   126725 **
   126726 **   2) The current terms (if any) are compared using memcmp(). If one
   126727 **      term is a prefix of another, the longer term is considered the
   126728 **      larger.
   126729 **
   126730 **   3) By segment age. An older segment is considered larger.
   126731 */
   126732 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126733   int rc;
   126734   if( pLhs->aNode && pRhs->aNode ){
   126735     int rc2 = pLhs->nTerm - pRhs->nTerm;
   126736     if( rc2<0 ){
   126737       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   126738     }else{
   126739       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   126740     }
   126741     if( rc==0 ){
   126742       rc = rc2;
   126743     }
   126744   }else{
   126745     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   126746   }
   126747   if( rc==0 ){
   126748     rc = pRhs->iIdx - pLhs->iIdx;
   126749   }
   126750   assert( rc!=0 );
   126751   return rc;
   126752 }
   126753 
   126754 /*
   126755 ** A different comparison function for SegReader structures. In this
   126756 ** version, it is assumed that each SegReader points to an entry in
   126757 ** a doclist for identical terms. Comparison is made as follows:
   126758 **
   126759 **   1) EOF (end of doclist in this case) is greater than not EOF.
   126760 **
   126761 **   2) By current docid.
   126762 **
   126763 **   3) By segment age. An older segment is considered larger.
   126764 */
   126765 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126766   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   126767   if( rc==0 ){
   126768     if( pLhs->iDocid==pRhs->iDocid ){
   126769       rc = pRhs->iIdx - pLhs->iIdx;
   126770     }else{
   126771       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   126772     }
   126773   }
   126774   assert( pLhs->aNode && pRhs->aNode );
   126775   return rc;
   126776 }
   126777 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   126778   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   126779   if( rc==0 ){
   126780     if( pLhs->iDocid==pRhs->iDocid ){
   126781       rc = pRhs->iIdx - pLhs->iIdx;
   126782     }else{
   126783       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
   126784     }
   126785   }
   126786   assert( pLhs->aNode && pRhs->aNode );
   126787   return rc;
   126788 }
   126789 
   126790 /*
   126791 ** Compare the term that the Fts3SegReader object passed as the first argument
   126792 ** points to with the term specified by arguments zTerm and nTerm.
   126793 **
   126794 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   126795 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   126796 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   126797 */
   126798 static int fts3SegReaderTermCmp(
   126799   Fts3SegReader *pSeg,            /* Segment reader object */
   126800   const char *zTerm,              /* Term to compare to */
   126801   int nTerm                       /* Size of term zTerm in bytes */
   126802 ){
   126803   int res = 0;
   126804   if( pSeg->aNode ){
   126805     if( pSeg->nTerm>nTerm ){
   126806       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   126807     }else{
   126808       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   126809     }
   126810     if( res==0 ){
   126811       res = pSeg->nTerm-nTerm;
   126812     }
   126813   }
   126814   return res;
   126815 }
   126816 
   126817 /*
   126818 ** Argument apSegment is an array of nSegment elements. It is known that
   126819 ** the final (nSegment-nSuspect) members are already in sorted order
   126820 ** (according to the comparison function provided). This function shuffles
   126821 ** the array around until all entries are in sorted order.
   126822 */
   126823 static void fts3SegReaderSort(
   126824   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   126825   int nSegment,                                  /* Size of apSegment array */
   126826   int nSuspect,                                  /* Unsorted entry count */
   126827   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   126828 ){
   126829   int i;                          /* Iterator variable */
   126830 
   126831   assert( nSuspect<=nSegment );
   126832 
   126833   if( nSuspect==nSegment ) nSuspect--;
   126834   for(i=nSuspect-1; i>=0; i--){
   126835     int j;
   126836     for(j=i; j<(nSegment-1); j++){
   126837       Fts3SegReader *pTmp;
   126838       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   126839       pTmp = apSegment[j+1];
   126840       apSegment[j+1] = apSegment[j];
   126841       apSegment[j] = pTmp;
   126842     }
   126843   }
   126844 
   126845 #ifndef NDEBUG
   126846   /* Check that the list really is sorted now. */
   126847   for(i=0; i<(nSuspect-1); i++){
   126848     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   126849   }
   126850 #endif
   126851 }
   126852 
   126853 /*
   126854 ** Insert a record into the %_segments table.
   126855 */
   126856 static int fts3WriteSegment(
   126857   Fts3Table *p,                   /* Virtual table handle */
   126858   sqlite3_int64 iBlock,           /* Block id for new block */
   126859   char *z,                        /* Pointer to buffer containing block data */
   126860   int n                           /* Size of buffer z in bytes */
   126861 ){
   126862   sqlite3_stmt *pStmt;
   126863   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   126864   if( rc==SQLITE_OK ){
   126865     sqlite3_bind_int64(pStmt, 1, iBlock);
   126866     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   126867     sqlite3_step(pStmt);
   126868     rc = sqlite3_reset(pStmt);
   126869   }
   126870   return rc;
   126871 }
   126872 
   126873 /*
   126874 ** Insert a record into the %_segdir table.
   126875 */
   126876 static int fts3WriteSegdir(
   126877   Fts3Table *p,                   /* Virtual table handle */
   126878   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
   126879   int iIdx,                       /* Value for "idx" field */
   126880   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   126881   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   126882   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   126883   char *zRoot,                    /* Blob value for "root" field */
   126884   int nRoot                       /* Number of bytes in buffer zRoot */
   126885 ){
   126886   sqlite3_stmt *pStmt;
   126887   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   126888   if( rc==SQLITE_OK ){
   126889     sqlite3_bind_int64(pStmt, 1, iLevel);
   126890     sqlite3_bind_int(pStmt, 2, iIdx);
   126891     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   126892     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   126893     sqlite3_bind_int64(pStmt, 5, iEndBlock);
   126894     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   126895     sqlite3_step(pStmt);
   126896     rc = sqlite3_reset(pStmt);
   126897   }
   126898   return rc;
   126899 }
   126900 
   126901 /*
   126902 ** Return the size of the common prefix (if any) shared by zPrev and
   126903 ** zNext, in bytes. For example,
   126904 **
   126905 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   126906 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   126907 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   126908 */
   126909 static int fts3PrefixCompress(
   126910   const char *zPrev,              /* Buffer containing previous term */
   126911   int nPrev,                      /* Size of buffer zPrev in bytes */
   126912   const char *zNext,              /* Buffer containing next term */
   126913   int nNext                       /* Size of buffer zNext in bytes */
   126914 ){
   126915   int n;
   126916   UNUSED_PARAMETER(nNext);
   126917   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   126918   return n;
   126919 }
   126920 
   126921 /*
   126922 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   126923 ** (according to memcmp) than the previous term.
   126924 */
   126925 static int fts3NodeAddTerm(
   126926   Fts3Table *p,                   /* Virtual table handle */
   126927   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   126928   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   126929   const char *zTerm,              /* Pointer to buffer containing term */
   126930   int nTerm                       /* Size of term in bytes */
   126931 ){
   126932   SegmentNode *pTree = *ppTree;
   126933   int rc;
   126934   SegmentNode *pNew;
   126935 
   126936   /* First try to append the term to the current node. Return early if
   126937   ** this is possible.
   126938   */
   126939   if( pTree ){
   126940     int nData = pTree->nData;     /* Current size of node in bytes */
   126941     int nReq = nData;             /* Required space after adding zTerm */
   126942     int nPrefix;                  /* Number of bytes of prefix compression */
   126943     int nSuffix;                  /* Suffix length */
   126944 
   126945     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   126946     nSuffix = nTerm-nPrefix;
   126947 
   126948     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   126949     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   126950 
   126951       if( nReq>p->nNodeSize ){
   126952         /* An unusual case: this is the first term to be added to the node
   126953         ** and the static node buffer (p->nNodeSize bytes) is not large
   126954         ** enough. Use a separately malloced buffer instead This wastes
   126955         ** p->nNodeSize bytes, but since this scenario only comes about when
   126956         ** the database contain two terms that share a prefix of almost 2KB,
   126957         ** this is not expected to be a serious problem.
   126958         */
   126959         assert( pTree->aData==(char *)&pTree[1] );
   126960         pTree->aData = (char *)sqlite3_malloc(nReq);
   126961         if( !pTree->aData ){
   126962           return SQLITE_NOMEM;
   126963         }
   126964       }
   126965 
   126966       if( pTree->zTerm ){
   126967         /* There is no prefix-length field for first term in a node */
   126968         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   126969       }
   126970 
   126971       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   126972       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   126973       pTree->nData = nData + nSuffix;
   126974       pTree->nEntry++;
   126975 
   126976       if( isCopyTerm ){
   126977         if( pTree->nMalloc<nTerm ){
   126978           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   126979           if( !zNew ){
   126980             return SQLITE_NOMEM;
   126981           }
   126982           pTree->nMalloc = nTerm*2;
   126983           pTree->zMalloc = zNew;
   126984         }
   126985         pTree->zTerm = pTree->zMalloc;
   126986         memcpy(pTree->zTerm, zTerm, nTerm);
   126987         pTree->nTerm = nTerm;
   126988       }else{
   126989         pTree->zTerm = (char *)zTerm;
   126990         pTree->nTerm = nTerm;
   126991       }
   126992       return SQLITE_OK;
   126993     }
   126994   }
   126995 
   126996   /* If control flows to here, it was not possible to append zTerm to the
   126997   ** current node. Create a new node (a right-sibling of the current node).
   126998   ** If this is the first node in the tree, the term is added to it.
   126999   **
   127000   ** Otherwise, the term is not added to the new node, it is left empty for
   127001   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   127002   ** has no parent, one is created here.
   127003   */
   127004   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   127005   if( !pNew ){
   127006     return SQLITE_NOMEM;
   127007   }
   127008   memset(pNew, 0, sizeof(SegmentNode));
   127009   pNew->nData = 1 + FTS3_VARINT_MAX;
   127010   pNew->aData = (char *)&pNew[1];
   127011 
   127012   if( pTree ){
   127013     SegmentNode *pParent = pTree->pParent;
   127014     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   127015     if( pTree->pParent==0 ){
   127016       pTree->pParent = pParent;
   127017     }
   127018     pTree->pRight = pNew;
   127019     pNew->pLeftmost = pTree->pLeftmost;
   127020     pNew->pParent = pParent;
   127021     pNew->zMalloc = pTree->zMalloc;
   127022     pNew->nMalloc = pTree->nMalloc;
   127023     pTree->zMalloc = 0;
   127024   }else{
   127025     pNew->pLeftmost = pNew;
   127026     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   127027   }
   127028 
   127029   *ppTree = pNew;
   127030   return rc;
   127031 }
   127032 
   127033 /*
   127034 ** Helper function for fts3NodeWrite().
   127035 */
   127036 static int fts3TreeFinishNode(
   127037   SegmentNode *pTree,
   127038   int iHeight,
   127039   sqlite3_int64 iLeftChild
   127040 ){
   127041   int nStart;
   127042   assert( iHeight>=1 && iHeight<128 );
   127043   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   127044   pTree->aData[nStart] = (char)iHeight;
   127045   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   127046   return nStart;
   127047 }
   127048 
   127049 /*
   127050 ** Write the buffer for the segment node pTree and all of its peers to the
   127051 ** database. Then call this function recursively to write the parent of
   127052 ** pTree and its peers to the database.
   127053 **
   127054 ** Except, if pTree is a root node, do not write it to the database. Instead,
   127055 ** set output variables *paRoot and *pnRoot to contain the root node.
   127056 **
   127057 ** If successful, SQLITE_OK is returned and output variable *piLast is
   127058 ** set to the largest blockid written to the database (or zero if no
   127059 ** blocks were written to the db). Otherwise, an SQLite error code is
   127060 ** returned.
   127061 */
   127062 static int fts3NodeWrite(
   127063   Fts3Table *p,                   /* Virtual table handle */
   127064   SegmentNode *pTree,             /* SegmentNode handle */
   127065   int iHeight,                    /* Height of this node in tree */
   127066   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   127067   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   127068   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   127069   char **paRoot,                  /* OUT: Data for root node */
   127070   int *pnRoot                     /* OUT: Size of root node in bytes */
   127071 ){
   127072   int rc = SQLITE_OK;
   127073 
   127074   if( !pTree->pParent ){
   127075     /* Root node of the tree. */
   127076     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   127077     *piLast = iFree-1;
   127078     *pnRoot = pTree->nData - nStart;
   127079     *paRoot = &pTree->aData[nStart];
   127080   }else{
   127081     SegmentNode *pIter;
   127082     sqlite3_int64 iNextFree = iFree;
   127083     sqlite3_int64 iNextLeaf = iLeaf;
   127084     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   127085       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   127086       int nWrite = pIter->nData - nStart;
   127087 
   127088       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   127089       iNextFree++;
   127090       iNextLeaf += (pIter->nEntry+1);
   127091     }
   127092     if( rc==SQLITE_OK ){
   127093       assert( iNextLeaf==iFree );
   127094       rc = fts3NodeWrite(
   127095           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   127096       );
   127097     }
   127098   }
   127099 
   127100   return rc;
   127101 }
   127102 
   127103 /*
   127104 ** Free all memory allocations associated with the tree pTree.
   127105 */
   127106 static void fts3NodeFree(SegmentNode *pTree){
   127107   if( pTree ){
   127108     SegmentNode *p = pTree->pLeftmost;
   127109     fts3NodeFree(p->pParent);
   127110     while( p ){
   127111       SegmentNode *pRight = p->pRight;
   127112       if( p->aData!=(char *)&p[1] ){
   127113         sqlite3_free(p->aData);
   127114       }
   127115       assert( pRight==0 || p->zMalloc==0 );
   127116       sqlite3_free(p->zMalloc);
   127117       sqlite3_free(p);
   127118       p = pRight;
   127119     }
   127120   }
   127121 }
   127122 
   127123 /*
   127124 ** Add a term to the segment being constructed by the SegmentWriter object
   127125 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   127126 ** be passed NULL. This function will allocate a new SegmentWriter object
   127127 ** and return it via the input/output variable *ppWriter in this case.
   127128 **
   127129 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   127130 */
   127131 static int fts3SegWriterAdd(
   127132   Fts3Table *p,                   /* Virtual table handle */
   127133   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   127134   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   127135   const char *zTerm,              /* Pointer to buffer containing term */
   127136   int nTerm,                      /* Size of term in bytes */
   127137   const char *aDoclist,           /* Pointer to buffer containing doclist */
   127138   int nDoclist                    /* Size of doclist in bytes */
   127139 ){
   127140   int nPrefix;                    /* Size of term prefix in bytes */
   127141   int nSuffix;                    /* Size of term suffix in bytes */
   127142   int nReq;                       /* Number of bytes required on leaf page */
   127143   int nData;
   127144   SegmentWriter *pWriter = *ppWriter;
   127145 
   127146   if( !pWriter ){
   127147     int rc;
   127148     sqlite3_stmt *pStmt;
   127149 
   127150     /* Allocate the SegmentWriter structure */
   127151     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   127152     if( !pWriter ) return SQLITE_NOMEM;
   127153     memset(pWriter, 0, sizeof(SegmentWriter));
   127154     *ppWriter = pWriter;
   127155 
   127156     /* Allocate a buffer in which to accumulate data */
   127157     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   127158     if( !pWriter->aData ) return SQLITE_NOMEM;
   127159     pWriter->nSize = p->nNodeSize;
   127160 
   127161     /* Find the next free blockid in the %_segments table */
   127162     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   127163     if( rc!=SQLITE_OK ) return rc;
   127164     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127165       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   127166       pWriter->iFirst = pWriter->iFree;
   127167     }
   127168     rc = sqlite3_reset(pStmt);
   127169     if( rc!=SQLITE_OK ) return rc;
   127170   }
   127171   nData = pWriter->nData;
   127172 
   127173   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   127174   nSuffix = nTerm-nPrefix;
   127175 
   127176   /* Figure out how many bytes are required by this new entry */
   127177   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   127178     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   127179     nSuffix +                               /* Term suffix */
   127180     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   127181     nDoclist;                               /* Doclist data */
   127182 
   127183   if( nData>0 && nData+nReq>p->nNodeSize ){
   127184     int rc;
   127185 
   127186     /* The current leaf node is full. Write it out to the database. */
   127187     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   127188     if( rc!=SQLITE_OK ) return rc;
   127189 
   127190     /* Add the current term to the interior node tree. The term added to
   127191     ** the interior tree must:
   127192     **
   127193     **   a) be greater than the largest term on the leaf node just written
   127194     **      to the database (still available in pWriter->zTerm), and
   127195     **
   127196     **   b) be less than or equal to the term about to be added to the new
   127197     **      leaf node (zTerm/nTerm).
   127198     **
   127199     ** In other words, it must be the prefix of zTerm 1 byte longer than
   127200     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   127201     */
   127202     assert( nPrefix<nTerm );
   127203     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   127204     if( rc!=SQLITE_OK ) return rc;
   127205 
   127206     nData = 0;
   127207     pWriter->nTerm = 0;
   127208 
   127209     nPrefix = 0;
   127210     nSuffix = nTerm;
   127211     nReq = 1 +                              /* varint containing prefix size */
   127212       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   127213       nTerm +                               /* Term suffix */
   127214       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   127215       nDoclist;                             /* Doclist data */
   127216   }
   127217 
   127218   /* If the buffer currently allocated is too small for this entry, realloc
   127219   ** the buffer to make it large enough.
   127220   */
   127221   if( nReq>pWriter->nSize ){
   127222     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   127223     if( !aNew ) return SQLITE_NOMEM;
   127224     pWriter->aData = aNew;
   127225     pWriter->nSize = nReq;
   127226   }
   127227   assert( nData+nReq<=pWriter->nSize );
   127228 
   127229   /* Append the prefix-compressed term and doclist to the buffer. */
   127230   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   127231   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   127232   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   127233   nData += nSuffix;
   127234   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   127235   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   127236   pWriter->nData = nData + nDoclist;
   127237 
   127238   /* Save the current term so that it can be used to prefix-compress the next.
   127239   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   127240   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   127241   ** store a copy of the pointer.
   127242   */
   127243   if( isCopyTerm ){
   127244     if( nTerm>pWriter->nMalloc ){
   127245       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   127246       if( !zNew ){
   127247         return SQLITE_NOMEM;
   127248       }
   127249       pWriter->nMalloc = nTerm*2;
   127250       pWriter->zMalloc = zNew;
   127251       pWriter->zTerm = zNew;
   127252     }
   127253     assert( pWriter->zTerm==pWriter->zMalloc );
   127254     memcpy(pWriter->zTerm, zTerm, nTerm);
   127255   }else{
   127256     pWriter->zTerm = (char *)zTerm;
   127257   }
   127258   pWriter->nTerm = nTerm;
   127259 
   127260   return SQLITE_OK;
   127261 }
   127262 
   127263 /*
   127264 ** Flush all data associated with the SegmentWriter object pWriter to the
   127265 ** database. This function must be called after all terms have been added
   127266 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   127267 ** returned. Otherwise, an SQLite error code.
   127268 */
   127269 static int fts3SegWriterFlush(
   127270   Fts3Table *p,                   /* Virtual table handle */
   127271   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   127272   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
   127273   int iIdx                        /* Value for 'idx' column of %_segdir */
   127274 ){
   127275   int rc;                         /* Return code */
   127276   if( pWriter->pTree ){
   127277     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   127278     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   127279     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   127280     int nRoot = 0;                /* Size of buffer zRoot */
   127281 
   127282     iLastLeaf = pWriter->iFree;
   127283     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   127284     if( rc==SQLITE_OK ){
   127285       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   127286           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   127287     }
   127288     if( rc==SQLITE_OK ){
   127289       rc = fts3WriteSegdir(
   127290           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
   127291     }
   127292   }else{
   127293     /* The entire tree fits on the root node. Write it to the segdir table. */
   127294     rc = fts3WriteSegdir(
   127295         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
   127296   }
   127297   return rc;
   127298 }
   127299 
   127300 /*
   127301 ** Release all memory held by the SegmentWriter object passed as the
   127302 ** first argument.
   127303 */
   127304 static void fts3SegWriterFree(SegmentWriter *pWriter){
   127305   if( pWriter ){
   127306     sqlite3_free(pWriter->aData);
   127307     sqlite3_free(pWriter->zMalloc);
   127308     fts3NodeFree(pWriter->pTree);
   127309     sqlite3_free(pWriter);
   127310   }
   127311 }
   127312 
   127313 /*
   127314 ** The first value in the apVal[] array is assumed to contain an integer.
   127315 ** This function tests if there exist any documents with docid values that
   127316 ** are different from that integer. i.e. if deleting the document with docid
   127317 ** pRowid would mean the FTS3 table were empty.
   127318 **
   127319 ** If successful, *pisEmpty is set to true if the table is empty except for
   127320 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
   127321 ** error occurs, an SQLite error code is returned.
   127322 */
   127323 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
   127324   sqlite3_stmt *pStmt;
   127325   int rc;
   127326   if( p->zContentTbl ){
   127327     /* If using the content=xxx option, assume the table is never empty */
   127328     *pisEmpty = 0;
   127329     rc = SQLITE_OK;
   127330   }else{
   127331     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
   127332     if( rc==SQLITE_OK ){
   127333       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127334         *pisEmpty = sqlite3_column_int(pStmt, 0);
   127335       }
   127336       rc = sqlite3_reset(pStmt);
   127337     }
   127338   }
   127339   return rc;
   127340 }
   127341 
   127342 /*
   127343 ** Set *pnMax to the largest segment level in the database for the index
   127344 ** iIndex.
   127345 **
   127346 ** Segment levels are stored in the 'level' column of the %_segdir table.
   127347 **
   127348 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   127349 */
   127350 static int fts3SegmentMaxLevel(
   127351   Fts3Table *p,
   127352   int iLangid,
   127353   int iIndex,
   127354   sqlite3_int64 *pnMax
   127355 ){
   127356   sqlite3_stmt *pStmt;
   127357   int rc;
   127358   assert( iIndex>=0 && iIndex<p->nIndex );
   127359 
   127360   /* Set pStmt to the compiled version of:
   127361   **
   127362   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
   127363   **
   127364   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
   127365   */
   127366   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   127367   if( rc!=SQLITE_OK ) return rc;
   127368   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   127369   sqlite3_bind_int64(pStmt, 2,
   127370       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   127371   );
   127372   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   127373     *pnMax = sqlite3_column_int64(pStmt, 0);
   127374   }
   127375   return sqlite3_reset(pStmt);
   127376 }
   127377 
   127378 /*
   127379 ** This function is used after merging multiple segments into a single large
   127380 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   127381 ** it:
   127382 **
   127383 **   1) Deletes all %_segments entries for the segments associated with
   127384 **      each of the SegReader objects in the array passed as the third
   127385 **      argument, and
   127386 **
   127387 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   127388 **      entries regardless of level if (iLevel<0).
   127389 **
   127390 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   127391 */
   127392 static int fts3DeleteSegdir(
   127393   Fts3Table *p,                   /* Virtual table handle */
   127394   int iLangid,                    /* Language id */
   127395   int iIndex,                     /* Index for p->aIndex */
   127396   int iLevel,                     /* Level of %_segdir entries to delete */
   127397   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   127398   int nReader                     /* Size of array apSegment */
   127399 ){
   127400   int rc;                         /* Return Code */
   127401   int i;                          /* Iterator variable */
   127402   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
   127403 
   127404   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   127405   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   127406     Fts3SegReader *pSegment = apSegment[i];
   127407     if( pSegment->iStartBlock ){
   127408       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
   127409       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
   127410       sqlite3_step(pDelete);
   127411       rc = sqlite3_reset(pDelete);
   127412     }
   127413   }
   127414   if( rc!=SQLITE_OK ){
   127415     return rc;
   127416   }
   127417 
   127418   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
   127419   if( iLevel==FTS3_SEGCURSOR_ALL ){
   127420     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
   127421     if( rc==SQLITE_OK ){
   127422       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
   127423       sqlite3_bind_int64(pDelete, 2,
   127424           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   127425       );
   127426     }
   127427   }else{
   127428     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
   127429     if( rc==SQLITE_OK ){
   127430       sqlite3_bind_int64(
   127431           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
   127432       );
   127433     }
   127434   }
   127435 
   127436   if( rc==SQLITE_OK ){
   127437     sqlite3_step(pDelete);
   127438     rc = sqlite3_reset(pDelete);
   127439   }
   127440 
   127441   return rc;
   127442 }
   127443 
   127444 /*
   127445 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   127446 ** a position list that may (or may not) feature multiple columns. This
   127447 ** function adjusts the pointer *ppList and the length *pnList so that they
   127448 ** identify the subset of the position list that corresponds to column iCol.
   127449 **
   127450 ** If there are no entries in the input position list for column iCol, then
   127451 ** *pnList is set to zero before returning.
   127452 */
   127453 static void fts3ColumnFilter(
   127454   int iCol,                       /* Column to filter on */
   127455   char **ppList,                  /* IN/OUT: Pointer to position list */
   127456   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   127457 ){
   127458   char *pList = *ppList;
   127459   int nList = *pnList;
   127460   char *pEnd = &pList[nList];
   127461   int iCurrent = 0;
   127462   char *p = pList;
   127463 
   127464   assert( iCol>=0 );
   127465   while( 1 ){
   127466     char c = 0;
   127467     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   127468 
   127469     if( iCol==iCurrent ){
   127470       nList = (int)(p - pList);
   127471       break;
   127472     }
   127473 
   127474     nList -= (int)(p - pList);
   127475     pList = p;
   127476     if( nList==0 ){
   127477       break;
   127478     }
   127479     p = &pList[1];
   127480     p += sqlite3Fts3GetVarint32(p, &iCurrent);
   127481   }
   127482 
   127483   *ppList = pList;
   127484   *pnList = nList;
   127485 }
   127486 
   127487 /*
   127488 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
   127489 ** existing data). Grow the buffer if required.
   127490 **
   127491 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
   127492 ** trying to resize the buffer, return SQLITE_NOMEM.
   127493 */
   127494 static int fts3MsrBufferData(
   127495   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   127496   char *pList,
   127497   int nList
   127498 ){
   127499   if( nList>pMsr->nBuffer ){
   127500     char *pNew;
   127501     pMsr->nBuffer = nList*2;
   127502     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
   127503     if( !pNew ) return SQLITE_NOMEM;
   127504     pMsr->aBuffer = pNew;
   127505   }
   127506 
   127507   memcpy(pMsr->aBuffer, pList, nList);
   127508   return SQLITE_OK;
   127509 }
   127510 
   127511 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
   127512   Fts3Table *p,                   /* Virtual table handle */
   127513   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
   127514   sqlite3_int64 *piDocid,         /* OUT: Docid value */
   127515   char **paPoslist,               /* OUT: Pointer to position list */
   127516   int *pnPoslist                  /* OUT: Size of position list in bytes */
   127517 ){
   127518   int nMerge = pMsr->nAdvance;
   127519   Fts3SegReader **apSegment = pMsr->apSegment;
   127520   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127521     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127522   );
   127523 
   127524   if( nMerge==0 ){
   127525     *paPoslist = 0;
   127526     return SQLITE_OK;
   127527   }
   127528 
   127529   while( 1 ){
   127530     Fts3SegReader *pSeg;
   127531     pSeg = pMsr->apSegment[0];
   127532 
   127533     if( pSeg->pOffsetList==0 ){
   127534       *paPoslist = 0;
   127535       break;
   127536     }else{
   127537       int rc;
   127538       char *pList;
   127539       int nList;
   127540       int j;
   127541       sqlite3_int64 iDocid = apSegment[0]->iDocid;
   127542 
   127543       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   127544       j = 1;
   127545       while( rc==SQLITE_OK
   127546         && j<nMerge
   127547         && apSegment[j]->pOffsetList
   127548         && apSegment[j]->iDocid==iDocid
   127549       ){
   127550         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   127551         j++;
   127552       }
   127553       if( rc!=SQLITE_OK ) return rc;
   127554       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
   127555 
   127556       if( pMsr->iColFilter>=0 ){
   127557         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
   127558       }
   127559 
   127560       if( nList>0 ){
   127561         if( fts3SegReaderIsPending(apSegment[0]) ){
   127562           rc = fts3MsrBufferData(pMsr, pList, nList+1);
   127563           if( rc!=SQLITE_OK ) return rc;
   127564           *paPoslist = pMsr->aBuffer;
   127565           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
   127566         }else{
   127567           *paPoslist = pList;
   127568         }
   127569         *piDocid = iDocid;
   127570         *pnPoslist = nList;
   127571         break;
   127572       }
   127573     }
   127574   }
   127575 
   127576   return SQLITE_OK;
   127577 }
   127578 
   127579 static int fts3SegReaderStart(
   127580   Fts3Table *p,                   /* Virtual table handle */
   127581   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127582   const char *zTerm,              /* Term searched for (or NULL) */
   127583   int nTerm                       /* Length of zTerm in bytes */
   127584 ){
   127585   int i;
   127586   int nSeg = pCsr->nSegment;
   127587 
   127588   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   127589   ** for, then advance each segment iterator until it points to a term of
   127590   ** equal or greater value than the specified term. This prevents many
   127591   ** unnecessary merge/sort operations for the case where single segment
   127592   ** b-tree leaf nodes contain more than one term.
   127593   */
   127594   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
   127595     int res = 0;
   127596     Fts3SegReader *pSeg = pCsr->apSegment[i];
   127597     do {
   127598       int rc = fts3SegReaderNext(p, pSeg, 0);
   127599       if( rc!=SQLITE_OK ) return rc;
   127600     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
   127601 
   127602     if( pSeg->bLookup && res!=0 ){
   127603       fts3SegReaderSetEof(pSeg);
   127604     }
   127605   }
   127606   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
   127607 
   127608   return SQLITE_OK;
   127609 }
   127610 
   127611 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
   127612   Fts3Table *p,                   /* Virtual table handle */
   127613   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127614   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
   127615 ){
   127616   pCsr->pFilter = pFilter;
   127617   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
   127618 }
   127619 
   127620 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
   127621   Fts3Table *p,                   /* Virtual table handle */
   127622   Fts3MultiSegReader *pCsr,       /* Cursor object */
   127623   int iCol,                       /* Column to match on. */
   127624   const char *zTerm,              /* Term to iterate through a doclist for */
   127625   int nTerm                       /* Number of bytes in zTerm */
   127626 ){
   127627   int i;
   127628   int rc;
   127629   int nSegment = pCsr->nSegment;
   127630   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127631     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127632   );
   127633 
   127634   assert( pCsr->pFilter==0 );
   127635   assert( zTerm && nTerm>0 );
   127636 
   127637   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
   127638   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
   127639   if( rc!=SQLITE_OK ) return rc;
   127640 
   127641   /* Determine how many of the segments actually point to zTerm/nTerm. */
   127642   for(i=0; i<nSegment; i++){
   127643     Fts3SegReader *pSeg = pCsr->apSegment[i];
   127644     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
   127645       break;
   127646     }
   127647   }
   127648   pCsr->nAdvance = i;
   127649 
   127650   /* Advance each of the segments to point to the first docid. */
   127651   for(i=0; i<pCsr->nAdvance; i++){
   127652     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
   127653     if( rc!=SQLITE_OK ) return rc;
   127654   }
   127655   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
   127656 
   127657   assert( iCol<0 || iCol<p->nColumn );
   127658   pCsr->iColFilter = iCol;
   127659 
   127660   return SQLITE_OK;
   127661 }
   127662 
   127663 /*
   127664 ** This function is called on a MultiSegReader that has been started using
   127665 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
   127666 ** have been made. Calling this function puts the MultiSegReader in such
   127667 ** a state that if the next two calls are:
   127668 **
   127669 **   sqlite3Fts3SegReaderStart()
   127670 **   sqlite3Fts3SegReaderStep()
   127671 **
   127672 ** then the entire doclist for the term is available in
   127673 ** MultiSegReader.aDoclist/nDoclist.
   127674 */
   127675 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   127676   int i;                          /* Used to iterate through segment-readers */
   127677 
   127678   assert( pCsr->zTerm==0 );
   127679   assert( pCsr->nTerm==0 );
   127680   assert( pCsr->aDoclist==0 );
   127681   assert( pCsr->nDoclist==0 );
   127682 
   127683   pCsr->nAdvance = 0;
   127684   pCsr->bRestart = 1;
   127685   for(i=0; i<pCsr->nSegment; i++){
   127686     pCsr->apSegment[i]->pOffsetList = 0;
   127687     pCsr->apSegment[i]->nOffsetList = 0;
   127688     pCsr->apSegment[i]->iDocid = 0;
   127689   }
   127690 
   127691   return SQLITE_OK;
   127692 }
   127693 
   127694 
   127695 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   127696   Fts3Table *p,                   /* Virtual table handle */
   127697   Fts3MultiSegReader *pCsr        /* Cursor object */
   127698 ){
   127699   int rc = SQLITE_OK;
   127700 
   127701   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   127702   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   127703   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   127704   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
   127705   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
   127706   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
   127707 
   127708   Fts3SegReader **apSegment = pCsr->apSegment;
   127709   int nSegment = pCsr->nSegment;
   127710   Fts3SegFilter *pFilter = pCsr->pFilter;
   127711   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
   127712     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
   127713   );
   127714 
   127715   if( pCsr->nSegment==0 ) return SQLITE_OK;
   127716 
   127717   do {
   127718     int nMerge;
   127719     int i;
   127720 
   127721     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
   127722     ** forward. Then sort the list in order of current term again.
   127723     */
   127724     for(i=0; i<pCsr->nAdvance; i++){
   127725       Fts3SegReader *pSeg = apSegment[i];
   127726       if( pSeg->bLookup ){
   127727         fts3SegReaderSetEof(pSeg);
   127728       }else{
   127729         rc = fts3SegReaderNext(p, pSeg, 0);
   127730       }
   127731       if( rc!=SQLITE_OK ) return rc;
   127732     }
   127733     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
   127734     pCsr->nAdvance = 0;
   127735 
   127736     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
   127737     assert( rc==SQLITE_OK );
   127738     if( apSegment[0]->aNode==0 ) break;
   127739 
   127740     pCsr->nTerm = apSegment[0]->nTerm;
   127741     pCsr->zTerm = apSegment[0]->zTerm;
   127742 
   127743     /* If this is a prefix-search, and if the term that apSegment[0] points
   127744     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   127745     ** required callbacks have been made. In this case exit early.
   127746     **
   127747     ** Similarly, if this is a search for an exact match, and the first term
   127748     ** of segment apSegment[0] is not a match, exit early.
   127749     */
   127750     if( pFilter->zTerm && !isScan ){
   127751       if( pCsr->nTerm<pFilter->nTerm
   127752        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
   127753        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
   127754       ){
   127755         break;
   127756       }
   127757     }
   127758 
   127759     nMerge = 1;
   127760     while( nMerge<nSegment
   127761         && apSegment[nMerge]->aNode
   127762         && apSegment[nMerge]->nTerm==pCsr->nTerm
   127763         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
   127764     ){
   127765       nMerge++;
   127766     }
   127767 
   127768     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   127769     if( nMerge==1
   127770      && !isIgnoreEmpty
   127771      && !isFirst
   127772      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
   127773     ){
   127774       pCsr->nDoclist = apSegment[0]->nDoclist;
   127775       if( fts3SegReaderIsPending(apSegment[0]) ){
   127776         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
   127777         pCsr->aDoclist = pCsr->aBuffer;
   127778       }else{
   127779         pCsr->aDoclist = apSegment[0]->aDoclist;
   127780       }
   127781       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
   127782     }else{
   127783       int nDoclist = 0;           /* Size of doclist */
   127784       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   127785 
   127786       /* The current term of the first nMerge entries in the array
   127787       ** of Fts3SegReader objects is the same. The doclists must be merged
   127788       ** and a single term returned with the merged doclist.
   127789       */
   127790       for(i=0; i<nMerge; i++){
   127791         fts3SegReaderFirstDocid(p, apSegment[i]);
   127792       }
   127793       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
   127794       while( apSegment[0]->pOffsetList ){
   127795         int j;                    /* Number of segments that share a docid */
   127796         char *pList;
   127797         int nList;
   127798         int nByte;
   127799         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   127800         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
   127801         j = 1;
   127802         while( j<nMerge
   127803             && apSegment[j]->pOffsetList
   127804             && apSegment[j]->iDocid==iDocid
   127805         ){
   127806           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
   127807           j++;
   127808         }
   127809 
   127810         if( isColFilter ){
   127811           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
   127812         }
   127813 
   127814         if( !isIgnoreEmpty || nList>0 ){
   127815 
   127816           /* Calculate the 'docid' delta value to write into the merged
   127817           ** doclist. */
   127818           sqlite3_int64 iDelta;
   127819           if( p->bDescIdx && nDoclist>0 ){
   127820             iDelta = iPrev - iDocid;
   127821           }else{
   127822             iDelta = iDocid - iPrev;
   127823           }
   127824           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
   127825           assert( nDoclist>0 || iDelta==iDocid );
   127826 
   127827           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
   127828           if( nDoclist+nByte>pCsr->nBuffer ){
   127829             char *aNew;
   127830             pCsr->nBuffer = (nDoclist+nByte)*2;
   127831             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
   127832             if( !aNew ){
   127833               return SQLITE_NOMEM;
   127834             }
   127835             pCsr->aBuffer = aNew;
   127836           }
   127837 
   127838           if( isFirst ){
   127839             char *a = &pCsr->aBuffer[nDoclist];
   127840             int nWrite;
   127841 
   127842             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
   127843             if( nWrite ){
   127844               iPrev = iDocid;
   127845               nDoclist += nWrite;
   127846             }
   127847           }else{
   127848             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
   127849             iPrev = iDocid;
   127850             if( isRequirePos ){
   127851               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
   127852               nDoclist += nList;
   127853               pCsr->aBuffer[nDoclist++] = '\0';
   127854             }
   127855           }
   127856         }
   127857 
   127858         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
   127859       }
   127860       if( nDoclist>0 ){
   127861         pCsr->aDoclist = pCsr->aBuffer;
   127862         pCsr->nDoclist = nDoclist;
   127863         rc = SQLITE_ROW;
   127864       }
   127865     }
   127866     pCsr->nAdvance = nMerge;
   127867   }while( rc==SQLITE_OK );
   127868 
   127869   return rc;
   127870 }
   127871 
   127872 
   127873 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
   127874   Fts3MultiSegReader *pCsr       /* Cursor object */
   127875 ){
   127876   if( pCsr ){
   127877     int i;
   127878     for(i=0; i<pCsr->nSegment; i++){
   127879       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
   127880     }
   127881     sqlite3_free(pCsr->apSegment);
   127882     sqlite3_free(pCsr->aBuffer);
   127883 
   127884     pCsr->nSegment = 0;
   127885     pCsr->apSegment = 0;
   127886     pCsr->aBuffer = 0;
   127887   }
   127888 }
   127889 
   127890 /*
   127891 ** Merge all level iLevel segments in the database into a single
   127892 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   127893 ** single segment with a level equal to the numerically largest level
   127894 ** currently present in the database.
   127895 **
   127896 ** If this function is called with iLevel<0, but there is only one
   127897 ** segment in the database, SQLITE_DONE is returned immediately.
   127898 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   127899 ** an SQLite error code is returned.
   127900 */
   127901 static int fts3SegmentMerge(
   127902   Fts3Table *p,
   127903   int iLangid,                    /* Language id to merge */
   127904   int iIndex,                     /* Index in p->aIndex[] to merge */
   127905   int iLevel                      /* Level to merge */
   127906 ){
   127907   int rc;                         /* Return code */
   127908   int iIdx = 0;                   /* Index of new segment */
   127909   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
   127910   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
   127911   Fts3SegFilter filter;           /* Segment term filter condition */
   127912   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
   127913   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
   127914 
   127915   assert( iLevel==FTS3_SEGCURSOR_ALL
   127916        || iLevel==FTS3_SEGCURSOR_PENDING
   127917        || iLevel>=0
   127918   );
   127919   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
   127920   assert( iIndex>=0 && iIndex<p->nIndex );
   127921 
   127922   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
   127923   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
   127924 
   127925   if( iLevel==FTS3_SEGCURSOR_ALL ){
   127926     /* This call is to merge all segments in the database to a single
   127927     ** segment. The level of the new segment is equal to the the numerically
   127928     ** greatest segment level currently present in the database for this
   127929     ** index. The idx of the new segment is always 0.  */
   127930     if( csr.nSegment==1 ){
   127931       rc = SQLITE_DONE;
   127932       goto finished;
   127933     }
   127934     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
   127935     bIgnoreEmpty = 1;
   127936 
   127937   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
   127938     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
   127939     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
   127940   }else{
   127941     /* This call is to merge all segments at level iLevel. find the next
   127942     ** available segment index at level iLevel+1. The call to
   127943     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   127944     ** a single iLevel+2 segment if necessary.  */
   127945     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
   127946     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
   127947   }
   127948   if( rc!=SQLITE_OK ) goto finished;
   127949   assert( csr.nSegment>0 );
   127950   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
   127951   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
   127952 
   127953   memset(&filter, 0, sizeof(Fts3SegFilter));
   127954   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   127955   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   127956 
   127957   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
   127958   while( SQLITE_OK==rc ){
   127959     rc = sqlite3Fts3SegReaderStep(p, &csr);
   127960     if( rc!=SQLITE_ROW ) break;
   127961     rc = fts3SegWriterAdd(p, &pWriter, 1,
   127962         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   127963   }
   127964   if( rc!=SQLITE_OK ) goto finished;
   127965   assert( pWriter );
   127966 
   127967   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
   127968     rc = fts3DeleteSegdir(
   127969         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
   127970     );
   127971     if( rc!=SQLITE_OK ) goto finished;
   127972   }
   127973   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   127974 
   127975  finished:
   127976   fts3SegWriterFree(pWriter);
   127977   sqlite3Fts3SegReaderFinish(&csr);
   127978   return rc;
   127979 }
   127980 
   127981 
   127982 /*
   127983 ** Flush the contents of pendingTerms to level 0 segments.
   127984 */
   127985 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   127986   int rc = SQLITE_OK;
   127987   int i;
   127988   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   127989     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
   127990     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   127991   }
   127992   sqlite3Fts3PendingTermsClear(p);
   127993   return rc;
   127994 }
   127995 
   127996 /*
   127997 ** Encode N integers as varints into a blob.
   127998 */
   127999 static void fts3EncodeIntArray(
   128000   int N,             /* The number of integers to encode */
   128001   u32 *a,            /* The integer values */
   128002   char *zBuf,        /* Write the BLOB here */
   128003   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   128004 ){
   128005   int i, j;
   128006   for(i=j=0; i<N; i++){
   128007     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   128008   }
   128009   *pNBuf = j;
   128010 }
   128011 
   128012 /*
   128013 ** Decode a blob of varints into N integers
   128014 */
   128015 static void fts3DecodeIntArray(
   128016   int N,             /* The number of integers to decode */
   128017   u32 *a,            /* Write the integer values */
   128018   const char *zBuf,  /* The BLOB containing the varints */
   128019   int nBuf           /* size of the BLOB */
   128020 ){
   128021   int i, j;
   128022   UNUSED_PARAMETER(nBuf);
   128023   for(i=j=0; i<N; i++){
   128024     sqlite3_int64 x;
   128025     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   128026     assert(j<=nBuf);
   128027     a[i] = (u32)(x & 0xffffffff);
   128028   }
   128029 }
   128030 
   128031 /*
   128032 ** Insert the sizes (in tokens) for each column of the document
   128033 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   128034 ** a blob of varints.
   128035 */
   128036 static void fts3InsertDocsize(
   128037   int *pRC,                       /* Result code */
   128038   Fts3Table *p,                   /* Table into which to insert */
   128039   u32 *aSz                        /* Sizes of each column, in tokens */
   128040 ){
   128041   char *pBlob;             /* The BLOB encoding of the document size */
   128042   int nBlob;               /* Number of bytes in the BLOB */
   128043   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   128044   int rc;                  /* Result code from subfunctions */
   128045 
   128046   if( *pRC ) return;
   128047   pBlob = sqlite3_malloc( 10*p->nColumn );
   128048   if( pBlob==0 ){
   128049     *pRC = SQLITE_NOMEM;
   128050     return;
   128051   }
   128052   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   128053   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   128054   if( rc ){
   128055     sqlite3_free(pBlob);
   128056     *pRC = rc;
   128057     return;
   128058   }
   128059   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   128060   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   128061   sqlite3_step(pStmt);
   128062   *pRC = sqlite3_reset(pStmt);
   128063 }
   128064 
   128065 /*
   128066 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   128067 ** where N is the number of user defined columns in the fts3 table plus
   128068 ** two. If nCol is the number of user defined columns, then values of the
   128069 ** varints are set as follows:
   128070 **
   128071 **   Varint 0:       Total number of rows in the table.
   128072 **
   128073 **   Varint 1..nCol: For each column, the total number of tokens stored in
   128074 **                   the column for all rows of the table.
   128075 **
   128076 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   128077 **                   columns of all rows of the table.
   128078 **
   128079 */
   128080 static void fts3UpdateDocTotals(
   128081   int *pRC,                       /* The result code */
   128082   Fts3Table *p,                   /* Table being updated */
   128083   u32 *aSzIns,                    /* Size increases */
   128084   u32 *aSzDel,                    /* Size decreases */
   128085   int nChng                       /* Change in the number of documents */
   128086 ){
   128087   char *pBlob;             /* Storage for BLOB written into %_stat */
   128088   int nBlob;               /* Size of BLOB written into %_stat */
   128089   u32 *a;                  /* Array of integers that becomes the BLOB */
   128090   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   128091   int i;                   /* Loop counter */
   128092   int rc;                  /* Result code from subfunctions */
   128093 
   128094   const int nStat = p->nColumn+2;
   128095 
   128096   if( *pRC ) return;
   128097   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   128098   if( a==0 ){
   128099     *pRC = SQLITE_NOMEM;
   128100     return;
   128101   }
   128102   pBlob = (char*)&a[nStat];
   128103   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
   128104   if( rc ){
   128105     sqlite3_free(a);
   128106     *pRC = rc;
   128107     return;
   128108   }
   128109   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   128110     fts3DecodeIntArray(nStat, a,
   128111          sqlite3_column_blob(pStmt, 0),
   128112          sqlite3_column_bytes(pStmt, 0));
   128113   }else{
   128114     memset(a, 0, sizeof(u32)*(nStat) );
   128115   }
   128116   sqlite3_reset(pStmt);
   128117   if( nChng<0 && a[0]<(u32)(-nChng) ){
   128118     a[0] = 0;
   128119   }else{
   128120     a[0] += nChng;
   128121   }
   128122   for(i=0; i<p->nColumn+1; i++){
   128123     u32 x = a[i+1];
   128124     if( x+aSzIns[i] < aSzDel[i] ){
   128125       x = 0;
   128126     }else{
   128127       x = x + aSzIns[i] - aSzDel[i];
   128128     }
   128129     a[i+1] = x;
   128130   }
   128131   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   128132   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
   128133   if( rc ){
   128134     sqlite3_free(a);
   128135     *pRC = rc;
   128136     return;
   128137   }
   128138   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
   128139   sqlite3_step(pStmt);
   128140   *pRC = sqlite3_reset(pStmt);
   128141   sqlite3_free(a);
   128142 }
   128143 
   128144 /*
   128145 ** Merge the entire database so that there is one segment for each
   128146 ** iIndex/iLangid combination.
   128147 */
   128148 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   128149   int bSeenDone = 0;
   128150   int rc;
   128151   sqlite3_stmt *pAllLangid = 0;
   128152 
   128153   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
   128154   if( rc==SQLITE_OK ){
   128155     int rc2;
   128156     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
   128157     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
   128158       int i;
   128159       int iLangid = sqlite3_column_int(pAllLangid, 0);
   128160       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
   128161         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
   128162         if( rc==SQLITE_DONE ){
   128163           bSeenDone = 1;
   128164           rc = SQLITE_OK;
   128165         }
   128166       }
   128167     }
   128168     rc2 = sqlite3_reset(pAllLangid);
   128169     if( rc==SQLITE_OK ) rc = rc2;
   128170   }
   128171 
   128172   sqlite3Fts3SegmentsClose(p);
   128173   sqlite3Fts3PendingTermsClear(p);
   128174 
   128175   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
   128176 }
   128177 
   128178 /*
   128179 ** This function is called when the user executes the following statement:
   128180 **
   128181 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
   128182 **
   128183 ** The entire FTS index is discarded and rebuilt. If the table is one
   128184 ** created using the content=xxx option, then the new index is based on
   128185 ** the current contents of the xxx table. Otherwise, it is rebuilt based
   128186 ** on the contents of the %_content table.
   128187 */
   128188 static int fts3DoRebuild(Fts3Table *p){
   128189   int rc;                         /* Return Code */
   128190 
   128191   rc = fts3DeleteAll(p, 0);
   128192   if( rc==SQLITE_OK ){
   128193     u32 *aSz = 0;
   128194     u32 *aSzIns = 0;
   128195     u32 *aSzDel = 0;
   128196     sqlite3_stmt *pStmt = 0;
   128197     int nEntry = 0;
   128198 
   128199     /* Compose and prepare an SQL statement to loop through the content table */
   128200     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
   128201     if( !zSql ){
   128202       rc = SQLITE_NOMEM;
   128203     }else{
   128204       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
   128205       sqlite3_free(zSql);
   128206     }
   128207 
   128208     if( rc==SQLITE_OK ){
   128209       int nByte = sizeof(u32) * (p->nColumn+1)*3;
   128210       aSz = (u32 *)sqlite3_malloc(nByte);
   128211       if( aSz==0 ){
   128212         rc = SQLITE_NOMEM;
   128213       }else{
   128214         memset(aSz, 0, nByte);
   128215         aSzIns = &aSz[p->nColumn+1];
   128216         aSzDel = &aSzIns[p->nColumn+1];
   128217       }
   128218     }
   128219 
   128220     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
   128221       int iCol;
   128222       int iLangid = langidFromSelect(p, pStmt);
   128223       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
   128224       aSz[p->nColumn] = 0;
   128225       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
   128226         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
   128227         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
   128228         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
   128229       }
   128230       if( p->bHasDocsize ){
   128231         fts3InsertDocsize(&rc, p, aSz);
   128232       }
   128233       if( rc!=SQLITE_OK ){
   128234         sqlite3_finalize(pStmt);
   128235         pStmt = 0;
   128236       }else{
   128237         nEntry++;
   128238         for(iCol=0; iCol<=p->nColumn; iCol++){
   128239           aSzIns[iCol] += aSz[iCol];
   128240         }
   128241       }
   128242     }
   128243     if( p->bHasStat ){
   128244       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
   128245     }
   128246     sqlite3_free(aSz);
   128247 
   128248     if( pStmt ){
   128249       int rc2 = sqlite3_finalize(pStmt);
   128250       if( rc==SQLITE_OK ){
   128251         rc = rc2;
   128252       }
   128253     }
   128254   }
   128255 
   128256   return rc;
   128257 }
   128258 
   128259 /*
   128260 ** Handle a 'special' INSERT of the form:
   128261 **
   128262 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   128263 **
   128264 ** Argument pVal contains the result of <expr>. Currently the only
   128265 ** meaningful value to insert is the text 'optimize'.
   128266 */
   128267 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   128268   int rc;                         /* Return Code */
   128269   const char *zVal = (const char *)sqlite3_value_text(pVal);
   128270   int nVal = sqlite3_value_bytes(pVal);
   128271 
   128272   if( !zVal ){
   128273     return SQLITE_NOMEM;
   128274   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   128275     rc = fts3DoOptimize(p, 0);
   128276   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
   128277     rc = fts3DoRebuild(p);
   128278 #ifdef SQLITE_TEST
   128279   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   128280     p->nNodeSize = atoi(&zVal[9]);
   128281     rc = SQLITE_OK;
   128282   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   128283     p->nMaxPendingData = atoi(&zVal[11]);
   128284     rc = SQLITE_OK;
   128285 #endif
   128286   }else{
   128287     rc = SQLITE_ERROR;
   128288   }
   128289 
   128290   return rc;
   128291 }
   128292 
   128293 /*
   128294 ** Delete all cached deferred doclists. Deferred doclists are cached
   128295 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   128296 */
   128297 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   128298   Fts3DeferredToken *pDef;
   128299   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   128300     fts3PendingListDelete(pDef->pList);
   128301     pDef->pList = 0;
   128302   }
   128303 }
   128304 
   128305 /*
   128306 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   128307 ** this list using sqlite3Fts3DeferToken().
   128308 */
   128309 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   128310   Fts3DeferredToken *pDef;
   128311   Fts3DeferredToken *pNext;
   128312   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   128313     pNext = pDef->pNext;
   128314     fts3PendingListDelete(pDef->pList);
   128315     sqlite3_free(pDef);
   128316   }
   128317   pCsr->pDeferred = 0;
   128318 }
   128319 
   128320 /*
   128321 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   128322 ** based on the row that pCsr currently points to.
   128323 **
   128324 ** A deferred-doclist is like any other doclist with position information
   128325 ** included, except that it only contains entries for a single row of the
   128326 ** table, not for all rows.
   128327 */
   128328 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   128329   int rc = SQLITE_OK;             /* Return code */
   128330   if( pCsr->pDeferred ){
   128331     int i;                        /* Used to iterate through table columns */
   128332     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   128333     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   128334 
   128335     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   128336     sqlite3_tokenizer *pT = p->pTokenizer;
   128337     sqlite3_tokenizer_module const *pModule = pT->pModule;
   128338 
   128339     assert( pCsr->isRequireSeek==0 );
   128340     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   128341 
   128342     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   128343       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   128344       sqlite3_tokenizer_cursor *pTC = 0;
   128345 
   128346       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
   128347       while( rc==SQLITE_OK ){
   128348         char const *zToken;       /* Buffer containing token */
   128349         int nToken;               /* Number of bytes in token */
   128350         int iDum1, iDum2;         /* Dummy variables */
   128351         int iPos;                 /* Position of token in zText */
   128352 
   128353         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   128354         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   128355           Fts3PhraseToken *pPT = pDef->pToken;
   128356           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   128357            && (pPT->bFirst==0 || iPos==0)
   128358            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   128359            && (0==memcmp(zToken, pPT->z, pPT->n))
   128360           ){
   128361             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   128362           }
   128363         }
   128364       }
   128365       if( pTC ) pModule->xClose(pTC);
   128366       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   128367     }
   128368 
   128369     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   128370       if( pDef->pList ){
   128371         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   128372       }
   128373     }
   128374   }
   128375 
   128376   return rc;
   128377 }
   128378 
   128379 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   128380   Fts3DeferredToken *p,
   128381   char **ppData,
   128382   int *pnData
   128383 ){
   128384   char *pRet;
   128385   int nSkip;
   128386   sqlite3_int64 dummy;
   128387 
   128388   *ppData = 0;
   128389   *pnData = 0;
   128390 
   128391   if( p->pList==0 ){
   128392     return SQLITE_OK;
   128393   }
   128394 
   128395   pRet = (char *)sqlite3_malloc(p->pList->nData);
   128396   if( !pRet ) return SQLITE_NOMEM;
   128397 
   128398   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   128399   *pnData = p->pList->nData - nSkip;
   128400   *ppData = pRet;
   128401 
   128402   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   128403   return SQLITE_OK;
   128404 }
   128405 
   128406 /*
   128407 ** Add an entry for token pToken to the pCsr->pDeferred list.
   128408 */
   128409 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   128410   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   128411   Fts3PhraseToken *pToken,        /* Token to defer */
   128412   int iCol                        /* Column that token must appear in (or -1) */
   128413 ){
   128414   Fts3DeferredToken *pDeferred;
   128415   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   128416   if( !pDeferred ){
   128417     return SQLITE_NOMEM;
   128418   }
   128419   memset(pDeferred, 0, sizeof(*pDeferred));
   128420   pDeferred->pToken = pToken;
   128421   pDeferred->pNext = pCsr->pDeferred;
   128422   pDeferred->iCol = iCol;
   128423   pCsr->pDeferred = pDeferred;
   128424 
   128425   assert( pToken->pDeferred==0 );
   128426   pToken->pDeferred = pDeferred;
   128427 
   128428   return SQLITE_OK;
   128429 }
   128430 
   128431 /*
   128432 ** SQLite value pRowid contains the rowid of a row that may or may not be
   128433 ** present in the FTS3 table. If it is, delete it and adjust the contents
   128434 ** of subsiduary data structures accordingly.
   128435 */
   128436 static int fts3DeleteByRowid(
   128437   Fts3Table *p,
   128438   sqlite3_value *pRowid,
   128439   int *pnDoc,
   128440   u32 *aSzDel
   128441 ){
   128442   int isEmpty = 0;
   128443   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
   128444   if( rc==SQLITE_OK ){
   128445     if( isEmpty ){
   128446       /* Deleting this row means the whole table is empty. In this case
   128447       ** delete the contents of all three tables and throw away any
   128448       ** data in the pendingTerms hash table.  */
   128449       rc = fts3DeleteAll(p, 1);
   128450       *pnDoc = *pnDoc - 1;
   128451     }else{
   128452       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
   128453       if( p->zContentTbl==0 ){
   128454         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
   128455         if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
   128456       }else{
   128457         *pnDoc = *pnDoc - 1;
   128458       }
   128459       if( p->bHasDocsize ){
   128460         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
   128461       }
   128462     }
   128463   }
   128464 
   128465   return rc;
   128466 }
   128467 
   128468 /*
   128469 ** This function does the work for the xUpdate method of FTS3 virtual
   128470 ** tables. The schema of the virtual table being:
   128471 **
   128472 **     CREATE TABLE <table name>(
   128473 **       <user COLUMns>,
   128474 **       <table name> HIDDEN,
   128475 **       docid HIDDEN,
   128476 **       <langid> HIDDEN
   128477 **     );
   128478 **
   128479 **
   128480 */
   128481 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   128482   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   128483   int nArg,                       /* Size of argument array */
   128484   sqlite3_value **apVal,          /* Array of arguments */
   128485   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   128486 ){
   128487   Fts3Table *p = (Fts3Table *)pVtab;
   128488   int rc = SQLITE_OK;             /* Return Code */
   128489   int isRemove = 0;               /* True for an UPDATE or DELETE */
   128490   u32 *aSzIns = 0;                /* Sizes of inserted documents */
   128491   u32 *aSzDel;                    /* Sizes of deleted documents */
   128492   int nChng = 0;                  /* Net change in number of documents */
   128493   int bInsertDone = 0;
   128494 
   128495   assert( p->pSegments==0 );
   128496   assert(
   128497       nArg==1                     /* DELETE operations */
   128498    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   128499   );
   128500 
   128501   /* Check for a "special" INSERT operation. One of the form:
   128502   **
   128503   **   INSERT INTO xyz(xyz) VALUES('command');
   128504   */
   128505   if( nArg>1
   128506    && sqlite3_value_type(apVal[0])==SQLITE_NULL
   128507    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   128508   ){
   128509     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
   128510     goto update_out;
   128511   }
   128512 
   128513   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
   128514     rc = SQLITE_CONSTRAINT;
   128515     goto update_out;
   128516   }
   128517 
   128518   /* Allocate space to hold the change in document sizes */
   128519   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
   128520   if( aSzIns==0 ){
   128521     rc = SQLITE_NOMEM;
   128522     goto update_out;
   128523   }
   128524   aSzDel = &aSzIns[p->nColumn+1];
   128525   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
   128526 
   128527   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
   128528   ** value, then this operation requires constraint handling.
   128529   **
   128530   ** If the on-conflict mode is REPLACE, this means that the existing row
   128531   ** should be deleted from the database before inserting the new row. Or,
   128532   ** if the on-conflict mode is other than REPLACE, then this method must
   128533   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
   128534   ** modify the database file.
   128535   */
   128536   if( nArg>1 && p->zContentTbl==0 ){
   128537     /* Find the value object that holds the new rowid value. */
   128538     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
   128539     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
   128540       pNewRowid = apVal[1];
   128541     }
   128542 
   128543     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
   128544         sqlite3_value_type(apVal[0])==SQLITE_NULL
   128545      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
   128546     )){
   128547       /* The new rowid is not NULL (in this case the rowid will be
   128548       ** automatically assigned and there is no chance of a conflict), and
   128549       ** the statement is either an INSERT or an UPDATE that modifies the
   128550       ** rowid column. So if the conflict mode is REPLACE, then delete any
   128551       ** existing row with rowid=pNewRowid.
   128552       **
   128553       ** Or, if the conflict mode is not REPLACE, insert the new record into
   128554       ** the %_content table. If we hit the duplicate rowid constraint (or any
   128555       ** other error) while doing so, return immediately.
   128556       **
   128557       ** This branch may also run if pNewRowid contains a value that cannot
   128558       ** be losslessly converted to an integer. In this case, the eventual
   128559       ** call to fts3InsertData() (either just below or further on in this
   128560       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
   128561       ** invoked, it will delete zero rows (since no row will have
   128562       ** docid=$pNewRowid if $pNewRowid is not an integer value).
   128563       */
   128564       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
   128565         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
   128566       }else{
   128567         rc = fts3InsertData(p, apVal, pRowid);
   128568         bInsertDone = 1;
   128569       }
   128570     }
   128571   }
   128572   if( rc!=SQLITE_OK ){
   128573     goto update_out;
   128574   }
   128575 
   128576   /* If this is a DELETE or UPDATE operation, remove the old record. */
   128577   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   128578     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
   128579     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   128580     isRemove = 1;
   128581   }
   128582 
   128583   /* If this is an INSERT or UPDATE operation, insert the new record. */
   128584   if( nArg>1 && rc==SQLITE_OK ){
   128585     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
   128586     if( bInsertDone==0 ){
   128587       rc = fts3InsertData(p, apVal, pRowid);
   128588       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
   128589         rc = FTS_CORRUPT_VTAB;
   128590       }
   128591     }
   128592     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
   128593       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
   128594     }
   128595     if( rc==SQLITE_OK ){
   128596       assert( p->iPrevDocid==*pRowid );
   128597       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
   128598     }
   128599     if( p->bHasDocsize ){
   128600       fts3InsertDocsize(&rc, p, aSzIns);
   128601     }
   128602     nChng++;
   128603   }
   128604 
   128605   if( p->bHasStat ){
   128606     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   128607   }
   128608 
   128609  update_out:
   128610   sqlite3_free(aSzIns);
   128611   sqlite3Fts3SegmentsClose(p);
   128612   return rc;
   128613 }
   128614 
   128615 /*
   128616 ** Flush any data in the pending-terms hash table to disk. If successful,
   128617 ** merge all segments in the database (including the new segment, if
   128618 ** there was any data to flush) into a single segment.
   128619 */
   128620 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   128621   int rc;
   128622   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   128623   if( rc==SQLITE_OK ){
   128624     rc = fts3DoOptimize(p, 1);
   128625     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
   128626       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   128627       if( rc2!=SQLITE_OK ) rc = rc2;
   128628     }else{
   128629       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   128630       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   128631     }
   128632   }
   128633   sqlite3Fts3SegmentsClose(p);
   128634   return rc;
   128635 }
   128636 
   128637 #endif
   128638 
   128639 /************** End of fts3_write.c ******************************************/
   128640 /************** Begin file fts3_snippet.c ************************************/
   128641 /*
   128642 ** 2009 Oct 23
   128643 **
   128644 ** The author disclaims copyright to this source code.  In place of
   128645 ** a legal notice, here is a blessing:
   128646 **
   128647 **    May you do good and not evil.
   128648 **    May you find forgiveness for yourself and forgive others.
   128649 **    May you share freely, never taking more than you give.
   128650 **
   128651 ******************************************************************************
   128652 */
   128653 
   128654 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   128655 
   128656 /* #include <string.h> */
   128657 /* #include <assert.h> */
   128658 
   128659 /*
   128660 ** Characters that may appear in the second argument to matchinfo().
   128661 */
   128662 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   128663 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   128664 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   128665 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   128666 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   128667 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   128668 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   128669 
   128670 /*
   128671 ** The default value for the second argument to matchinfo().
   128672 */
   128673 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   128674 
   128675 
   128676 /*
   128677 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   128678 ** Fts3Expr.aDoclist[]/nDoclist.
   128679 */
   128680 typedef struct LoadDoclistCtx LoadDoclistCtx;
   128681 struct LoadDoclistCtx {
   128682   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   128683   int nPhrase;                    /* Number of phrases seen so far */
   128684   int nToken;                     /* Number of tokens seen so far */
   128685 };
   128686 
   128687 /*
   128688 ** The following types are used as part of the implementation of the
   128689 ** fts3BestSnippet() routine.
   128690 */
   128691 typedef struct SnippetIter SnippetIter;
   128692 typedef struct SnippetPhrase SnippetPhrase;
   128693 typedef struct SnippetFragment SnippetFragment;
   128694 
   128695 struct SnippetIter {
   128696   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   128697   int iCol;                       /* Extract snippet from this column */
   128698   int nSnippet;                   /* Requested snippet length (in tokens) */
   128699   int nPhrase;                    /* Number of phrases in query */
   128700   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   128701   int iCurrent;                   /* First token of current snippet */
   128702 };
   128703 
   128704 struct SnippetPhrase {
   128705   int nToken;                     /* Number of tokens in phrase */
   128706   char *pList;                    /* Pointer to start of phrase position list */
   128707   int iHead;                      /* Next value in position list */
   128708   char *pHead;                    /* Position list data following iHead */
   128709   int iTail;                      /* Next value in trailing position list */
   128710   char *pTail;                    /* Position list data following iTail */
   128711 };
   128712 
   128713 struct SnippetFragment {
   128714   int iCol;                       /* Column snippet is extracted from */
   128715   int iPos;                       /* Index of first token in snippet */
   128716   u64 covered;                    /* Mask of query phrases covered */
   128717   u64 hlmask;                     /* Mask of snippet terms to highlight */
   128718 };
   128719 
   128720 /*
   128721 ** This type is used as an fts3ExprIterate() context object while
   128722 ** accumulating the data returned by the matchinfo() function.
   128723 */
   128724 typedef struct MatchInfo MatchInfo;
   128725 struct MatchInfo {
   128726   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   128727   int nCol;                       /* Number of columns in table */
   128728   int nPhrase;                    /* Number of matchable phrases in query */
   128729   sqlite3_int64 nDoc;             /* Number of docs in database */
   128730   u32 *aMatchinfo;                /* Pre-allocated buffer */
   128731 };
   128732 
   128733 
   128734 
   128735 /*
   128736 ** The snippet() and offsets() functions both return text values. An instance
   128737 ** of the following structure is used to accumulate those values while the
   128738 ** functions are running. See fts3StringAppend() for details.
   128739 */
   128740 typedef struct StrBuffer StrBuffer;
   128741 struct StrBuffer {
   128742   char *z;                        /* Pointer to buffer containing string */
   128743   int n;                          /* Length of z in bytes (excl. nul-term) */
   128744   int nAlloc;                     /* Allocated size of buffer z in bytes */
   128745 };
   128746 
   128747 
   128748 /*
   128749 ** This function is used to help iterate through a position-list. A position
   128750 ** list is a list of unique integers, sorted from smallest to largest. Each
   128751 ** element of the list is represented by an FTS3 varint that takes the value
   128752 ** of the difference between the current element and the previous one plus
   128753 ** two. For example, to store the position-list:
   128754 **
   128755 **     4 9 113
   128756 **
   128757 ** the three varints:
   128758 **
   128759 **     6 7 106
   128760 **
   128761 ** are encoded.
   128762 **
   128763 ** When this function is called, *pp points to the start of an element of
   128764 ** the list. *piPos contains the value of the previous entry in the list.
   128765 ** After it returns, *piPos contains the value of the next element of the
   128766 ** list and *pp is advanced to the following varint.
   128767 */
   128768 static void fts3GetDeltaPosition(char **pp, int *piPos){
   128769   int iVal;
   128770   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
   128771   *piPos += (iVal-2);
   128772 }
   128773 
   128774 /*
   128775 ** Helper function for fts3ExprIterate() (see below).
   128776 */
   128777 static int fts3ExprIterate2(
   128778   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   128779   int *piPhrase,                  /* Pointer to phrase counter */
   128780   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   128781   void *pCtx                      /* Second argument to pass to callback */
   128782 ){
   128783   int rc;                         /* Return code */
   128784   int eType = pExpr->eType;       /* Type of expression node pExpr */
   128785 
   128786   if( eType!=FTSQUERY_PHRASE ){
   128787     assert( pExpr->pLeft && pExpr->pRight );
   128788     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   128789     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   128790       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   128791     }
   128792   }else{
   128793     rc = x(pExpr, *piPhrase, pCtx);
   128794     (*piPhrase)++;
   128795   }
   128796   return rc;
   128797 }
   128798 
   128799 /*
   128800 ** Iterate through all phrase nodes in an FTS3 query, except those that
   128801 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   128802 ** For each phrase node found, the supplied callback function is invoked.
   128803 **
   128804 ** If the callback function returns anything other than SQLITE_OK,
   128805 ** the iteration is abandoned and the error code returned immediately.
   128806 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   128807 ** all eligible phrase nodes.
   128808 */
   128809 static int fts3ExprIterate(
   128810   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   128811   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   128812   void *pCtx                      /* Second argument to pass to callback */
   128813 ){
   128814   int iPhrase = 0;                /* Variable used as the phrase counter */
   128815   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   128816 }
   128817 
   128818 /*
   128819 ** This is an fts3ExprIterate() callback used while loading the doclists
   128820 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   128821 ** fts3ExprLoadDoclists().
   128822 */
   128823 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   128824   int rc = SQLITE_OK;
   128825   Fts3Phrase *pPhrase = pExpr->pPhrase;
   128826   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   128827 
   128828   UNUSED_PARAMETER(iPhrase);
   128829 
   128830   p->nPhrase++;
   128831   p->nToken += pPhrase->nToken;
   128832 
   128833   return rc;
   128834 }
   128835 
   128836 /*
   128837 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   128838 ** pCsr.
   128839 **
   128840 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   128841 ** phrases in the expression (all phrases except those directly or
   128842 ** indirectly descended from the right-hand-side of a NOT operator). If
   128843 ** pnToken is not NULL, then it is set to the number of tokens in all
   128844 ** matchable phrases of the expression.
   128845 */
   128846 static int fts3ExprLoadDoclists(
   128847   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   128848   int *pnPhrase,                  /* OUT: Number of phrases in query */
   128849   int *pnToken                    /* OUT: Number of tokens in query */
   128850 ){
   128851   int rc;                         /* Return Code */
   128852   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   128853   sCtx.pCsr = pCsr;
   128854   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
   128855   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   128856   if( pnToken ) *pnToken = sCtx.nToken;
   128857   return rc;
   128858 }
   128859 
   128860 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   128861   (*(int *)ctx)++;
   128862   UNUSED_PARAMETER(pExpr);
   128863   UNUSED_PARAMETER(iPhrase);
   128864   return SQLITE_OK;
   128865 }
   128866 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   128867   int nPhrase = 0;
   128868   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   128869   return nPhrase;
   128870 }
   128871 
   128872 /*
   128873 ** Advance the position list iterator specified by the first two
   128874 ** arguments so that it points to the first element with a value greater
   128875 ** than or equal to parameter iNext.
   128876 */
   128877 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   128878   char *pIter = *ppIter;
   128879   if( pIter ){
   128880     int iIter = *piIter;
   128881 
   128882     while( iIter<iNext ){
   128883       if( 0==(*pIter & 0xFE) ){
   128884         iIter = -1;
   128885         pIter = 0;
   128886         break;
   128887       }
   128888       fts3GetDeltaPosition(&pIter, &iIter);
   128889     }
   128890 
   128891     *piIter = iIter;
   128892     *ppIter = pIter;
   128893   }
   128894 }
   128895 
   128896 /*
   128897 ** Advance the snippet iterator to the next candidate snippet.
   128898 */
   128899 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   128900   int i;                          /* Loop counter */
   128901 
   128902   if( pIter->iCurrent<0 ){
   128903     /* The SnippetIter object has just been initialized. The first snippet
   128904     ** candidate always starts at offset 0 (even if this candidate has a
   128905     ** score of 0.0).
   128906     */
   128907     pIter->iCurrent = 0;
   128908 
   128909     /* Advance the 'head' iterator of each phrase to the first offset that
   128910     ** is greater than or equal to (iNext+nSnippet).
   128911     */
   128912     for(i=0; i<pIter->nPhrase; i++){
   128913       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128914       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   128915     }
   128916   }else{
   128917     int iStart;
   128918     int iEnd = 0x7FFFFFFF;
   128919 
   128920     for(i=0; i<pIter->nPhrase; i++){
   128921       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128922       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   128923         iEnd = pPhrase->iHead;
   128924       }
   128925     }
   128926     if( iEnd==0x7FFFFFFF ){
   128927       return 1;
   128928     }
   128929 
   128930     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   128931     for(i=0; i<pIter->nPhrase; i++){
   128932       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128933       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   128934       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   128935     }
   128936   }
   128937 
   128938   return 0;
   128939 }
   128940 
   128941 /*
   128942 ** Retrieve information about the current candidate snippet of snippet
   128943 ** iterator pIter.
   128944 */
   128945 static void fts3SnippetDetails(
   128946   SnippetIter *pIter,             /* Snippet iterator */
   128947   u64 mCovered,                   /* Bitmask of phrases already covered */
   128948   int *piToken,                   /* OUT: First token of proposed snippet */
   128949   int *piScore,                   /* OUT: "Score" for this snippet */
   128950   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   128951   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   128952 ){
   128953   int iStart = pIter->iCurrent;   /* First token of snippet */
   128954   int iScore = 0;                 /* Score of this snippet */
   128955   int i;                          /* Loop counter */
   128956   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   128957   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   128958 
   128959   for(i=0; i<pIter->nPhrase; i++){
   128960     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   128961     if( pPhrase->pTail ){
   128962       char *pCsr = pPhrase->pTail;
   128963       int iCsr = pPhrase->iTail;
   128964 
   128965       while( iCsr<(iStart+pIter->nSnippet) ){
   128966         int j;
   128967         u64 mPhrase = (u64)1 << i;
   128968         u64 mPos = (u64)1 << (iCsr - iStart);
   128969         assert( iCsr>=iStart );
   128970         if( (mCover|mCovered)&mPhrase ){
   128971           iScore++;
   128972         }else{
   128973           iScore += 1000;
   128974         }
   128975         mCover |= mPhrase;
   128976 
   128977         for(j=0; j<pPhrase->nToken; j++){
   128978           mHighlight |= (mPos>>j);
   128979         }
   128980 
   128981         if( 0==(*pCsr & 0x0FE) ) break;
   128982         fts3GetDeltaPosition(&pCsr, &iCsr);
   128983       }
   128984     }
   128985   }
   128986 
   128987   /* Set the output variables before returning. */
   128988   *piToken = iStart;
   128989   *piScore = iScore;
   128990   *pmCover = mCover;
   128991   *pmHighlight = mHighlight;
   128992 }
   128993 
   128994 /*
   128995 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   128996 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   128997 */
   128998 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   128999   SnippetIter *p = (SnippetIter *)ctx;
   129000   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   129001   char *pCsr;
   129002 
   129003   pPhrase->nToken = pExpr->pPhrase->nToken;
   129004 
   129005   pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
   129006   if( pCsr ){
   129007     int iFirst = 0;
   129008     pPhrase->pList = pCsr;
   129009     fts3GetDeltaPosition(&pCsr, &iFirst);
   129010     assert( iFirst>=0 );
   129011     pPhrase->pHead = pCsr;
   129012     pPhrase->pTail = pCsr;
   129013     pPhrase->iHead = iFirst;
   129014     pPhrase->iTail = iFirst;
   129015   }else{
   129016     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
   129017   }
   129018 
   129019   return SQLITE_OK;
   129020 }
   129021 
   129022 /*
   129023 ** Select the fragment of text consisting of nFragment contiguous tokens
   129024 ** from column iCol that represent the "best" snippet. The best snippet
   129025 ** is the snippet with the highest score, where scores are calculated
   129026 ** by adding:
   129027 **
   129028 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
   129029 **
   129030 **   (b) +1000 points for the first occurence of each matchable phrase in
   129031 **       the snippet for which the corresponding mCovered bit is not set.
   129032 **
   129033 ** The selected snippet parameters are stored in structure *pFragment before
   129034 ** returning. The score of the selected snippet is stored in *piScore
   129035 ** before returning.
   129036 */
   129037 static int fts3BestSnippet(
   129038   int nSnippet,                   /* Desired snippet length */
   129039   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   129040   int iCol,                       /* Index of column to create snippet from */
   129041   u64 mCovered,                   /* Mask of phrases already covered */
   129042   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   129043   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   129044   int *piScore                    /* OUT: Score of snippet pFragment */
   129045 ){
   129046   int rc;                         /* Return Code */
   129047   int nList;                      /* Number of phrases in expression */
   129048   SnippetIter sIter;              /* Iterates through snippet candidates */
   129049   int nByte;                      /* Number of bytes of space to allocate */
   129050   int iBestScore = -1;            /* Best snippet score found so far */
   129051   int i;                          /* Loop counter */
   129052 
   129053   memset(&sIter, 0, sizeof(sIter));
   129054 
   129055   /* Iterate through the phrases in the expression to count them. The same
   129056   ** callback makes sure the doclists are loaded for each phrase.
   129057   */
   129058   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   129059   if( rc!=SQLITE_OK ){
   129060     return rc;
   129061   }
   129062 
   129063   /* Now that it is known how many phrases there are, allocate and zero
   129064   ** the required space using malloc().
   129065   */
   129066   nByte = sizeof(SnippetPhrase) * nList;
   129067   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   129068   if( !sIter.aPhrase ){
   129069     return SQLITE_NOMEM;
   129070   }
   129071   memset(sIter.aPhrase, 0, nByte);
   129072 
   129073   /* Initialize the contents of the SnippetIter object. Then iterate through
   129074   ** the set of phrases in the expression to populate the aPhrase[] array.
   129075   */
   129076   sIter.pCsr = pCsr;
   129077   sIter.iCol = iCol;
   129078   sIter.nSnippet = nSnippet;
   129079   sIter.nPhrase = nList;
   129080   sIter.iCurrent = -1;
   129081   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
   129082 
   129083   /* Set the *pmSeen output variable. */
   129084   for(i=0; i<nList; i++){
   129085     if( sIter.aPhrase[i].pHead ){
   129086       *pmSeen |= (u64)1 << i;
   129087     }
   129088   }
   129089 
   129090   /* Loop through all candidate snippets. Store the best snippet in
   129091   ** *pFragment. Store its associated 'score' in iBestScore.
   129092   */
   129093   pFragment->iCol = iCol;
   129094   while( !fts3SnippetNextCandidate(&sIter) ){
   129095     int iPos;
   129096     int iScore;
   129097     u64 mCover;
   129098     u64 mHighlight;
   129099     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
   129100     assert( iScore>=0 );
   129101     if( iScore>iBestScore ){
   129102       pFragment->iPos = iPos;
   129103       pFragment->hlmask = mHighlight;
   129104       pFragment->covered = mCover;
   129105       iBestScore = iScore;
   129106     }
   129107   }
   129108 
   129109   sqlite3_free(sIter.aPhrase);
   129110   *piScore = iBestScore;
   129111   return SQLITE_OK;
   129112 }
   129113 
   129114 
   129115 /*
   129116 ** Append a string to the string-buffer passed as the first argument.
   129117 **
   129118 ** If nAppend is negative, then the length of the string zAppend is
   129119 ** determined using strlen().
   129120 */
   129121 static int fts3StringAppend(
   129122   StrBuffer *pStr,                /* Buffer to append to */
   129123   const char *zAppend,            /* Pointer to data to append to buffer */
   129124   int nAppend                     /* Size of zAppend in bytes (or -1) */
   129125 ){
   129126   if( nAppend<0 ){
   129127     nAppend = (int)strlen(zAppend);
   129128   }
   129129 
   129130   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   129131   ** to grow the buffer until so that it is big enough to accomadate the
   129132   ** appended data.
   129133   */
   129134   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   129135     int nAlloc = pStr->nAlloc+nAppend+100;
   129136     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   129137     if( !zNew ){
   129138       return SQLITE_NOMEM;
   129139     }
   129140     pStr->z = zNew;
   129141     pStr->nAlloc = nAlloc;
   129142   }
   129143 
   129144   /* Append the data to the string buffer. */
   129145   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   129146   pStr->n += nAppend;
   129147   pStr->z[pStr->n] = '\0';
   129148 
   129149   return SQLITE_OK;
   129150 }
   129151 
   129152 /*
   129153 ** The fts3BestSnippet() function often selects snippets that end with a
   129154 ** query term. That is, the final term of the snippet is always a term
   129155 ** that requires highlighting. For example, if 'X' is a highlighted term
   129156 ** and '.' is a non-highlighted term, BestSnippet() may select:
   129157 **
   129158 **     ........X.....X
   129159 **
   129160 ** This function "shifts" the beginning of the snippet forward in the
   129161 ** document so that there are approximately the same number of
   129162 ** non-highlighted terms to the right of the final highlighted term as there
   129163 ** are to the left of the first highlighted term. For example, to this:
   129164 **
   129165 **     ....X.....X....
   129166 **
   129167 ** This is done as part of extracting the snippet text, not when selecting
   129168 ** the snippet. Snippet selection is done based on doclists only, so there
   129169 ** is no way for fts3BestSnippet() to know whether or not the document
   129170 ** actually contains terms that follow the final highlighted term.
   129171 */
   129172 static int fts3SnippetShift(
   129173   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   129174   int iLangid,                    /* Language id to use in tokenizing */
   129175   int nSnippet,                   /* Number of tokens desired for snippet */
   129176   const char *zDoc,               /* Document text to extract snippet from */
   129177   int nDoc,                       /* Size of buffer zDoc in bytes */
   129178   int *piPos,                     /* IN/OUT: First token of snippet */
   129179   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   129180 ){
   129181   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   129182 
   129183   if( hlmask ){
   129184     int nLeft;                    /* Tokens to the left of first highlight */
   129185     int nRight;                   /* Tokens to the right of last highlight */
   129186     int nDesired;                 /* Ideal number of tokens to shift forward */
   129187 
   129188     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   129189     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   129190     nDesired = (nLeft-nRight)/2;
   129191 
   129192     /* Ideally, the start of the snippet should be pushed forward in the
   129193     ** document nDesired tokens. This block checks if there are actually
   129194     ** nDesired tokens to the right of the snippet. If so, *piPos and
   129195     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   129196     ** right. Otherwise, the snippet is shifted by the number of tokens
   129197     ** available.
   129198     */
   129199     if( nDesired>0 ){
   129200       int nShift;                 /* Number of tokens to shift snippet by */
   129201       int iCurrent = 0;           /* Token counter */
   129202       int rc;                     /* Return Code */
   129203       sqlite3_tokenizer_module *pMod;
   129204       sqlite3_tokenizer_cursor *pC;
   129205       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   129206 
   129207       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   129208       ** or more tokens in zDoc/nDoc.
   129209       */
   129210       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
   129211       if( rc!=SQLITE_OK ){
   129212         return rc;
   129213       }
   129214       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   129215         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
   129216         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   129217       }
   129218       pMod->xClose(pC);
   129219       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   129220 
   129221       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   129222       assert( nShift<=nDesired );
   129223       if( nShift>0 ){
   129224         *piPos += nShift;
   129225         *pHlmask = hlmask >> nShift;
   129226       }
   129227     }
   129228   }
   129229   return SQLITE_OK;
   129230 }
   129231 
   129232 /*
   129233 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   129234 ** append it to string buffer pOut.
   129235 */
   129236 static int fts3SnippetText(
   129237   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   129238   SnippetFragment *pFragment,     /* Snippet to extract */
   129239   int iFragment,                  /* Fragment number */
   129240   int isLast,                     /* True for final fragment in snippet */
   129241   int nSnippet,                   /* Number of tokens in extracted snippet */
   129242   const char *zOpen,              /* String inserted before highlighted term */
   129243   const char *zClose,             /* String inserted after highlighted term */
   129244   const char *zEllipsis,          /* String inserted between snippets */
   129245   StrBuffer *pOut                 /* Write output here */
   129246 ){
   129247   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129248   int rc;                         /* Return code */
   129249   const char *zDoc;               /* Document text to extract snippet from */
   129250   int nDoc;                       /* Size of zDoc in bytes */
   129251   int iCurrent = 0;               /* Current token number of document */
   129252   int iEnd = 0;                   /* Byte offset of end of current token */
   129253   int isShiftDone = 0;            /* True after snippet is shifted */
   129254   int iPos = pFragment->iPos;     /* First token of snippet */
   129255   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   129256   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   129257   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   129258   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   129259   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
   129260   int DUMMY1;                     /* Dummy argument used with tokenizer */
   129261 
   129262   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   129263   if( zDoc==0 ){
   129264     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   129265       return SQLITE_NOMEM;
   129266     }
   129267     return SQLITE_OK;
   129268   }
   129269   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   129270 
   129271   /* Open a token cursor on the document. */
   129272   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   129273   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
   129274   if( rc!=SQLITE_OK ){
   129275     return rc;
   129276   }
   129277 
   129278   while( rc==SQLITE_OK ){
   129279     int iBegin;                   /* Offset in zDoc of start of token */
   129280     int iFin;                     /* Offset in zDoc of end of token */
   129281     int isHighlight;              /* True for highlighted terms */
   129282 
   129283     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   129284     if( rc!=SQLITE_OK ){
   129285       if( rc==SQLITE_DONE ){
   129286         /* Special case - the last token of the snippet is also the last token
   129287         ** of the column. Append any punctuation that occurred between the end
   129288         ** of the previous token and the end of the document to the output.
   129289         ** Then break out of the loop. */
   129290         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   129291       }
   129292       break;
   129293     }
   129294     if( iCurrent<iPos ){ continue; }
   129295 
   129296     if( !isShiftDone ){
   129297       int n = nDoc - iBegin;
   129298       rc = fts3SnippetShift(
   129299           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
   129300       );
   129301       isShiftDone = 1;
   129302 
   129303       /* Now that the shift has been done, check if the initial "..." are
   129304       ** required. They are required if (a) this is not the first fragment,
   129305       ** or (b) this fragment does not begin at position 0 of its column.
   129306       */
   129307       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
   129308         rc = fts3StringAppend(pOut, zEllipsis, -1);
   129309       }
   129310       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   129311     }
   129312 
   129313     if( iCurrent>=(iPos+nSnippet) ){
   129314       if( isLast ){
   129315         rc = fts3StringAppend(pOut, zEllipsis, -1);
   129316       }
   129317       break;
   129318     }
   129319 
   129320     /* Set isHighlight to true if this term should be highlighted. */
   129321     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   129322 
   129323     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   129324     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   129325     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   129326     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   129327 
   129328     iEnd = iFin;
   129329   }
   129330 
   129331   pMod->xClose(pC);
   129332   return rc;
   129333 }
   129334 
   129335 
   129336 /*
   129337 ** This function is used to count the entries in a column-list (a
   129338 ** delta-encoded list of term offsets within a single column of a single
   129339 ** row). When this function is called, *ppCollist should point to the
   129340 ** beginning of the first varint in the column-list (the varint that
   129341 ** contains the position of the first matching term in the column data).
   129342 ** Before returning, *ppCollist is set to point to the first byte after
   129343 ** the last varint in the column-list (either the 0x00 signifying the end
   129344 ** of the position-list, or the 0x01 that precedes the column number of
   129345 ** the next column in the position-list).
   129346 **
   129347 ** The number of elements in the column-list is returned.
   129348 */
   129349 static int fts3ColumnlistCount(char **ppCollist){
   129350   char *pEnd = *ppCollist;
   129351   char c = 0;
   129352   int nEntry = 0;
   129353 
   129354   /* A column-list is terminated by either a 0x01 or 0x00. */
   129355   while( 0xFE & (*pEnd | c) ){
   129356     c = *pEnd++ & 0x80;
   129357     if( !c ) nEntry++;
   129358   }
   129359 
   129360   *ppCollist = pEnd;
   129361   return nEntry;
   129362 }
   129363 
   129364 /*
   129365 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   129366 ** for a single query.
   129367 **
   129368 ** fts3ExprIterate() callback to load the 'global' elements of a
   129369 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   129370 ** of the matchinfo array that are constant for all rows returned by the
   129371 ** current query.
   129372 **
   129373 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   129374 ** function populates Matchinfo.aMatchinfo[] as follows:
   129375 **
   129376 **   for(iCol=0; iCol<nCol; iCol++){
   129377 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   129378 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   129379 **   }
   129380 **
   129381 ** where X is the number of matches for phrase iPhrase is column iCol of all
   129382 ** rows of the table. Y is the number of rows for which column iCol contains
   129383 ** at least one instance of phrase iPhrase.
   129384 **
   129385 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   129386 ** Y values are set to nDoc, where nDoc is the number of documents in the
   129387 ** file system. This is done because the full-text index doclist is required
   129388 ** to calculate these values properly, and the full-text index doclist is
   129389 ** not available for deferred tokens.
   129390 */
   129391 static int fts3ExprGlobalHitsCb(
   129392   Fts3Expr *pExpr,                /* Phrase expression node */
   129393   int iPhrase,                    /* Phrase number (numbered from zero) */
   129394   void *pCtx                      /* Pointer to MatchInfo structure */
   129395 ){
   129396   MatchInfo *p = (MatchInfo *)pCtx;
   129397   return sqlite3Fts3EvalPhraseStats(
   129398       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
   129399   );
   129400 }
   129401 
   129402 /*
   129403 ** fts3ExprIterate() callback used to collect the "local" part of the
   129404 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   129405 ** array that are different for each row returned by the query.
   129406 */
   129407 static int fts3ExprLocalHitsCb(
   129408   Fts3Expr *pExpr,                /* Phrase expression node */
   129409   int iPhrase,                    /* Phrase number */
   129410   void *pCtx                      /* Pointer to MatchInfo structure */
   129411 ){
   129412   MatchInfo *p = (MatchInfo *)pCtx;
   129413   int iStart = iPhrase * p->nCol * 3;
   129414   int i;
   129415 
   129416   for(i=0; i<p->nCol; i++){
   129417     char *pCsr;
   129418     pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
   129419     if( pCsr ){
   129420       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
   129421     }else{
   129422       p->aMatchinfo[iStart+i*3] = 0;
   129423     }
   129424   }
   129425 
   129426   return SQLITE_OK;
   129427 }
   129428 
   129429 static int fts3MatchinfoCheck(
   129430   Fts3Table *pTab,
   129431   char cArg,
   129432   char **pzErr
   129433 ){
   129434   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   129435    || (cArg==FTS3_MATCHINFO_NCOL)
   129436    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
   129437    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
   129438    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   129439    || (cArg==FTS3_MATCHINFO_LCS)
   129440    || (cArg==FTS3_MATCHINFO_HITS)
   129441   ){
   129442     return SQLITE_OK;
   129443   }
   129444   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
   129445   return SQLITE_ERROR;
   129446 }
   129447 
   129448 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   129449   int nVal;                       /* Number of integers output by cArg */
   129450 
   129451   switch( cArg ){
   129452     case FTS3_MATCHINFO_NDOC:
   129453     case FTS3_MATCHINFO_NPHRASE:
   129454     case FTS3_MATCHINFO_NCOL:
   129455       nVal = 1;
   129456       break;
   129457 
   129458     case FTS3_MATCHINFO_AVGLENGTH:
   129459     case FTS3_MATCHINFO_LENGTH:
   129460     case FTS3_MATCHINFO_LCS:
   129461       nVal = pInfo->nCol;
   129462       break;
   129463 
   129464     default:
   129465       assert( cArg==FTS3_MATCHINFO_HITS );
   129466       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   129467       break;
   129468   }
   129469 
   129470   return nVal;
   129471 }
   129472 
   129473 static int fts3MatchinfoSelectDoctotal(
   129474   Fts3Table *pTab,
   129475   sqlite3_stmt **ppStmt,
   129476   sqlite3_int64 *pnDoc,
   129477   const char **paLen
   129478 ){
   129479   sqlite3_stmt *pStmt;
   129480   const char *a;
   129481   sqlite3_int64 nDoc;
   129482 
   129483   if( !*ppStmt ){
   129484     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   129485     if( rc!=SQLITE_OK ) return rc;
   129486   }
   129487   pStmt = *ppStmt;
   129488   assert( sqlite3_data_count(pStmt)==1 );
   129489 
   129490   a = sqlite3_column_blob(pStmt, 0);
   129491   a += sqlite3Fts3GetVarint(a, &nDoc);
   129492   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
   129493   *pnDoc = (u32)nDoc;
   129494 
   129495   if( paLen ) *paLen = a;
   129496   return SQLITE_OK;
   129497 }
   129498 
   129499 /*
   129500 ** An instance of the following structure is used to store state while
   129501 ** iterating through a multi-column position-list corresponding to the
   129502 ** hits for a single phrase on a single row in order to calculate the
   129503 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   129504 */
   129505 typedef struct LcsIterator LcsIterator;
   129506 struct LcsIterator {
   129507   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   129508   int iPosOffset;                 /* Tokens count up to end of this phrase */
   129509   char *pRead;                    /* Cursor used to iterate through aDoclist */
   129510   int iPos;                       /* Current position */
   129511 };
   129512 
   129513 /*
   129514 ** If LcsIterator.iCol is set to the following value, the iterator has
   129515 ** finished iterating through all offsets for all columns.
   129516 */
   129517 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   129518 
   129519 static int fts3MatchinfoLcsCb(
   129520   Fts3Expr *pExpr,                /* Phrase expression node */
   129521   int iPhrase,                    /* Phrase number (numbered from zero) */
   129522   void *pCtx                      /* Pointer to MatchInfo structure */
   129523 ){
   129524   LcsIterator *aIter = (LcsIterator *)pCtx;
   129525   aIter[iPhrase].pExpr = pExpr;
   129526   return SQLITE_OK;
   129527 }
   129528 
   129529 /*
   129530 ** Advance the iterator passed as an argument to the next position. Return
   129531 ** 1 if the iterator is at EOF or if it now points to the start of the
   129532 ** position list for the next column.
   129533 */
   129534 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   129535   char *pRead = pIter->pRead;
   129536   sqlite3_int64 iRead;
   129537   int rc = 0;
   129538 
   129539   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   129540   if( iRead==0 || iRead==1 ){
   129541     pRead = 0;
   129542     rc = 1;
   129543   }else{
   129544     pIter->iPos += (int)(iRead-2);
   129545   }
   129546 
   129547   pIter->pRead = pRead;
   129548   return rc;
   129549 }
   129550 
   129551 /*
   129552 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   129553 **
   129554 ** If the call is successful, the longest-common-substring lengths for each
   129555 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   129556 ** array before returning. SQLITE_OK is returned in this case.
   129557 **
   129558 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   129559 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   129560 ** undefined.
   129561 */
   129562 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   129563   LcsIterator *aIter;
   129564   int i;
   129565   int iCol;
   129566   int nToken = 0;
   129567 
   129568   /* Allocate and populate the array of LcsIterator objects. The array
   129569   ** contains one element for each matchable phrase in the query.
   129570   **/
   129571   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   129572   if( !aIter ) return SQLITE_NOMEM;
   129573   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   129574   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   129575 
   129576   for(i=0; i<pInfo->nPhrase; i++){
   129577     LcsIterator *pIter = &aIter[i];
   129578     nToken -= pIter->pExpr->pPhrase->nToken;
   129579     pIter->iPosOffset = nToken;
   129580   }
   129581 
   129582   for(iCol=0; iCol<pInfo->nCol; iCol++){
   129583     int nLcs = 0;                 /* LCS value for this column */
   129584     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   129585 
   129586     for(i=0; i<pInfo->nPhrase; i++){
   129587       LcsIterator *pIt = &aIter[i];
   129588       pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
   129589       if( pIt->pRead ){
   129590         pIt->iPos = pIt->iPosOffset;
   129591         fts3LcsIteratorAdvance(&aIter[i]);
   129592         nLive++;
   129593       }
   129594     }
   129595 
   129596     while( nLive>0 ){
   129597       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   129598       int nThisLcs = 0;           /* LCS for the current iterator positions */
   129599 
   129600       for(i=0; i<pInfo->nPhrase; i++){
   129601         LcsIterator *pIter = &aIter[i];
   129602         if( pIter->pRead==0 ){
   129603           /* This iterator is already at EOF for this column. */
   129604           nThisLcs = 0;
   129605         }else{
   129606           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   129607             pAdv = pIter;
   129608           }
   129609           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   129610             nThisLcs++;
   129611           }else{
   129612             nThisLcs = 1;
   129613           }
   129614           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   129615         }
   129616       }
   129617       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   129618     }
   129619 
   129620     pInfo->aMatchinfo[iCol] = nLcs;
   129621   }
   129622 
   129623   sqlite3_free(aIter);
   129624   return SQLITE_OK;
   129625 }
   129626 
   129627 /*
   129628 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   129629 ** be returned by the matchinfo() function. Argument zArg contains the
   129630 ** format string passed as the second argument to matchinfo (or the
   129631 ** default value "pcx" if no second argument was specified). The format
   129632 ** string has already been validated and the pInfo->aMatchinfo[] array
   129633 ** is guaranteed to be large enough for the output.
   129634 **
   129635 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   129636 ** If it is false, then assume that those fields that do not change between
   129637 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   129638 ** have already been populated.
   129639 **
   129640 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   129641 ** occurs. If a value other than SQLITE_OK is returned, the state the
   129642 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   129643 */
   129644 static int fts3MatchinfoValues(
   129645   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   129646   int bGlobal,                    /* True to grab the global stats */
   129647   MatchInfo *pInfo,               /* Matchinfo context object */
   129648   const char *zArg                /* Matchinfo format string */
   129649 ){
   129650   int rc = SQLITE_OK;
   129651   int i;
   129652   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129653   sqlite3_stmt *pSelect = 0;
   129654 
   129655   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   129656 
   129657     switch( zArg[i] ){
   129658       case FTS3_MATCHINFO_NPHRASE:
   129659         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   129660         break;
   129661 
   129662       case FTS3_MATCHINFO_NCOL:
   129663         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   129664         break;
   129665 
   129666       case FTS3_MATCHINFO_NDOC:
   129667         if( bGlobal ){
   129668           sqlite3_int64 nDoc = 0;
   129669           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   129670           pInfo->aMatchinfo[0] = (u32)nDoc;
   129671         }
   129672         break;
   129673 
   129674       case FTS3_MATCHINFO_AVGLENGTH:
   129675         if( bGlobal ){
   129676           sqlite3_int64 nDoc;     /* Number of rows in table */
   129677           const char *a;          /* Aggregate column length array */
   129678 
   129679           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   129680           if( rc==SQLITE_OK ){
   129681             int iCol;
   129682             for(iCol=0; iCol<pInfo->nCol; iCol++){
   129683               u32 iVal;
   129684               sqlite3_int64 nToken;
   129685               a += sqlite3Fts3GetVarint(a, &nToken);
   129686               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   129687               pInfo->aMatchinfo[iCol] = iVal;
   129688             }
   129689           }
   129690         }
   129691         break;
   129692 
   129693       case FTS3_MATCHINFO_LENGTH: {
   129694         sqlite3_stmt *pSelectDocsize = 0;
   129695         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   129696         if( rc==SQLITE_OK ){
   129697           int iCol;
   129698           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   129699           for(iCol=0; iCol<pInfo->nCol; iCol++){
   129700             sqlite3_int64 nToken;
   129701             a += sqlite3Fts3GetVarint(a, &nToken);
   129702             pInfo->aMatchinfo[iCol] = (u32)nToken;
   129703           }
   129704         }
   129705         sqlite3_reset(pSelectDocsize);
   129706         break;
   129707       }
   129708 
   129709       case FTS3_MATCHINFO_LCS:
   129710         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   129711         if( rc==SQLITE_OK ){
   129712           rc = fts3MatchinfoLcs(pCsr, pInfo);
   129713         }
   129714         break;
   129715 
   129716       default: {
   129717         Fts3Expr *pExpr;
   129718         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   129719         pExpr = pCsr->pExpr;
   129720         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   129721         if( rc!=SQLITE_OK ) break;
   129722         if( bGlobal ){
   129723           if( pCsr->pDeferred ){
   129724             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   129725             if( rc!=SQLITE_OK ) break;
   129726           }
   129727           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   129728           if( rc!=SQLITE_OK ) break;
   129729         }
   129730         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   129731         break;
   129732       }
   129733     }
   129734 
   129735     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   129736   }
   129737 
   129738   sqlite3_reset(pSelect);
   129739   return rc;
   129740 }
   129741 
   129742 
   129743 /*
   129744 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   129745 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   129746 */
   129747 static int fts3GetMatchinfo(
   129748   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   129749   const char *zArg                /* Second argument to matchinfo() function */
   129750 ){
   129751   MatchInfo sInfo;
   129752   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129753   int rc = SQLITE_OK;
   129754   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   129755 
   129756   memset(&sInfo, 0, sizeof(MatchInfo));
   129757   sInfo.pCursor = pCsr;
   129758   sInfo.nCol = pTab->nColumn;
   129759 
   129760   /* If there is cached matchinfo() data, but the format string for the
   129761   ** cache does not match the format string for this request, discard
   129762   ** the cached data. */
   129763   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
   129764     assert( pCsr->aMatchinfo );
   129765     sqlite3_free(pCsr->aMatchinfo);
   129766     pCsr->zMatchinfo = 0;
   129767     pCsr->aMatchinfo = 0;
   129768   }
   129769 
   129770   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
   129771   ** matchinfo function has been called for this query. In this case
   129772   ** allocate the array used to accumulate the matchinfo data and
   129773   ** initialize those elements that are constant for every row.
   129774   */
   129775   if( pCsr->aMatchinfo==0 ){
   129776     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   129777     int nArg;                     /* Bytes in zArg */
   129778     int i;                        /* Used to iterate through zArg */
   129779 
   129780     /* Determine the number of phrases in the query */
   129781     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   129782     sInfo.nPhrase = pCsr->nPhrase;
   129783 
   129784     /* Determine the number of integers in the buffer returned by this call. */
   129785     for(i=0; zArg[i]; i++){
   129786       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   129787     }
   129788 
   129789     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   129790     nArg = (int)strlen(zArg);
   129791     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
   129792     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
   129793 
   129794     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
   129795     pCsr->nMatchinfo = nMatchinfo;
   129796     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
   129797     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
   129798     pCsr->isMatchinfoNeeded = 1;
   129799     bGlobal = 1;
   129800   }
   129801 
   129802   sInfo.aMatchinfo = pCsr->aMatchinfo;
   129803   sInfo.nPhrase = pCsr->nPhrase;
   129804   if( pCsr->isMatchinfoNeeded ){
   129805     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   129806     pCsr->isMatchinfoNeeded = 0;
   129807   }
   129808 
   129809   return rc;
   129810 }
   129811 
   129812 /*
   129813 ** Implementation of snippet() function.
   129814 */
   129815 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   129816   sqlite3_context *pCtx,          /* SQLite function call context */
   129817   Fts3Cursor *pCsr,               /* Cursor object */
   129818   const char *zStart,             /* Snippet start text - "<b>" */
   129819   const char *zEnd,               /* Snippet end text - "</b>" */
   129820   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   129821   int iCol,                       /* Extract snippet from this column */
   129822   int nToken                      /* Approximate number of tokens in snippet */
   129823 ){
   129824   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129825   int rc = SQLITE_OK;
   129826   int i;
   129827   StrBuffer res = {0, 0, 0};
   129828 
   129829   /* The returned text includes up to four fragments of text extracted from
   129830   ** the data in the current row. The first iteration of the for(...) loop
   129831   ** below attempts to locate a single fragment of text nToken tokens in
   129832   ** size that contains at least one instance of all phrases in the query
   129833   ** expression that appear in the current row. If such a fragment of text
   129834   ** cannot be found, the second iteration of the loop attempts to locate
   129835   ** a pair of fragments, and so on.
   129836   */
   129837   int nSnippet = 0;               /* Number of fragments in this snippet */
   129838   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   129839   int nFToken = -1;               /* Number of tokens in each fragment */
   129840 
   129841   if( !pCsr->pExpr ){
   129842     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   129843     return;
   129844   }
   129845 
   129846   for(nSnippet=1; 1; nSnippet++){
   129847 
   129848     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   129849     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   129850     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   129851 
   129852     if( nToken>=0 ){
   129853       nFToken = (nToken+nSnippet-1) / nSnippet;
   129854     }else{
   129855       nFToken = -1 * nToken;
   129856     }
   129857 
   129858     for(iSnip=0; iSnip<nSnippet; iSnip++){
   129859       int iBestScore = -1;        /* Best score of columns checked so far */
   129860       int iRead;                  /* Used to iterate through columns */
   129861       SnippetFragment *pFragment = &aSnippet[iSnip];
   129862 
   129863       memset(pFragment, 0, sizeof(*pFragment));
   129864 
   129865       /* Loop through all columns of the table being considered for snippets.
   129866       ** If the iCol argument to this function was negative, this means all
   129867       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   129868       */
   129869       for(iRead=0; iRead<pTab->nColumn; iRead++){
   129870         SnippetFragment sF = {0, 0, 0, 0};
   129871         int iS;
   129872         if( iCol>=0 && iRead!=iCol ) continue;
   129873 
   129874         /* Find the best snippet of nFToken tokens in column iRead. */
   129875         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   129876         if( rc!=SQLITE_OK ){
   129877           goto snippet_out;
   129878         }
   129879         if( iS>iBestScore ){
   129880           *pFragment = sF;
   129881           iBestScore = iS;
   129882         }
   129883       }
   129884 
   129885       mCovered |= pFragment->covered;
   129886     }
   129887 
   129888     /* If all query phrases seen by fts3BestSnippet() are present in at least
   129889     ** one of the nSnippet snippet fragments, break out of the loop.
   129890     */
   129891     assert( (mCovered&mSeen)==mCovered );
   129892     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   129893   }
   129894 
   129895   assert( nFToken>0 );
   129896 
   129897   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   129898     rc = fts3SnippetText(pCsr, &aSnippet[i],
   129899         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   129900     );
   129901   }
   129902 
   129903  snippet_out:
   129904   sqlite3Fts3SegmentsClose(pTab);
   129905   if( rc!=SQLITE_OK ){
   129906     sqlite3_result_error_code(pCtx, rc);
   129907     sqlite3_free(res.z);
   129908   }else{
   129909     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   129910   }
   129911 }
   129912 
   129913 
   129914 typedef struct TermOffset TermOffset;
   129915 typedef struct TermOffsetCtx TermOffsetCtx;
   129916 
   129917 struct TermOffset {
   129918   char *pList;                    /* Position-list */
   129919   int iPos;                       /* Position just read from pList */
   129920   int iOff;                       /* Offset of this term from read positions */
   129921 };
   129922 
   129923 struct TermOffsetCtx {
   129924   Fts3Cursor *pCsr;
   129925   int iCol;                       /* Column of table to populate aTerm for */
   129926   int iTerm;
   129927   sqlite3_int64 iDocid;
   129928   TermOffset *aTerm;
   129929 };
   129930 
   129931 /*
   129932 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   129933 */
   129934 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   129935   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   129936   int nTerm;                      /* Number of tokens in phrase */
   129937   int iTerm;                      /* For looping through nTerm phrase terms */
   129938   char *pList;                    /* Pointer to position list for phrase */
   129939   int iPos = 0;                   /* First position in position-list */
   129940 
   129941   UNUSED_PARAMETER(iPhrase);
   129942   pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
   129943   nTerm = pExpr->pPhrase->nToken;
   129944   if( pList ){
   129945     fts3GetDeltaPosition(&pList, &iPos);
   129946     assert( iPos>=0 );
   129947   }
   129948 
   129949   for(iTerm=0; iTerm<nTerm; iTerm++){
   129950     TermOffset *pT = &p->aTerm[p->iTerm++];
   129951     pT->iOff = nTerm-iTerm-1;
   129952     pT->pList = pList;
   129953     pT->iPos = iPos;
   129954   }
   129955 
   129956   return SQLITE_OK;
   129957 }
   129958 
   129959 /*
   129960 ** Implementation of offsets() function.
   129961 */
   129962 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   129963   sqlite3_context *pCtx,          /* SQLite function call context */
   129964   Fts3Cursor *pCsr                /* Cursor object */
   129965 ){
   129966   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   129967   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   129968   const char *ZDUMMY;             /* Dummy argument used with xNext() */
   129969   int NDUMMY;                     /* Dummy argument used with xNext() */
   129970   int rc;                         /* Return Code */
   129971   int nToken;                     /* Number of tokens in query */
   129972   int iCol;                       /* Column currently being processed */
   129973   StrBuffer res = {0, 0, 0};      /* Result string */
   129974   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   129975 
   129976   if( !pCsr->pExpr ){
   129977     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   129978     return;
   129979   }
   129980 
   129981   memset(&sCtx, 0, sizeof(sCtx));
   129982   assert( pCsr->isRequireSeek==0 );
   129983 
   129984   /* Count the number of terms in the query */
   129985   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   129986   if( rc!=SQLITE_OK ) goto offsets_out;
   129987 
   129988   /* Allocate the array of TermOffset iterators. */
   129989   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   129990   if( 0==sCtx.aTerm ){
   129991     rc = SQLITE_NOMEM;
   129992     goto offsets_out;
   129993   }
   129994   sCtx.iDocid = pCsr->iPrevId;
   129995   sCtx.pCsr = pCsr;
   129996 
   129997   /* Loop through the table columns, appending offset information to
   129998   ** string-buffer res for each column.
   129999   */
   130000   for(iCol=0; iCol<pTab->nColumn; iCol++){
   130001     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   130002     int iStart;
   130003     int iEnd;
   130004     int iCurrent;
   130005     const char *zDoc;
   130006     int nDoc;
   130007 
   130008     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   130009     ** no way that this operation can fail, so the return code from
   130010     ** fts3ExprIterate() can be discarded.
   130011     */
   130012     sCtx.iCol = iCol;
   130013     sCtx.iTerm = 0;
   130014     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
   130015 
   130016     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   130017     ** in column iCol, jump immediately to the next iteration of the loop.
   130018     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   130019     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   130020     ** to the caller.
   130021     */
   130022     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   130023     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   130024     if( zDoc==0 ){
   130025       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   130026         continue;
   130027       }
   130028       rc = SQLITE_NOMEM;
   130029       goto offsets_out;
   130030     }
   130031 
   130032     /* Initialize a tokenizer iterator to iterate through column iCol. */
   130033     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
   130034         zDoc, nDoc, &pC
   130035     );
   130036     if( rc!=SQLITE_OK ) goto offsets_out;
   130037 
   130038     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   130039     while( rc==SQLITE_OK ){
   130040       int i;                      /* Used to loop through terms */
   130041       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   130042       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   130043 
   130044       for(i=0; i<nToken; i++){
   130045         TermOffset *pT = &sCtx.aTerm[i];
   130046         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   130047           iMinPos = pT->iPos-pT->iOff;
   130048           pTerm = pT;
   130049         }
   130050       }
   130051 
   130052       if( !pTerm ){
   130053         /* All offsets for this column have been gathered. */
   130054         rc = SQLITE_DONE;
   130055       }else{
   130056         assert( iCurrent<=iMinPos );
   130057         if( 0==(0xFE&*pTerm->pList) ){
   130058           pTerm->pList = 0;
   130059         }else{
   130060           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   130061         }
   130062         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   130063           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   130064         }
   130065         if( rc==SQLITE_OK ){
   130066           char aBuffer[64];
   130067           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   130068               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   130069           );
   130070           rc = fts3StringAppend(&res, aBuffer, -1);
   130071         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
   130072           rc = FTS_CORRUPT_VTAB;
   130073         }
   130074       }
   130075     }
   130076     if( rc==SQLITE_DONE ){
   130077       rc = SQLITE_OK;
   130078     }
   130079 
   130080     pMod->xClose(pC);
   130081     if( rc!=SQLITE_OK ) goto offsets_out;
   130082   }
   130083 
   130084  offsets_out:
   130085   sqlite3_free(sCtx.aTerm);
   130086   assert( rc!=SQLITE_DONE );
   130087   sqlite3Fts3SegmentsClose(pTab);
   130088   if( rc!=SQLITE_OK ){
   130089     sqlite3_result_error_code(pCtx,  rc);
   130090     sqlite3_free(res.z);
   130091   }else{
   130092     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   130093   }
   130094   return;
   130095 }
   130096 
   130097 /*
   130098 ** Implementation of matchinfo() function.
   130099 */
   130100 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   130101   sqlite3_context *pContext,      /* Function call context */
   130102   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   130103   const char *zArg                /* Second arg to matchinfo() function */
   130104 ){
   130105   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   130106   int rc;
   130107   int i;
   130108   const char *zFormat;
   130109 
   130110   if( zArg ){
   130111     for(i=0; zArg[i]; i++){
   130112       char *zErr = 0;
   130113       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   130114         sqlite3_result_error(pContext, zErr, -1);
   130115         sqlite3_free(zErr);
   130116         return;
   130117       }
   130118     }
   130119     zFormat = zArg;
   130120   }else{
   130121     zFormat = FTS3_MATCHINFO_DEFAULT;
   130122   }
   130123 
   130124   if( !pCsr->pExpr ){
   130125     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   130126     return;
   130127   }
   130128 
   130129   /* Retrieve matchinfo() data. */
   130130   rc = fts3GetMatchinfo(pCsr, zFormat);
   130131   sqlite3Fts3SegmentsClose(pTab);
   130132 
   130133   if( rc!=SQLITE_OK ){
   130134     sqlite3_result_error_code(pContext, rc);
   130135   }else{
   130136     int n = pCsr->nMatchinfo * sizeof(u32);
   130137     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   130138   }
   130139 }
   130140 
   130141 #endif
   130142 
   130143 /************** End of fts3_snippet.c ****************************************/
   130144 /************** Begin file rtree.c *******************************************/
   130145 /*
   130146 ** 2001 September 15
   130147 **
   130148 ** The author disclaims copyright to this source code.  In place of
   130149 ** a legal notice, here is a blessing:
   130150 **
   130151 **    May you do good and not evil.
   130152 **    May you find forgiveness for yourself and forgive others.
   130153 **    May you share freely, never taking more than you give.
   130154 **
   130155 *************************************************************************
   130156 ** This file contains code for implementations of the r-tree and r*-tree
   130157 ** algorithms packaged as an SQLite virtual table module.
   130158 */
   130159 
   130160 /*
   130161 ** Database Format of R-Tree Tables
   130162 ** --------------------------------
   130163 **
   130164 ** The data structure for a single virtual r-tree table is stored in three
   130165 ** native SQLite tables declared as follows. In each case, the '%' character
   130166 ** in the table name is replaced with the user-supplied name of the r-tree
   130167 ** table.
   130168 **
   130169 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   130170 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   130171 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   130172 **
   130173 ** The data for each node of the r-tree structure is stored in the %_node
   130174 ** table. For each node that is not the root node of the r-tree, there is
   130175 ** an entry in the %_parent table associating the node with its parent.
   130176 ** And for each row of data in the table, there is an entry in the %_rowid
   130177 ** table that maps from the entries rowid to the id of the node that it
   130178 ** is stored on.
   130179 **
   130180 ** The root node of an r-tree always exists, even if the r-tree table is
   130181 ** empty. The nodeno of the root node is always 1. All other nodes in the
   130182 ** table must be the same size as the root node. The content of each node
   130183 ** is formatted as follows:
   130184 **
   130185 **   1. If the node is the root node (node 1), then the first 2 bytes
   130186 **      of the node contain the tree depth as a big-endian integer.
   130187 **      For non-root nodes, the first 2 bytes are left unused.
   130188 **
   130189 **   2. The next 2 bytes contain the number of entries currently
   130190 **      stored in the node.
   130191 **
   130192 **   3. The remainder of the node contains the node entries. Each entry
   130193 **      consists of a single 8-byte integer followed by an even number
   130194 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   130195 **      of a record. For internal nodes it is the node number of a
   130196 **      child page.
   130197 */
   130198 
   130199 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   130200 
   130201 /*
   130202 ** This file contains an implementation of a couple of different variants
   130203 ** of the r-tree algorithm. See the README file for further details. The
   130204 ** same data-structure is used for all, but the algorithms for insert and
   130205 ** delete operations vary. The variants used are selected at compile time
   130206 ** by defining the following symbols:
   130207 */
   130208 
   130209 /* Either, both or none of the following may be set to activate
   130210 ** r*tree variant algorithms.
   130211 */
   130212 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
   130213 #define VARIANT_RSTARTREE_REINSERT      1
   130214 
   130215 /*
   130216 ** Exactly one of the following must be set to 1.
   130217 */
   130218 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
   130219 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
   130220 #define VARIANT_RSTARTREE_SPLIT         1
   130221 
   130222 #define VARIANT_GUTTMAN_SPLIT \
   130223         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
   130224 
   130225 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   130226   #define PickNext QuadraticPickNext
   130227   #define PickSeeds QuadraticPickSeeds
   130228   #define AssignCells splitNodeGuttman
   130229 #endif
   130230 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   130231   #define PickNext LinearPickNext
   130232   #define PickSeeds LinearPickSeeds
   130233   #define AssignCells splitNodeGuttman
   130234 #endif
   130235 #if VARIANT_RSTARTREE_SPLIT
   130236   #define AssignCells splitNodeStartree
   130237 #endif
   130238 
   130239 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   130240 # define NDEBUG 1
   130241 #endif
   130242 
   130243 #ifndef SQLITE_CORE
   130244   SQLITE_EXTENSION_INIT1
   130245 #else
   130246 #endif
   130247 
   130248 /* #include <string.h> */
   130249 /* #include <assert.h> */
   130250 
   130251 #ifndef SQLITE_AMALGAMATION
   130252 #include "sqlite3rtree.h"
   130253 typedef sqlite3_int64 i64;
   130254 typedef unsigned char u8;
   130255 typedef unsigned int u32;
   130256 #endif
   130257 
   130258 /*  The following macro is used to suppress compiler warnings.
   130259 */
   130260 #ifndef UNUSED_PARAMETER
   130261 # define UNUSED_PARAMETER(x) (void)(x)
   130262 #endif
   130263 
   130264 typedef struct Rtree Rtree;
   130265 typedef struct RtreeCursor RtreeCursor;
   130266 typedef struct RtreeNode RtreeNode;
   130267 typedef struct RtreeCell RtreeCell;
   130268 typedef struct RtreeConstraint RtreeConstraint;
   130269 typedef struct RtreeMatchArg RtreeMatchArg;
   130270 typedef struct RtreeGeomCallback RtreeGeomCallback;
   130271 typedef union RtreeCoord RtreeCoord;
   130272 
   130273 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   130274 #define RTREE_MAX_DIMENSIONS 5
   130275 
   130276 /* Size of hash table Rtree.aHash. This hash table is not expected to
   130277 ** ever contain very many entries, so a fixed number of buckets is
   130278 ** used.
   130279 */
   130280 #define HASHSIZE 128
   130281 
   130282 /*
   130283 ** An rtree virtual-table object.
   130284 */
   130285 struct Rtree {
   130286   sqlite3_vtab base;
   130287   sqlite3 *db;                /* Host database connection */
   130288   int iNodeSize;              /* Size in bytes of each node in the node table */
   130289   int nDim;                   /* Number of dimensions */
   130290   int nBytesPerCell;          /* Bytes consumed per cell */
   130291   int iDepth;                 /* Current depth of the r-tree structure */
   130292   char *zDb;                  /* Name of database containing r-tree table */
   130293   char *zName;                /* Name of r-tree table */
   130294   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   130295   int nBusy;                  /* Current number of users of this structure */
   130296 
   130297   /* List of nodes removed during a CondenseTree operation. List is
   130298   ** linked together via the pointer normally used for hash chains -
   130299   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   130300   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   130301   */
   130302   RtreeNode *pDeleted;
   130303   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   130304 
   130305   /* Statements to read/write/delete a record from xxx_node */
   130306   sqlite3_stmt *pReadNode;
   130307   sqlite3_stmt *pWriteNode;
   130308   sqlite3_stmt *pDeleteNode;
   130309 
   130310   /* Statements to read/write/delete a record from xxx_rowid */
   130311   sqlite3_stmt *pReadRowid;
   130312   sqlite3_stmt *pWriteRowid;
   130313   sqlite3_stmt *pDeleteRowid;
   130314 
   130315   /* Statements to read/write/delete a record from xxx_parent */
   130316   sqlite3_stmt *pReadParent;
   130317   sqlite3_stmt *pWriteParent;
   130318   sqlite3_stmt *pDeleteParent;
   130319 
   130320   int eCoordType;
   130321 };
   130322 
   130323 /* Possible values for eCoordType: */
   130324 #define RTREE_COORD_REAL32 0
   130325 #define RTREE_COORD_INT32  1
   130326 
   130327 /*
   130328 ** The minimum number of cells allowed for a node is a third of the
   130329 ** maximum. In Gutman's notation:
   130330 **
   130331 **     m = M/3
   130332 **
   130333 ** If an R*-tree "Reinsert" operation is required, the same number of
   130334 ** cells are removed from the overfull node and reinserted into the tree.
   130335 */
   130336 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   130337 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   130338 #define RTREE_MAXCELLS 51
   130339 
   130340 /*
   130341 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   130342 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   130343 ** Therefore all non-root nodes must contain at least 3 entries. Since
   130344 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
   130345 ** 40 or less.
   130346 */
   130347 #define RTREE_MAX_DEPTH 40
   130348 
   130349 /*
   130350 ** An rtree cursor object.
   130351 */
   130352 struct RtreeCursor {
   130353   sqlite3_vtab_cursor base;
   130354   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
   130355   int iCell;                        /* Index of current cell in pNode */
   130356   int iStrategy;                    /* Copy of idxNum search parameter */
   130357   int nConstraint;                  /* Number of entries in aConstraint */
   130358   RtreeConstraint *aConstraint;     /* Search constraints. */
   130359 };
   130360 
   130361 union RtreeCoord {
   130362   float f;
   130363   int i;
   130364 };
   130365 
   130366 /*
   130367 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   130368 ** formatted as a double. This macro assumes that local variable pRtree points
   130369 ** to the Rtree structure associated with the RtreeCoord.
   130370 */
   130371 #define DCOORD(coord) (                           \
   130372   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   130373     ((double)coord.f) :                           \
   130374     ((double)coord.i)                             \
   130375 )
   130376 
   130377 /*
   130378 ** A search constraint.
   130379 */
   130380 struct RtreeConstraint {
   130381   int iCoord;                     /* Index of constrained coordinate */
   130382   int op;                         /* Constraining operation */
   130383   double rValue;                  /* Constraint value. */
   130384   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130385   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
   130386 };
   130387 
   130388 /* Possible values for RtreeConstraint.op */
   130389 #define RTREE_EQ    0x41
   130390 #define RTREE_LE    0x42
   130391 #define RTREE_LT    0x43
   130392 #define RTREE_GE    0x44
   130393 #define RTREE_GT    0x45
   130394 #define RTREE_MATCH 0x46
   130395 
   130396 /*
   130397 ** An rtree structure node.
   130398 */
   130399 struct RtreeNode {
   130400   RtreeNode *pParent;               /* Parent node */
   130401   i64 iNode;
   130402   int nRef;
   130403   int isDirty;
   130404   u8 *zData;
   130405   RtreeNode *pNext;                 /* Next node in this hash chain */
   130406 };
   130407 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   130408 
   130409 /*
   130410 ** Structure to store a deserialized rtree record.
   130411 */
   130412 struct RtreeCell {
   130413   i64 iRowid;
   130414   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
   130415 };
   130416 
   130417 
   130418 /*
   130419 ** Value for the first field of every RtreeMatchArg object. The MATCH
   130420 ** operator tests that the first field of a blob operand matches this
   130421 ** value to avoid operating on invalid blobs (which could cause a segfault).
   130422 */
   130423 #define RTREE_GEOMETRY_MAGIC 0x891245AB
   130424 
   130425 /*
   130426 ** An instance of this structure must be supplied as a blob argument to
   130427 ** the right-hand-side of an SQL MATCH operator used to constrain an
   130428 ** r-tree query.
   130429 */
   130430 struct RtreeMatchArg {
   130431   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
   130432   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130433   void *pContext;
   130434   int nParam;
   130435   double aParam[1];
   130436 };
   130437 
   130438 /*
   130439 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
   130440 ** a single instance of the following structure is allocated. It is used
   130441 ** as the context for the user-function created by by s_r_g_c(). The object
   130442 ** is eventually deleted by the destructor mechanism provided by
   130443 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
   130444 ** the geometry callback function).
   130445 */
   130446 struct RtreeGeomCallback {
   130447   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   130448   void *pContext;
   130449 };
   130450 
   130451 #ifndef MAX
   130452 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   130453 #endif
   130454 #ifndef MIN
   130455 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   130456 #endif
   130457 
   130458 /*
   130459 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   130460 ** 64 bit integer. The deserialized value is returned.
   130461 */
   130462 static int readInt16(u8 *p){
   130463   return (p[0]<<8) + p[1];
   130464 }
   130465 static void readCoord(u8 *p, RtreeCoord *pCoord){
   130466   u32 i = (
   130467     (((u32)p[0]) << 24) +
   130468     (((u32)p[1]) << 16) +
   130469     (((u32)p[2]) <<  8) +
   130470     (((u32)p[3]) <<  0)
   130471   );
   130472   *(u32 *)pCoord = i;
   130473 }
   130474 static i64 readInt64(u8 *p){
   130475   return (
   130476     (((i64)p[0]) << 56) +
   130477     (((i64)p[1]) << 48) +
   130478     (((i64)p[2]) << 40) +
   130479     (((i64)p[3]) << 32) +
   130480     (((i64)p[4]) << 24) +
   130481     (((i64)p[5]) << 16) +
   130482     (((i64)p[6]) <<  8) +
   130483     (((i64)p[7]) <<  0)
   130484   );
   130485 }
   130486 
   130487 /*
   130488 ** Functions to serialize a 16 bit integer, 32 bit real number and
   130489 ** 64 bit integer. The value returned is the number of bytes written
   130490 ** to the argument buffer (always 2, 4 and 8 respectively).
   130491 */
   130492 static int writeInt16(u8 *p, int i){
   130493   p[0] = (i>> 8)&0xFF;
   130494   p[1] = (i>> 0)&0xFF;
   130495   return 2;
   130496 }
   130497 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   130498   u32 i;
   130499   assert( sizeof(RtreeCoord)==4 );
   130500   assert( sizeof(u32)==4 );
   130501   i = *(u32 *)pCoord;
   130502   p[0] = (i>>24)&0xFF;
   130503   p[1] = (i>>16)&0xFF;
   130504   p[2] = (i>> 8)&0xFF;
   130505   p[3] = (i>> 0)&0xFF;
   130506   return 4;
   130507 }
   130508 static int writeInt64(u8 *p, i64 i){
   130509   p[0] = (i>>56)&0xFF;
   130510   p[1] = (i>>48)&0xFF;
   130511   p[2] = (i>>40)&0xFF;
   130512   p[3] = (i>>32)&0xFF;
   130513   p[4] = (i>>24)&0xFF;
   130514   p[5] = (i>>16)&0xFF;
   130515   p[6] = (i>> 8)&0xFF;
   130516   p[7] = (i>> 0)&0xFF;
   130517   return 8;
   130518 }
   130519 
   130520 /*
   130521 ** Increment the reference count of node p.
   130522 */
   130523 static void nodeReference(RtreeNode *p){
   130524   if( p ){
   130525     p->nRef++;
   130526   }
   130527 }
   130528 
   130529 /*
   130530 ** Clear the content of node p (set all bytes to 0x00).
   130531 */
   130532 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   130533   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   130534   p->isDirty = 1;
   130535 }
   130536 
   130537 /*
   130538 ** Given a node number iNode, return the corresponding key to use
   130539 ** in the Rtree.aHash table.
   130540 */
   130541 static int nodeHash(i64 iNode){
   130542   return (
   130543     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
   130544     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
   130545   ) % HASHSIZE;
   130546 }
   130547 
   130548 /*
   130549 ** Search the node hash table for node iNode. If found, return a pointer
   130550 ** to it. Otherwise, return 0.
   130551 */
   130552 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   130553   RtreeNode *p;
   130554   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   130555   return p;
   130556 }
   130557 
   130558 /*
   130559 ** Add node pNode to the node hash table.
   130560 */
   130561 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   130562   int iHash;
   130563   assert( pNode->pNext==0 );
   130564   iHash = nodeHash(pNode->iNode);
   130565   pNode->pNext = pRtree->aHash[iHash];
   130566   pRtree->aHash[iHash] = pNode;
   130567 }
   130568 
   130569 /*
   130570 ** Remove node pNode from the node hash table.
   130571 */
   130572 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   130573   RtreeNode **pp;
   130574   if( pNode->iNode!=0 ){
   130575     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   130576     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   130577     *pp = pNode->pNext;
   130578     pNode->pNext = 0;
   130579   }
   130580 }
   130581 
   130582 /*
   130583 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   130584 ** indicating that node has not yet been assigned a node number. It is
   130585 ** assigned a node number when nodeWrite() is called to write the
   130586 ** node contents out to the database.
   130587 */
   130588 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   130589   RtreeNode *pNode;
   130590   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   130591   if( pNode ){
   130592     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   130593     pNode->zData = (u8 *)&pNode[1];
   130594     pNode->nRef = 1;
   130595     pNode->pParent = pParent;
   130596     pNode->isDirty = 1;
   130597     nodeReference(pParent);
   130598   }
   130599   return pNode;
   130600 }
   130601 
   130602 /*
   130603 ** Obtain a reference to an r-tree node.
   130604 */
   130605 static int
   130606 nodeAcquire(
   130607   Rtree *pRtree,             /* R-tree structure */
   130608   i64 iNode,                 /* Node number to load */
   130609   RtreeNode *pParent,        /* Either the parent node or NULL */
   130610   RtreeNode **ppNode         /* OUT: Acquired node */
   130611 ){
   130612   int rc;
   130613   int rc2 = SQLITE_OK;
   130614   RtreeNode *pNode;
   130615 
   130616   /* Check if the requested node is already in the hash table. If so,
   130617   ** increase its reference count and return it.
   130618   */
   130619   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   130620     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   130621     if( pParent && !pNode->pParent ){
   130622       nodeReference(pParent);
   130623       pNode->pParent = pParent;
   130624     }
   130625     pNode->nRef++;
   130626     *ppNode = pNode;
   130627     return SQLITE_OK;
   130628   }
   130629 
   130630   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   130631   rc = sqlite3_step(pRtree->pReadNode);
   130632   if( rc==SQLITE_ROW ){
   130633     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   130634     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
   130635       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   130636       if( !pNode ){
   130637         rc2 = SQLITE_NOMEM;
   130638       }else{
   130639         pNode->pParent = pParent;
   130640         pNode->zData = (u8 *)&pNode[1];
   130641         pNode->nRef = 1;
   130642         pNode->iNode = iNode;
   130643         pNode->isDirty = 0;
   130644         pNode->pNext = 0;
   130645         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   130646         nodeReference(pParent);
   130647       }
   130648     }
   130649   }
   130650   rc = sqlite3_reset(pRtree->pReadNode);
   130651   if( rc==SQLITE_OK ) rc = rc2;
   130652 
   130653   /* If the root node was just loaded, set pRtree->iDepth to the height
   130654   ** of the r-tree structure. A height of zero means all data is stored on
   130655   ** the root node. A height of one means the children of the root node
   130656   ** are the leaves, and so on. If the depth as specified on the root node
   130657   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   130658   */
   130659   if( pNode && iNode==1 ){
   130660     pRtree->iDepth = readInt16(pNode->zData);
   130661     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   130662       rc = SQLITE_CORRUPT_VTAB;
   130663     }
   130664   }
   130665 
   130666   /* If no error has occurred so far, check if the "number of entries"
   130667   ** field on the node is too large. If so, set the return code to
   130668   ** SQLITE_CORRUPT_VTAB.
   130669   */
   130670   if( pNode && rc==SQLITE_OK ){
   130671     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   130672       rc = SQLITE_CORRUPT_VTAB;
   130673     }
   130674   }
   130675 
   130676   if( rc==SQLITE_OK ){
   130677     if( pNode!=0 ){
   130678       nodeHashInsert(pRtree, pNode);
   130679     }else{
   130680       rc = SQLITE_CORRUPT_VTAB;
   130681     }
   130682     *ppNode = pNode;
   130683   }else{
   130684     sqlite3_free(pNode);
   130685     *ppNode = 0;
   130686   }
   130687 
   130688   return rc;
   130689 }
   130690 
   130691 /*
   130692 ** Overwrite cell iCell of node pNode with the contents of pCell.
   130693 */
   130694 static void nodeOverwriteCell(
   130695   Rtree *pRtree,
   130696   RtreeNode *pNode,
   130697   RtreeCell *pCell,
   130698   int iCell
   130699 ){
   130700   int ii;
   130701   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   130702   p += writeInt64(p, pCell->iRowid);
   130703   for(ii=0; ii<(pRtree->nDim*2); ii++){
   130704     p += writeCoord(p, &pCell->aCoord[ii]);
   130705   }
   130706   pNode->isDirty = 1;
   130707 }
   130708 
   130709 /*
   130710 ** Remove cell the cell with index iCell from node pNode.
   130711 */
   130712 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   130713   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   130714   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   130715   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   130716   memmove(pDst, pSrc, nByte);
   130717   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   130718   pNode->isDirty = 1;
   130719 }
   130720 
   130721 /*
   130722 ** Insert the contents of cell pCell into node pNode. If the insert
   130723 ** is successful, return SQLITE_OK.
   130724 **
   130725 ** If there is not enough free space in pNode, return SQLITE_FULL.
   130726 */
   130727 static int
   130728 nodeInsertCell(
   130729   Rtree *pRtree,
   130730   RtreeNode *pNode,
   130731   RtreeCell *pCell
   130732 ){
   130733   int nCell;                    /* Current number of cells in pNode */
   130734   int nMaxCell;                 /* Maximum number of cells for pNode */
   130735 
   130736   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   130737   nCell = NCELL(pNode);
   130738 
   130739   assert( nCell<=nMaxCell );
   130740   if( nCell<nMaxCell ){
   130741     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   130742     writeInt16(&pNode->zData[2], nCell+1);
   130743     pNode->isDirty = 1;
   130744   }
   130745 
   130746   return (nCell==nMaxCell);
   130747 }
   130748 
   130749 /*
   130750 ** If the node is dirty, write it out to the database.
   130751 */
   130752 static int
   130753 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   130754   int rc = SQLITE_OK;
   130755   if( pNode->isDirty ){
   130756     sqlite3_stmt *p = pRtree->pWriteNode;
   130757     if( pNode->iNode ){
   130758       sqlite3_bind_int64(p, 1, pNode->iNode);
   130759     }else{
   130760       sqlite3_bind_null(p, 1);
   130761     }
   130762     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   130763     sqlite3_step(p);
   130764     pNode->isDirty = 0;
   130765     rc = sqlite3_reset(p);
   130766     if( pNode->iNode==0 && rc==SQLITE_OK ){
   130767       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   130768       nodeHashInsert(pRtree, pNode);
   130769     }
   130770   }
   130771   return rc;
   130772 }
   130773 
   130774 /*
   130775 ** Release a reference to a node. If the node is dirty and the reference
   130776 ** count drops to zero, the node data is written to the database.
   130777 */
   130778 static int
   130779 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   130780   int rc = SQLITE_OK;
   130781   if( pNode ){
   130782     assert( pNode->nRef>0 );
   130783     pNode->nRef--;
   130784     if( pNode->nRef==0 ){
   130785       if( pNode->iNode==1 ){
   130786         pRtree->iDepth = -1;
   130787       }
   130788       if( pNode->pParent ){
   130789         rc = nodeRelease(pRtree, pNode->pParent);
   130790       }
   130791       if( rc==SQLITE_OK ){
   130792         rc = nodeWrite(pRtree, pNode);
   130793       }
   130794       nodeHashDelete(pRtree, pNode);
   130795       sqlite3_free(pNode);
   130796     }
   130797   }
   130798   return rc;
   130799 }
   130800 
   130801 /*
   130802 ** Return the 64-bit integer value associated with cell iCell of
   130803 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   130804 ** an internal node, then the 64-bit integer is a child page number.
   130805 */
   130806 static i64 nodeGetRowid(
   130807   Rtree *pRtree,
   130808   RtreeNode *pNode,
   130809   int iCell
   130810 ){
   130811   assert( iCell<NCELL(pNode) );
   130812   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   130813 }
   130814 
   130815 /*
   130816 ** Return coordinate iCoord from cell iCell in node pNode.
   130817 */
   130818 static void nodeGetCoord(
   130819   Rtree *pRtree,
   130820   RtreeNode *pNode,
   130821   int iCell,
   130822   int iCoord,
   130823   RtreeCoord *pCoord           /* Space to write result to */
   130824 ){
   130825   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   130826 }
   130827 
   130828 /*
   130829 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   130830 ** to by pCell with the results.
   130831 */
   130832 static void nodeGetCell(
   130833   Rtree *pRtree,
   130834   RtreeNode *pNode,
   130835   int iCell,
   130836   RtreeCell *pCell
   130837 ){
   130838   int ii;
   130839   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   130840   for(ii=0; ii<pRtree->nDim*2; ii++){
   130841     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
   130842   }
   130843 }
   130844 
   130845 
   130846 /* Forward declaration for the function that does the work of
   130847 ** the virtual table module xCreate() and xConnect() methods.
   130848 */
   130849 static int rtreeInit(
   130850   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   130851 );
   130852 
   130853 /*
   130854 ** Rtree virtual table module xCreate method.
   130855 */
   130856 static int rtreeCreate(
   130857   sqlite3 *db,
   130858   void *pAux,
   130859   int argc, const char *const*argv,
   130860   sqlite3_vtab **ppVtab,
   130861   char **pzErr
   130862 ){
   130863   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   130864 }
   130865 
   130866 /*
   130867 ** Rtree virtual table module xConnect method.
   130868 */
   130869 static int rtreeConnect(
   130870   sqlite3 *db,
   130871   void *pAux,
   130872   int argc, const char *const*argv,
   130873   sqlite3_vtab **ppVtab,
   130874   char **pzErr
   130875 ){
   130876   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   130877 }
   130878 
   130879 /*
   130880 ** Increment the r-tree reference count.
   130881 */
   130882 static void rtreeReference(Rtree *pRtree){
   130883   pRtree->nBusy++;
   130884 }
   130885 
   130886 /*
   130887 ** Decrement the r-tree reference count. When the reference count reaches
   130888 ** zero the structure is deleted.
   130889 */
   130890 static void rtreeRelease(Rtree *pRtree){
   130891   pRtree->nBusy--;
   130892   if( pRtree->nBusy==0 ){
   130893     sqlite3_finalize(pRtree->pReadNode);
   130894     sqlite3_finalize(pRtree->pWriteNode);
   130895     sqlite3_finalize(pRtree->pDeleteNode);
   130896     sqlite3_finalize(pRtree->pReadRowid);
   130897     sqlite3_finalize(pRtree->pWriteRowid);
   130898     sqlite3_finalize(pRtree->pDeleteRowid);
   130899     sqlite3_finalize(pRtree->pReadParent);
   130900     sqlite3_finalize(pRtree->pWriteParent);
   130901     sqlite3_finalize(pRtree->pDeleteParent);
   130902     sqlite3_free(pRtree);
   130903   }
   130904 }
   130905 
   130906 /*
   130907 ** Rtree virtual table module xDisconnect method.
   130908 */
   130909 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   130910   rtreeRelease((Rtree *)pVtab);
   130911   return SQLITE_OK;
   130912 }
   130913 
   130914 /*
   130915 ** Rtree virtual table module xDestroy method.
   130916 */
   130917 static int rtreeDestroy(sqlite3_vtab *pVtab){
   130918   Rtree *pRtree = (Rtree *)pVtab;
   130919   int rc;
   130920   char *zCreate = sqlite3_mprintf(
   130921     "DROP TABLE '%q'.'%q_node';"
   130922     "DROP TABLE '%q'.'%q_rowid';"
   130923     "DROP TABLE '%q'.'%q_parent';",
   130924     pRtree->zDb, pRtree->zName,
   130925     pRtree->zDb, pRtree->zName,
   130926     pRtree->zDb, pRtree->zName
   130927   );
   130928   if( !zCreate ){
   130929     rc = SQLITE_NOMEM;
   130930   }else{
   130931     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   130932     sqlite3_free(zCreate);
   130933   }
   130934   if( rc==SQLITE_OK ){
   130935     rtreeRelease(pRtree);
   130936   }
   130937 
   130938   return rc;
   130939 }
   130940 
   130941 /*
   130942 ** Rtree virtual table module xOpen method.
   130943 */
   130944 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   130945   int rc = SQLITE_NOMEM;
   130946   RtreeCursor *pCsr;
   130947 
   130948   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   130949   if( pCsr ){
   130950     memset(pCsr, 0, sizeof(RtreeCursor));
   130951     pCsr->base.pVtab = pVTab;
   130952     rc = SQLITE_OK;
   130953   }
   130954   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   130955 
   130956   return rc;
   130957 }
   130958 
   130959 
   130960 /*
   130961 ** Free the RtreeCursor.aConstraint[] array and its contents.
   130962 */
   130963 static void freeCursorConstraints(RtreeCursor *pCsr){
   130964   if( pCsr->aConstraint ){
   130965     int i;                        /* Used to iterate through constraint array */
   130966     for(i=0; i<pCsr->nConstraint; i++){
   130967       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
   130968       if( pGeom ){
   130969         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
   130970         sqlite3_free(pGeom);
   130971       }
   130972     }
   130973     sqlite3_free(pCsr->aConstraint);
   130974     pCsr->aConstraint = 0;
   130975   }
   130976 }
   130977 
   130978 /*
   130979 ** Rtree virtual table module xClose method.
   130980 */
   130981 static int rtreeClose(sqlite3_vtab_cursor *cur){
   130982   Rtree *pRtree = (Rtree *)(cur->pVtab);
   130983   int rc;
   130984   RtreeCursor *pCsr = (RtreeCursor *)cur;
   130985   freeCursorConstraints(pCsr);
   130986   rc = nodeRelease(pRtree, pCsr->pNode);
   130987   sqlite3_free(pCsr);
   130988   return rc;
   130989 }
   130990 
   130991 /*
   130992 ** Rtree virtual table module xEof method.
   130993 **
   130994 ** Return non-zero if the cursor does not currently point to a valid
   130995 ** record (i.e if the scan has finished), or zero otherwise.
   130996 */
   130997 static int rtreeEof(sqlite3_vtab_cursor *cur){
   130998   RtreeCursor *pCsr = (RtreeCursor *)cur;
   130999   return (pCsr->pNode==0);
   131000 }
   131001 
   131002 /*
   131003 ** The r-tree constraint passed as the second argument to this function is
   131004 ** guaranteed to be a MATCH constraint.
   131005 */
   131006 static int testRtreeGeom(
   131007   Rtree *pRtree,                  /* R-Tree object */
   131008   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
   131009   RtreeCell *pCell,               /* Cell to test */
   131010   int *pbRes                      /* OUT: Test result */
   131011 ){
   131012   int i;
   131013   double aCoord[RTREE_MAX_DIMENSIONS*2];
   131014   int nCoord = pRtree->nDim*2;
   131015 
   131016   assert( pConstraint->op==RTREE_MATCH );
   131017   assert( pConstraint->pGeom );
   131018 
   131019   for(i=0; i<nCoord; i++){
   131020     aCoord[i] = DCOORD(pCell->aCoord[i]);
   131021   }
   131022   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
   131023 }
   131024 
   131025 /*
   131026 ** Cursor pCursor currently points to a cell in a non-leaf page.
   131027 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
   131028 ** (excluded) by the constraints in the pCursor->aConstraint[]
   131029 ** array, or false otherwise.
   131030 **
   131031 ** Return SQLITE_OK if successful or an SQLite error code if an error
   131032 ** occurs within a geometry callback.
   131033 */
   131034 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   131035   RtreeCell cell;
   131036   int ii;
   131037   int bRes = 0;
   131038   int rc = SQLITE_OK;
   131039 
   131040   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   131041   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
   131042     RtreeConstraint *p = &pCursor->aConstraint[ii];
   131043     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
   131044     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
   131045 
   131046     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   131047         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   131048     );
   131049 
   131050     switch( p->op ){
   131051       case RTREE_LE: case RTREE_LT:
   131052         bRes = p->rValue<cell_min;
   131053         break;
   131054 
   131055       case RTREE_GE: case RTREE_GT:
   131056         bRes = p->rValue>cell_max;
   131057         break;
   131058 
   131059       case RTREE_EQ:
   131060         bRes = (p->rValue>cell_max || p->rValue<cell_min);
   131061         break;
   131062 
   131063       default: {
   131064         assert( p->op==RTREE_MATCH );
   131065         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
   131066         bRes = !bRes;
   131067         break;
   131068       }
   131069     }
   131070   }
   131071 
   131072   *pbEof = bRes;
   131073   return rc;
   131074 }
   131075 
   131076 /*
   131077 ** Test if the cell that cursor pCursor currently points to
   131078 ** would be filtered (excluded) by the constraints in the
   131079 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
   131080 ** returning. If the cell is not filtered (excluded) by the constraints,
   131081 ** set pbEof to zero.
   131082 **
   131083 ** Return SQLITE_OK if successful or an SQLite error code if an error
   131084 ** occurs within a geometry callback.
   131085 **
   131086 ** This function assumes that the cell is part of a leaf node.
   131087 */
   131088 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   131089   RtreeCell cell;
   131090   int ii;
   131091   *pbEof = 0;
   131092 
   131093   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   131094   for(ii=0; ii<pCursor->nConstraint; ii++){
   131095     RtreeConstraint *p = &pCursor->aConstraint[ii];
   131096     double coord = DCOORD(cell.aCoord[p->iCoord]);
   131097     int res;
   131098     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   131099         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   131100     );
   131101     switch( p->op ){
   131102       case RTREE_LE: res = (coord<=p->rValue); break;
   131103       case RTREE_LT: res = (coord<p->rValue);  break;
   131104       case RTREE_GE: res = (coord>=p->rValue); break;
   131105       case RTREE_GT: res = (coord>p->rValue);  break;
   131106       case RTREE_EQ: res = (coord==p->rValue); break;
   131107       default: {
   131108         int rc;
   131109         assert( p->op==RTREE_MATCH );
   131110         rc = testRtreeGeom(pRtree, p, &cell, &res);
   131111         if( rc!=SQLITE_OK ){
   131112           return rc;
   131113         }
   131114         break;
   131115       }
   131116     }
   131117 
   131118     if( !res ){
   131119       *pbEof = 1;
   131120       return SQLITE_OK;
   131121     }
   131122   }
   131123 
   131124   return SQLITE_OK;
   131125 }
   131126 
   131127 /*
   131128 ** Cursor pCursor currently points at a node that heads a sub-tree of
   131129 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
   131130 ** to point to the left-most cell of the sub-tree that matches the
   131131 ** configured constraints.
   131132 */
   131133 static int descendToCell(
   131134   Rtree *pRtree,
   131135   RtreeCursor *pCursor,
   131136   int iHeight,
   131137   int *pEof                 /* OUT: Set to true if cannot descend */
   131138 ){
   131139   int isEof;
   131140   int rc;
   131141   int ii;
   131142   RtreeNode *pChild;
   131143   sqlite3_int64 iRowid;
   131144 
   131145   RtreeNode *pSavedNode = pCursor->pNode;
   131146   int iSavedCell = pCursor->iCell;
   131147 
   131148   assert( iHeight>=0 );
   131149 
   131150   if( iHeight==0 ){
   131151     rc = testRtreeEntry(pRtree, pCursor, &isEof);
   131152   }else{
   131153     rc = testRtreeCell(pRtree, pCursor, &isEof);
   131154   }
   131155   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
   131156     goto descend_to_cell_out;
   131157   }
   131158 
   131159   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
   131160   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
   131161   if( rc!=SQLITE_OK ){
   131162     goto descend_to_cell_out;
   131163   }
   131164 
   131165   nodeRelease(pRtree, pCursor->pNode);
   131166   pCursor->pNode = pChild;
   131167   isEof = 1;
   131168   for(ii=0; isEof && ii<NCELL(pChild); ii++){
   131169     pCursor->iCell = ii;
   131170     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
   131171     if( rc!=SQLITE_OK ){
   131172       goto descend_to_cell_out;
   131173     }
   131174   }
   131175 
   131176   if( isEof ){
   131177     assert( pCursor->pNode==pChild );
   131178     nodeReference(pSavedNode);
   131179     nodeRelease(pRtree, pChild);
   131180     pCursor->pNode = pSavedNode;
   131181     pCursor->iCell = iSavedCell;
   131182   }
   131183 
   131184 descend_to_cell_out:
   131185   *pEof = isEof;
   131186   return rc;
   131187 }
   131188 
   131189 /*
   131190 ** One of the cells in node pNode is guaranteed to have a 64-bit
   131191 ** integer value equal to iRowid. Return the index of this cell.
   131192 */
   131193 static int nodeRowidIndex(
   131194   Rtree *pRtree,
   131195   RtreeNode *pNode,
   131196   i64 iRowid,
   131197   int *piIndex
   131198 ){
   131199   int ii;
   131200   int nCell = NCELL(pNode);
   131201   for(ii=0; ii<nCell; ii++){
   131202     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   131203       *piIndex = ii;
   131204       return SQLITE_OK;
   131205     }
   131206   }
   131207   return SQLITE_CORRUPT_VTAB;
   131208 }
   131209 
   131210 /*
   131211 ** Return the index of the cell containing a pointer to node pNode
   131212 ** in its parent. If pNode is the root node, return -1.
   131213 */
   131214 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   131215   RtreeNode *pParent = pNode->pParent;
   131216   if( pParent ){
   131217     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   131218   }
   131219   *piIndex = -1;
   131220   return SQLITE_OK;
   131221 }
   131222 
   131223 /*
   131224 ** Rtree virtual table module xNext method.
   131225 */
   131226 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   131227   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
   131228   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131229   int rc = SQLITE_OK;
   131230 
   131231   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
   131232   ** already at EOF. It is against the rules to call the xNext() method of
   131233   ** a cursor that has already reached EOF.
   131234   */
   131235   assert( pCsr->pNode );
   131236 
   131237   if( pCsr->iStrategy==1 ){
   131238     /* This "scan" is a direct lookup by rowid. There is no next entry. */
   131239     nodeRelease(pRtree, pCsr->pNode);
   131240     pCsr->pNode = 0;
   131241   }else{
   131242     /* Move to the next entry that matches the configured constraints. */
   131243     int iHeight = 0;
   131244     while( pCsr->pNode ){
   131245       RtreeNode *pNode = pCsr->pNode;
   131246       int nCell = NCELL(pNode);
   131247       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
   131248         int isEof;
   131249         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
   131250         if( rc!=SQLITE_OK || !isEof ){
   131251           return rc;
   131252         }
   131253       }
   131254       pCsr->pNode = pNode->pParent;
   131255       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
   131256       if( rc!=SQLITE_OK ){
   131257         return rc;
   131258       }
   131259       nodeReference(pCsr->pNode);
   131260       nodeRelease(pRtree, pNode);
   131261       iHeight++;
   131262     }
   131263   }
   131264 
   131265   return rc;
   131266 }
   131267 
   131268 /*
   131269 ** Rtree virtual table module xRowid method.
   131270 */
   131271 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   131272   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   131273   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131274 
   131275   assert(pCsr->pNode);
   131276   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   131277 
   131278   return SQLITE_OK;
   131279 }
   131280 
   131281 /*
   131282 ** Rtree virtual table module xColumn method.
   131283 */
   131284 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   131285   Rtree *pRtree = (Rtree *)cur->pVtab;
   131286   RtreeCursor *pCsr = (RtreeCursor *)cur;
   131287 
   131288   if( i==0 ){
   131289     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   131290     sqlite3_result_int64(ctx, iRowid);
   131291   }else{
   131292     RtreeCoord c;
   131293     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
   131294     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   131295       sqlite3_result_double(ctx, c.f);
   131296     }else{
   131297       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   131298       sqlite3_result_int(ctx, c.i);
   131299     }
   131300   }
   131301 
   131302   return SQLITE_OK;
   131303 }
   131304 
   131305 /*
   131306 ** Use nodeAcquire() to obtain the leaf node containing the record with
   131307 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   131308 ** return SQLITE_OK. If there is no such record in the table, set
   131309 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   131310 ** to zero and return an SQLite error code.
   131311 */
   131312 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
   131313   int rc;
   131314   *ppLeaf = 0;
   131315   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   131316   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   131317     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   131318     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   131319     sqlite3_reset(pRtree->pReadRowid);
   131320   }else{
   131321     rc = sqlite3_reset(pRtree->pReadRowid);
   131322   }
   131323   return rc;
   131324 }
   131325 
   131326 /*
   131327 ** This function is called to configure the RtreeConstraint object passed
   131328 ** as the second argument for a MATCH constraint. The value passed as the
   131329 ** first argument to this function is the right-hand operand to the MATCH
   131330 ** operator.
   131331 */
   131332 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   131333   RtreeMatchArg *p;
   131334   sqlite3_rtree_geometry *pGeom;
   131335   int nBlob;
   131336 
   131337   /* Check that value is actually a blob. */
   131338   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
   131339 
   131340   /* Check that the blob is roughly the right size. */
   131341   nBlob = sqlite3_value_bytes(pValue);
   131342   if( nBlob<(int)sizeof(RtreeMatchArg)
   131343    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
   131344   ){
   131345     return SQLITE_ERROR;
   131346   }
   131347 
   131348   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
   131349       sizeof(sqlite3_rtree_geometry) + nBlob
   131350   );
   131351   if( !pGeom ) return SQLITE_NOMEM;
   131352   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
   131353   p = (RtreeMatchArg *)&pGeom[1];
   131354 
   131355   memcpy(p, sqlite3_value_blob(pValue), nBlob);
   131356   if( p->magic!=RTREE_GEOMETRY_MAGIC
   131357    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
   131358   ){
   131359     sqlite3_free(pGeom);
   131360     return SQLITE_ERROR;
   131361   }
   131362 
   131363   pGeom->pContext = p->pContext;
   131364   pGeom->nParam = p->nParam;
   131365   pGeom->aParam = p->aParam;
   131366 
   131367   pCons->xGeom = p->xGeom;
   131368   pCons->pGeom = pGeom;
   131369   return SQLITE_OK;
   131370 }
   131371 
   131372 /*
   131373 ** Rtree virtual table module xFilter method.
   131374 */
   131375 static int rtreeFilter(
   131376   sqlite3_vtab_cursor *pVtabCursor,
   131377   int idxNum, const char *idxStr,
   131378   int argc, sqlite3_value **argv
   131379 ){
   131380   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   131381   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   131382 
   131383   RtreeNode *pRoot = 0;
   131384   int ii;
   131385   int rc = SQLITE_OK;
   131386 
   131387   rtreeReference(pRtree);
   131388 
   131389   freeCursorConstraints(pCsr);
   131390   pCsr->iStrategy = idxNum;
   131391 
   131392   if( idxNum==1 ){
   131393     /* Special case - lookup by rowid. */
   131394     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   131395     i64 iRowid = sqlite3_value_int64(argv[0]);
   131396     rc = findLeafNode(pRtree, iRowid, &pLeaf);
   131397     pCsr->pNode = pLeaf;
   131398     if( pLeaf ){
   131399       assert( rc==SQLITE_OK );
   131400       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
   131401     }
   131402   }else{
   131403     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   131404     ** with the configured constraints.
   131405     */
   131406     if( argc>0 ){
   131407       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   131408       pCsr->nConstraint = argc;
   131409       if( !pCsr->aConstraint ){
   131410         rc = SQLITE_NOMEM;
   131411       }else{
   131412         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   131413         assert( (idxStr==0 && argc==0)
   131414                 || (idxStr && (int)strlen(idxStr)==argc*2) );
   131415         for(ii=0; ii<argc; ii++){
   131416           RtreeConstraint *p = &pCsr->aConstraint[ii];
   131417           p->op = idxStr[ii*2];
   131418           p->iCoord = idxStr[ii*2+1]-'a';
   131419           if( p->op==RTREE_MATCH ){
   131420             /* A MATCH operator. The right-hand-side must be a blob that
   131421             ** can be cast into an RtreeMatchArg object. One created using
   131422             ** an sqlite3_rtree_geometry_callback() SQL user function.
   131423             */
   131424             rc = deserializeGeometry(argv[ii], p);
   131425             if( rc!=SQLITE_OK ){
   131426               break;
   131427             }
   131428           }else{
   131429             p->rValue = sqlite3_value_double(argv[ii]);
   131430           }
   131431         }
   131432       }
   131433     }
   131434 
   131435     if( rc==SQLITE_OK ){
   131436       pCsr->pNode = 0;
   131437       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   131438     }
   131439     if( rc==SQLITE_OK ){
   131440       int isEof = 1;
   131441       int nCell = NCELL(pRoot);
   131442       pCsr->pNode = pRoot;
   131443       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
   131444         assert( pCsr->pNode==pRoot );
   131445         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
   131446         if( !isEof ){
   131447           break;
   131448         }
   131449       }
   131450       if( rc==SQLITE_OK && isEof ){
   131451         assert( pCsr->pNode==pRoot );
   131452         nodeRelease(pRtree, pRoot);
   131453         pCsr->pNode = 0;
   131454       }
   131455       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
   131456     }
   131457   }
   131458 
   131459   rtreeRelease(pRtree);
   131460   return rc;
   131461 }
   131462 
   131463 /*
   131464 ** Rtree virtual table module xBestIndex method. There are three
   131465 ** table scan strategies to choose from (in order from most to
   131466 ** least desirable):
   131467 **
   131468 **   idxNum     idxStr        Strategy
   131469 **   ------------------------------------------------
   131470 **     1        Unused        Direct lookup by rowid.
   131471 **     2        See below     R-tree query or full-table scan.
   131472 **   ------------------------------------------------
   131473 **
   131474 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   131475 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   131476 ** constraint used. The first two bytes of idxStr correspond to
   131477 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   131478 ** (argvIndex==1) etc.
   131479 **
   131480 ** The first of each pair of bytes in idxStr identifies the constraint
   131481 ** operator as follows:
   131482 **
   131483 **   Operator    Byte Value
   131484 **   ----------------------
   131485 **      =        0x41 ('A')
   131486 **     <=        0x42 ('B')
   131487 **      <        0x43 ('C')
   131488 **     >=        0x44 ('D')
   131489 **      >        0x45 ('E')
   131490 **   MATCH       0x46 ('F')
   131491 **   ----------------------
   131492 **
   131493 ** The second of each pair of bytes identifies the coordinate column
   131494 ** to which the constraint applies. The leftmost coordinate column
   131495 ** is 'a', the second from the left 'b' etc.
   131496 */
   131497 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   131498   int rc = SQLITE_OK;
   131499   int ii;
   131500 
   131501   int iIdx = 0;
   131502   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   131503   memset(zIdxStr, 0, sizeof(zIdxStr));
   131504   UNUSED_PARAMETER(tab);
   131505 
   131506   assert( pIdxInfo->idxStr==0 );
   131507   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
   131508     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   131509 
   131510     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   131511       /* We have an equality constraint on the rowid. Use strategy 1. */
   131512       int jj;
   131513       for(jj=0; jj<ii; jj++){
   131514         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   131515         pIdxInfo->aConstraintUsage[jj].omit = 0;
   131516       }
   131517       pIdxInfo->idxNum = 1;
   131518       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   131519       pIdxInfo->aConstraintUsage[jj].omit = 1;
   131520 
   131521       /* This strategy involves a two rowid lookups on an B-Tree structures
   131522       ** and then a linear search of an R-Tree node. This should be
   131523       ** considered almost as quick as a direct rowid lookup (for which
   131524       ** sqlite uses an internal cost of 0.0).
   131525       */
   131526       pIdxInfo->estimatedCost = 10.0;
   131527       return SQLITE_OK;
   131528     }
   131529 
   131530     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   131531       u8 op;
   131532       switch( p->op ){
   131533         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   131534         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   131535         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   131536         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   131537         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   131538         default:
   131539           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   131540           op = RTREE_MATCH;
   131541           break;
   131542       }
   131543       zIdxStr[iIdx++] = op;
   131544       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
   131545       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   131546       pIdxInfo->aConstraintUsage[ii].omit = 1;
   131547     }
   131548   }
   131549 
   131550   pIdxInfo->idxNum = 2;
   131551   pIdxInfo->needToFreeIdxStr = 1;
   131552   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   131553     return SQLITE_NOMEM;
   131554   }
   131555   assert( iIdx>=0 );
   131556   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
   131557   return rc;
   131558 }
   131559 
   131560 /*
   131561 ** Return the N-dimensional volumn of the cell stored in *p.
   131562 */
   131563 static float cellArea(Rtree *pRtree, RtreeCell *p){
   131564   float area = 1.0;
   131565   int ii;
   131566   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131567     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
   131568   }
   131569   return area;
   131570 }
   131571 
   131572 /*
   131573 ** Return the margin length of cell p. The margin length is the sum
   131574 ** of the objects size in each dimension.
   131575 */
   131576 static float cellMargin(Rtree *pRtree, RtreeCell *p){
   131577   float margin = 0.0;
   131578   int ii;
   131579   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131580     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   131581   }
   131582   return margin;
   131583 }
   131584 
   131585 /*
   131586 ** Store the union of cells p1 and p2 in p1.
   131587 */
   131588 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   131589   int ii;
   131590   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   131591     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131592       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   131593       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   131594     }
   131595   }else{
   131596     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131597       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   131598       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   131599     }
   131600   }
   131601 }
   131602 
   131603 /*
   131604 ** Return true if the area covered by p2 is a subset of the area covered
   131605 ** by p1. False otherwise.
   131606 */
   131607 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   131608   int ii;
   131609   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   131610   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   131611     RtreeCoord *a1 = &p1->aCoord[ii];
   131612     RtreeCoord *a2 = &p2->aCoord[ii];
   131613     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   131614      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   131615     ){
   131616       return 0;
   131617     }
   131618   }
   131619   return 1;
   131620 }
   131621 
   131622 /*
   131623 ** Return the amount cell p would grow by if it were unioned with pCell.
   131624 */
   131625 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   131626   float area;
   131627   RtreeCell cell;
   131628   memcpy(&cell, p, sizeof(RtreeCell));
   131629   area = cellArea(pRtree, &cell);
   131630   cellUnion(pRtree, &cell, pCell);
   131631   return (cellArea(pRtree, &cell)-area);
   131632 }
   131633 
   131634 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
   131635 static float cellOverlap(
   131636   Rtree *pRtree,
   131637   RtreeCell *p,
   131638   RtreeCell *aCell,
   131639   int nCell,
   131640   int iExclude
   131641 ){
   131642   int ii;
   131643   float overlap = 0.0;
   131644   for(ii=0; ii<nCell; ii++){
   131645 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131646     if( ii!=iExclude )
   131647 #else
   131648     assert( iExclude==-1 );
   131649     UNUSED_PARAMETER(iExclude);
   131650 #endif
   131651     {
   131652       int jj;
   131653       float o = 1.0;
   131654       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   131655         double x1;
   131656         double x2;
   131657 
   131658         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   131659         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   131660 
   131661         if( x2<x1 ){
   131662           o = 0.0;
   131663           break;
   131664         }else{
   131665           o = o * (float)(x2-x1);
   131666         }
   131667       }
   131668       overlap += o;
   131669     }
   131670   }
   131671   return overlap;
   131672 }
   131673 #endif
   131674 
   131675 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131676 static float cellOverlapEnlargement(
   131677   Rtree *pRtree,
   131678   RtreeCell *p,
   131679   RtreeCell *pInsert,
   131680   RtreeCell *aCell,
   131681   int nCell,
   131682   int iExclude
   131683 ){
   131684   double before;
   131685   double after;
   131686   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   131687   cellUnion(pRtree, p, pInsert);
   131688   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   131689   return (float)(after-before);
   131690 }
   131691 #endif
   131692 
   131693 
   131694 /*
   131695 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   131696 ** ChooseSubTree in r*tree terminology.
   131697 */
   131698 static int ChooseLeaf(
   131699   Rtree *pRtree,               /* Rtree table */
   131700   RtreeCell *pCell,            /* Cell to insert into rtree */
   131701   int iHeight,                 /* Height of sub-tree rooted at pCell */
   131702   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   131703 ){
   131704   int rc;
   131705   int ii;
   131706   RtreeNode *pNode;
   131707   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   131708 
   131709   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   131710     int iCell;
   131711     sqlite3_int64 iBest = 0;
   131712 
   131713     float fMinGrowth = 0.0;
   131714     float fMinArea = 0.0;
   131715 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131716     float fMinOverlap = 0.0;
   131717     float overlap;
   131718 #endif
   131719 
   131720     int nCell = NCELL(pNode);
   131721     RtreeCell cell;
   131722     RtreeNode *pChild;
   131723 
   131724     RtreeCell *aCell = 0;
   131725 
   131726 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131727     if( ii==(pRtree->iDepth-1) ){
   131728       int jj;
   131729       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
   131730       if( !aCell ){
   131731         rc = SQLITE_NOMEM;
   131732         nodeRelease(pRtree, pNode);
   131733         pNode = 0;
   131734         continue;
   131735       }
   131736       for(jj=0; jj<nCell; jj++){
   131737         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
   131738       }
   131739     }
   131740 #endif
   131741 
   131742     /* Select the child node which will be enlarged the least if pCell
   131743     ** is inserted into it. Resolve ties by choosing the entry with
   131744     ** the smallest area.
   131745     */
   131746     for(iCell=0; iCell<nCell; iCell++){
   131747       int bBest = 0;
   131748       float growth;
   131749       float area;
   131750       nodeGetCell(pRtree, pNode, iCell, &cell);
   131751       growth = cellGrowth(pRtree, &cell, pCell);
   131752       area = cellArea(pRtree, &cell);
   131753 
   131754 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   131755       if( ii==(pRtree->iDepth-1) ){
   131756         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
   131757       }else{
   131758         overlap = 0.0;
   131759       }
   131760       if( (iCell==0)
   131761        || (overlap<fMinOverlap)
   131762        || (overlap==fMinOverlap && growth<fMinGrowth)
   131763        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
   131764       ){
   131765         bBest = 1;
   131766         fMinOverlap = overlap;
   131767       }
   131768 #else
   131769       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   131770         bBest = 1;
   131771       }
   131772 #endif
   131773       if( bBest ){
   131774         fMinGrowth = growth;
   131775         fMinArea = area;
   131776         iBest = cell.iRowid;
   131777       }
   131778     }
   131779 
   131780     sqlite3_free(aCell);
   131781     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   131782     nodeRelease(pRtree, pNode);
   131783     pNode = pChild;
   131784   }
   131785 
   131786   *ppLeaf = pNode;
   131787   return rc;
   131788 }
   131789 
   131790 /*
   131791 ** A cell with the same content as pCell has just been inserted into
   131792 ** the node pNode. This function updates the bounding box cells in
   131793 ** all ancestor elements.
   131794 */
   131795 static int AdjustTree(
   131796   Rtree *pRtree,                    /* Rtree table */
   131797   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   131798   RtreeCell *pCell                  /* This cell was just inserted */
   131799 ){
   131800   RtreeNode *p = pNode;
   131801   while( p->pParent ){
   131802     RtreeNode *pParent = p->pParent;
   131803     RtreeCell cell;
   131804     int iCell;
   131805 
   131806     if( nodeParentIndex(pRtree, p, &iCell) ){
   131807       return SQLITE_CORRUPT_VTAB;
   131808     }
   131809 
   131810     nodeGetCell(pRtree, pParent, iCell, &cell);
   131811     if( !cellContains(pRtree, &cell, pCell) ){
   131812       cellUnion(pRtree, &cell, pCell);
   131813       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   131814     }
   131815 
   131816     p = pParent;
   131817   }
   131818   return SQLITE_OK;
   131819 }
   131820 
   131821 /*
   131822 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   131823 */
   131824 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   131825   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   131826   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   131827   sqlite3_step(pRtree->pWriteRowid);
   131828   return sqlite3_reset(pRtree->pWriteRowid);
   131829 }
   131830 
   131831 /*
   131832 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   131833 */
   131834 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   131835   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   131836   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   131837   sqlite3_step(pRtree->pWriteParent);
   131838   return sqlite3_reset(pRtree->pWriteParent);
   131839 }
   131840 
   131841 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   131842 
   131843 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   131844 /*
   131845 ** Implementation of the linear variant of the PickNext() function from
   131846 ** Guttman[84].
   131847 */
   131848 static RtreeCell *LinearPickNext(
   131849   Rtree *pRtree,
   131850   RtreeCell *aCell,
   131851   int nCell,
   131852   RtreeCell *pLeftBox,
   131853   RtreeCell *pRightBox,
   131854   int *aiUsed
   131855 ){
   131856   int ii;
   131857   for(ii=0; aiUsed[ii]; ii++);
   131858   aiUsed[ii] = 1;
   131859   return &aCell[ii];
   131860 }
   131861 
   131862 /*
   131863 ** Implementation of the linear variant of the PickSeeds() function from
   131864 ** Guttman[84].
   131865 */
   131866 static void LinearPickSeeds(
   131867   Rtree *pRtree,
   131868   RtreeCell *aCell,
   131869   int nCell,
   131870   int *piLeftSeed,
   131871   int *piRightSeed
   131872 ){
   131873   int i;
   131874   int iLeftSeed = 0;
   131875   int iRightSeed = 1;
   131876   float maxNormalInnerWidth = 0.0;
   131877 
   131878   /* Pick two "seed" cells from the array of cells. The algorithm used
   131879   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
   131880   ** indices of the two seed cells in the array are stored in local
   131881   ** variables iLeftSeek and iRightSeed.
   131882   */
   131883   for(i=0; i<pRtree->nDim; i++){
   131884     float x1 = DCOORD(aCell[0].aCoord[i*2]);
   131885     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
   131886     float x3 = x1;
   131887     float x4 = x2;
   131888     int jj;
   131889 
   131890     int iCellLeft = 0;
   131891     int iCellRight = 0;
   131892 
   131893     for(jj=1; jj<nCell; jj++){
   131894       float left = DCOORD(aCell[jj].aCoord[i*2]);
   131895       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
   131896 
   131897       if( left<x1 ) x1 = left;
   131898       if( right>x4 ) x4 = right;
   131899       if( left>x3 ){
   131900         x3 = left;
   131901         iCellRight = jj;
   131902       }
   131903       if( right<x2 ){
   131904         x2 = right;
   131905         iCellLeft = jj;
   131906       }
   131907     }
   131908 
   131909     if( x4!=x1 ){
   131910       float normalwidth = (x3 - x2) / (x4 - x1);
   131911       if( normalwidth>maxNormalInnerWidth ){
   131912         iLeftSeed = iCellLeft;
   131913         iRightSeed = iCellRight;
   131914       }
   131915     }
   131916   }
   131917 
   131918   *piLeftSeed = iLeftSeed;
   131919   *piRightSeed = iRightSeed;
   131920 }
   131921 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
   131922 
   131923 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   131924 /*
   131925 ** Implementation of the quadratic variant of the PickNext() function from
   131926 ** Guttman[84].
   131927 */
   131928 static RtreeCell *QuadraticPickNext(
   131929   Rtree *pRtree,
   131930   RtreeCell *aCell,
   131931   int nCell,
   131932   RtreeCell *pLeftBox,
   131933   RtreeCell *pRightBox,
   131934   int *aiUsed
   131935 ){
   131936   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
   131937 
   131938   int iSelect = -1;
   131939   float fDiff;
   131940   int ii;
   131941   for(ii=0; ii<nCell; ii++){
   131942     if( aiUsed[ii]==0 ){
   131943       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   131944       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   131945       float diff = FABS(right-left);
   131946       if( iSelect<0 || diff>fDiff ){
   131947         fDiff = diff;
   131948         iSelect = ii;
   131949       }
   131950     }
   131951   }
   131952   aiUsed[iSelect] = 1;
   131953   return &aCell[iSelect];
   131954 }
   131955 
   131956 /*
   131957 ** Implementation of the quadratic variant of the PickSeeds() function from
   131958 ** Guttman[84].
   131959 */
   131960 static void QuadraticPickSeeds(
   131961   Rtree *pRtree,
   131962   RtreeCell *aCell,
   131963   int nCell,
   131964   int *piLeftSeed,
   131965   int *piRightSeed
   131966 ){
   131967   int ii;
   131968   int jj;
   131969 
   131970   int iLeftSeed = 0;
   131971   int iRightSeed = 1;
   131972   float fWaste = 0.0;
   131973 
   131974   for(ii=0; ii<nCell; ii++){
   131975     for(jj=ii+1; jj<nCell; jj++){
   131976       float right = cellArea(pRtree, &aCell[jj]);
   131977       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
   131978       float waste = growth - right;
   131979 
   131980       if( waste>fWaste ){
   131981         iLeftSeed = ii;
   131982         iRightSeed = jj;
   131983         fWaste = waste;
   131984       }
   131985     }
   131986   }
   131987 
   131988   *piLeftSeed = iLeftSeed;
   131989   *piRightSeed = iRightSeed;
   131990 }
   131991 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
   131992 
   131993 /*
   131994 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   131995 ** nIdx. The aIdx array contains the set of integers from 0 to
   131996 ** (nIdx-1) in no particular order. This function sorts the values
   131997 ** in aIdx according to the indexed values in aDistance. For
   131998 ** example, assuming the inputs:
   131999 **
   132000 **   aIdx      = { 0,   1,   2,   3 }
   132001 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   132002 **
   132003 ** this function sets the aIdx array to contain:
   132004 **
   132005 **   aIdx      = { 0,   1,   2,   3 }
   132006 **
   132007 ** The aSpare array is used as temporary working space by the
   132008 ** sorting algorithm.
   132009 */
   132010 static void SortByDistance(
   132011   int *aIdx,
   132012   int nIdx,
   132013   float *aDistance,
   132014   int *aSpare
   132015 ){
   132016   if( nIdx>1 ){
   132017     int iLeft = 0;
   132018     int iRight = 0;
   132019 
   132020     int nLeft = nIdx/2;
   132021     int nRight = nIdx-nLeft;
   132022     int *aLeft = aIdx;
   132023     int *aRight = &aIdx[nLeft];
   132024 
   132025     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   132026     SortByDistance(aRight, nRight, aDistance, aSpare);
   132027 
   132028     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   132029     aLeft = aSpare;
   132030 
   132031     while( iLeft<nLeft || iRight<nRight ){
   132032       if( iLeft==nLeft ){
   132033         aIdx[iLeft+iRight] = aRight[iRight];
   132034         iRight++;
   132035       }else if( iRight==nRight ){
   132036         aIdx[iLeft+iRight] = aLeft[iLeft];
   132037         iLeft++;
   132038       }else{
   132039         float fLeft = aDistance[aLeft[iLeft]];
   132040         float fRight = aDistance[aRight[iRight]];
   132041         if( fLeft<fRight ){
   132042           aIdx[iLeft+iRight] = aLeft[iLeft];
   132043           iLeft++;
   132044         }else{
   132045           aIdx[iLeft+iRight] = aRight[iRight];
   132046           iRight++;
   132047         }
   132048       }
   132049     }
   132050 
   132051 #if 0
   132052     /* Check that the sort worked */
   132053     {
   132054       int jj;
   132055       for(jj=1; jj<nIdx; jj++){
   132056         float left = aDistance[aIdx[jj-1]];
   132057         float right = aDistance[aIdx[jj]];
   132058         assert( left<=right );
   132059       }
   132060     }
   132061 #endif
   132062   }
   132063 }
   132064 
   132065 /*
   132066 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   132067 ** nIdx. The aIdx array contains the set of integers from 0 to
   132068 ** (nIdx-1) in no particular order. This function sorts the values
   132069 ** in aIdx according to dimension iDim of the cells in aCell. The
   132070 ** minimum value of dimension iDim is considered first, the
   132071 ** maximum used to break ties.
   132072 **
   132073 ** The aSpare array is used as temporary working space by the
   132074 ** sorting algorithm.
   132075 */
   132076 static void SortByDimension(
   132077   Rtree *pRtree,
   132078   int *aIdx,
   132079   int nIdx,
   132080   int iDim,
   132081   RtreeCell *aCell,
   132082   int *aSpare
   132083 ){
   132084   if( nIdx>1 ){
   132085 
   132086     int iLeft = 0;
   132087     int iRight = 0;
   132088 
   132089     int nLeft = nIdx/2;
   132090     int nRight = nIdx-nLeft;
   132091     int *aLeft = aIdx;
   132092     int *aRight = &aIdx[nLeft];
   132093 
   132094     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   132095     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   132096 
   132097     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   132098     aLeft = aSpare;
   132099     while( iLeft<nLeft || iRight<nRight ){
   132100       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   132101       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   132102       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   132103       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   132104       if( (iLeft!=nLeft) && ((iRight==nRight)
   132105        || (xleft1<xright1)
   132106        || (xleft1==xright1 && xleft2<xright2)
   132107       )){
   132108         aIdx[iLeft+iRight] = aLeft[iLeft];
   132109         iLeft++;
   132110       }else{
   132111         aIdx[iLeft+iRight] = aRight[iRight];
   132112         iRight++;
   132113       }
   132114     }
   132115 
   132116 #if 0
   132117     /* Check that the sort worked */
   132118     {
   132119       int jj;
   132120       for(jj=1; jj<nIdx; jj++){
   132121         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   132122         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   132123         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   132124         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   132125         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   132126       }
   132127     }
   132128 #endif
   132129   }
   132130 }
   132131 
   132132 #if VARIANT_RSTARTREE_SPLIT
   132133 /*
   132134 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   132135 */
   132136 static int splitNodeStartree(
   132137   Rtree *pRtree,
   132138   RtreeCell *aCell,
   132139   int nCell,
   132140   RtreeNode *pLeft,
   132141   RtreeNode *pRight,
   132142   RtreeCell *pBboxLeft,
   132143   RtreeCell *pBboxRight
   132144 ){
   132145   int **aaSorted;
   132146   int *aSpare;
   132147   int ii;
   132148 
   132149   int iBestDim = 0;
   132150   int iBestSplit = 0;
   132151   float fBestMargin = 0.0;
   132152 
   132153   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   132154 
   132155   aaSorted = (int **)sqlite3_malloc(nByte);
   132156   if( !aaSorted ){
   132157     return SQLITE_NOMEM;
   132158   }
   132159 
   132160   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   132161   memset(aaSorted, 0, nByte);
   132162   for(ii=0; ii<pRtree->nDim; ii++){
   132163     int jj;
   132164     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   132165     for(jj=0; jj<nCell; jj++){
   132166       aaSorted[ii][jj] = jj;
   132167     }
   132168     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   132169   }
   132170 
   132171   for(ii=0; ii<pRtree->nDim; ii++){
   132172     float margin = 0.0;
   132173     float fBestOverlap = 0.0;
   132174     float fBestArea = 0.0;
   132175     int iBestLeft = 0;
   132176     int nLeft;
   132177 
   132178     for(
   132179       nLeft=RTREE_MINCELLS(pRtree);
   132180       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   132181       nLeft++
   132182     ){
   132183       RtreeCell left;
   132184       RtreeCell right;
   132185       int kk;
   132186       float overlap;
   132187       float area;
   132188 
   132189       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   132190       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   132191       for(kk=1; kk<(nCell-1); kk++){
   132192         if( kk<nLeft ){
   132193           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   132194         }else{
   132195           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   132196         }
   132197       }
   132198       margin += cellMargin(pRtree, &left);
   132199       margin += cellMargin(pRtree, &right);
   132200       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
   132201       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   132202       if( (nLeft==RTREE_MINCELLS(pRtree))
   132203        || (overlap<fBestOverlap)
   132204        || (overlap==fBestOverlap && area<fBestArea)
   132205       ){
   132206         iBestLeft = nLeft;
   132207         fBestOverlap = overlap;
   132208         fBestArea = area;
   132209       }
   132210     }
   132211 
   132212     if( ii==0 || margin<fBestMargin ){
   132213       iBestDim = ii;
   132214       fBestMargin = margin;
   132215       iBestSplit = iBestLeft;
   132216     }
   132217   }
   132218 
   132219   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   132220   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   132221   for(ii=0; ii<nCell; ii++){
   132222     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   132223     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   132224     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   132225     nodeInsertCell(pRtree, pTarget, pCell);
   132226     cellUnion(pRtree, pBbox, pCell);
   132227   }
   132228 
   132229   sqlite3_free(aaSorted);
   132230   return SQLITE_OK;
   132231 }
   132232 #endif
   132233 
   132234 #if VARIANT_GUTTMAN_SPLIT
   132235 /*
   132236 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
   132237 */
   132238 static int splitNodeGuttman(
   132239   Rtree *pRtree,
   132240   RtreeCell *aCell,
   132241   int nCell,
   132242   RtreeNode *pLeft,
   132243   RtreeNode *pRight,
   132244   RtreeCell *pBboxLeft,
   132245   RtreeCell *pBboxRight
   132246 ){
   132247   int iLeftSeed = 0;
   132248   int iRightSeed = 1;
   132249   int *aiUsed;
   132250   int i;
   132251 
   132252   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
   132253   if( !aiUsed ){
   132254     return SQLITE_NOMEM;
   132255   }
   132256   memset(aiUsed, 0, sizeof(int)*nCell);
   132257 
   132258   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
   132259 
   132260   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
   132261   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
   132262   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
   132263   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
   132264   aiUsed[iLeftSeed] = 1;
   132265   aiUsed[iRightSeed] = 1;
   132266 
   132267   for(i=nCell-2; i>0; i--){
   132268     RtreeCell *pNext;
   132269     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
   132270     float diff =
   132271       cellGrowth(pRtree, pBboxLeft, pNext) -
   132272       cellGrowth(pRtree, pBboxRight, pNext)
   132273     ;
   132274     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
   132275      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
   132276     ){
   132277       nodeInsertCell(pRtree, pRight, pNext);
   132278       cellUnion(pRtree, pBboxRight, pNext);
   132279     }else{
   132280       nodeInsertCell(pRtree, pLeft, pNext);
   132281       cellUnion(pRtree, pBboxLeft, pNext);
   132282     }
   132283   }
   132284 
   132285   sqlite3_free(aiUsed);
   132286   return SQLITE_OK;
   132287 }
   132288 #endif
   132289 
   132290 static int updateMapping(
   132291   Rtree *pRtree,
   132292   i64 iRowid,
   132293   RtreeNode *pNode,
   132294   int iHeight
   132295 ){
   132296   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   132297   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   132298   if( iHeight>0 ){
   132299     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   132300     if( pChild ){
   132301       nodeRelease(pRtree, pChild->pParent);
   132302       nodeReference(pNode);
   132303       pChild->pParent = pNode;
   132304     }
   132305   }
   132306   return xSetMapping(pRtree, iRowid, pNode->iNode);
   132307 }
   132308 
   132309 static int SplitNode(
   132310   Rtree *pRtree,
   132311   RtreeNode *pNode,
   132312   RtreeCell *pCell,
   132313   int iHeight
   132314 ){
   132315   int i;
   132316   int newCellIsRight = 0;
   132317 
   132318   int rc = SQLITE_OK;
   132319   int nCell = NCELL(pNode);
   132320   RtreeCell *aCell;
   132321   int *aiUsed;
   132322 
   132323   RtreeNode *pLeft = 0;
   132324   RtreeNode *pRight = 0;
   132325 
   132326   RtreeCell leftbbox;
   132327   RtreeCell rightbbox;
   132328 
   132329   /* Allocate an array and populate it with a copy of pCell and
   132330   ** all cells from node pLeft. Then zero the original node.
   132331   */
   132332   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   132333   if( !aCell ){
   132334     rc = SQLITE_NOMEM;
   132335     goto splitnode_out;
   132336   }
   132337   aiUsed = (int *)&aCell[nCell+1];
   132338   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   132339   for(i=0; i<nCell; i++){
   132340     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   132341   }
   132342   nodeZero(pRtree, pNode);
   132343   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   132344   nCell++;
   132345 
   132346   if( pNode->iNode==1 ){
   132347     pRight = nodeNew(pRtree, pNode);
   132348     pLeft = nodeNew(pRtree, pNode);
   132349     pRtree->iDepth++;
   132350     pNode->isDirty = 1;
   132351     writeInt16(pNode->zData, pRtree->iDepth);
   132352   }else{
   132353     pLeft = pNode;
   132354     pRight = nodeNew(pRtree, pLeft->pParent);
   132355     nodeReference(pLeft);
   132356   }
   132357 
   132358   if( !pLeft || !pRight ){
   132359     rc = SQLITE_NOMEM;
   132360     goto splitnode_out;
   132361   }
   132362 
   132363   memset(pLeft->zData, 0, pRtree->iNodeSize);
   132364   memset(pRight->zData, 0, pRtree->iNodeSize);
   132365 
   132366   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
   132367   if( rc!=SQLITE_OK ){
   132368     goto splitnode_out;
   132369   }
   132370 
   132371   /* Ensure both child nodes have node numbers assigned to them by calling
   132372   ** nodeWrite(). Node pRight always needs a node number, as it was created
   132373   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   132374   ** In this case avoid the all to nodeWrite().
   132375   */
   132376   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   132377    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   132378   ){
   132379     goto splitnode_out;
   132380   }
   132381 
   132382   rightbbox.iRowid = pRight->iNode;
   132383   leftbbox.iRowid = pLeft->iNode;
   132384 
   132385   if( pNode->iNode==1 ){
   132386     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   132387     if( rc!=SQLITE_OK ){
   132388       goto splitnode_out;
   132389     }
   132390   }else{
   132391     RtreeNode *pParent = pLeft->pParent;
   132392     int iCell;
   132393     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   132394     if( rc==SQLITE_OK ){
   132395       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   132396       rc = AdjustTree(pRtree, pParent, &leftbbox);
   132397     }
   132398     if( rc!=SQLITE_OK ){
   132399       goto splitnode_out;
   132400     }
   132401   }
   132402   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   132403     goto splitnode_out;
   132404   }
   132405 
   132406   for(i=0; i<NCELL(pRight); i++){
   132407     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   132408     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   132409     if( iRowid==pCell->iRowid ){
   132410       newCellIsRight = 1;
   132411     }
   132412     if( rc!=SQLITE_OK ){
   132413       goto splitnode_out;
   132414     }
   132415   }
   132416   if( pNode->iNode==1 ){
   132417     for(i=0; i<NCELL(pLeft); i++){
   132418       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   132419       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   132420       if( rc!=SQLITE_OK ){
   132421         goto splitnode_out;
   132422       }
   132423     }
   132424   }else if( newCellIsRight==0 ){
   132425     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   132426   }
   132427 
   132428   if( rc==SQLITE_OK ){
   132429     rc = nodeRelease(pRtree, pRight);
   132430     pRight = 0;
   132431   }
   132432   if( rc==SQLITE_OK ){
   132433     rc = nodeRelease(pRtree, pLeft);
   132434     pLeft = 0;
   132435   }
   132436 
   132437 splitnode_out:
   132438   nodeRelease(pRtree, pRight);
   132439   nodeRelease(pRtree, pLeft);
   132440   sqlite3_free(aCell);
   132441   return rc;
   132442 }
   132443 
   132444 /*
   132445 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   132446 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   132447 ** the pLeaf->pParent chain all the way up to the root node.
   132448 **
   132449 ** This operation is required when a row is deleted (or updated - an update
   132450 ** is implemented as a delete followed by an insert). SQLite provides the
   132451 ** rowid of the row to delete, which can be used to find the leaf on which
   132452 ** the entry resides (argument pLeaf). Once the leaf is located, this
   132453 ** function is called to determine its ancestry.
   132454 */
   132455 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   132456   int rc = SQLITE_OK;
   132457   RtreeNode *pChild = pLeaf;
   132458   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   132459     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   132460     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   132461     rc = sqlite3_step(pRtree->pReadParent);
   132462     if( rc==SQLITE_ROW ){
   132463       RtreeNode *pTest;           /* Used to test for reference loops */
   132464       i64 iNode;                  /* Node number of parent node */
   132465 
   132466       /* Before setting pChild->pParent, test that we are not creating a
   132467       ** loop of references (as we would if, say, pChild==pParent). We don't
   132468       ** want to do this as it leads to a memory leak when trying to delete
   132469       ** the referenced counted node structures.
   132470       */
   132471       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   132472       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   132473       if( !pTest ){
   132474         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   132475       }
   132476     }
   132477     rc = sqlite3_reset(pRtree->pReadParent);
   132478     if( rc==SQLITE_OK ) rc = rc2;
   132479     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
   132480     pChild = pChild->pParent;
   132481   }
   132482   return rc;
   132483 }
   132484 
   132485 static int deleteCell(Rtree *, RtreeNode *, int, int);
   132486 
   132487 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   132488   int rc;
   132489   int rc2;
   132490   RtreeNode *pParent = 0;
   132491   int iCell;
   132492 
   132493   assert( pNode->nRef==1 );
   132494 
   132495   /* Remove the entry in the parent cell. */
   132496   rc = nodeParentIndex(pRtree, pNode, &iCell);
   132497   if( rc==SQLITE_OK ){
   132498     pParent = pNode->pParent;
   132499     pNode->pParent = 0;
   132500     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   132501   }
   132502   rc2 = nodeRelease(pRtree, pParent);
   132503   if( rc==SQLITE_OK ){
   132504     rc = rc2;
   132505   }
   132506   if( rc!=SQLITE_OK ){
   132507     return rc;
   132508   }
   132509 
   132510   /* Remove the xxx_node entry. */
   132511   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   132512   sqlite3_step(pRtree->pDeleteNode);
   132513   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   132514     return rc;
   132515   }
   132516 
   132517   /* Remove the xxx_parent entry. */
   132518   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   132519   sqlite3_step(pRtree->pDeleteParent);
   132520   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   132521     return rc;
   132522   }
   132523 
   132524   /* Remove the node from the in-memory hash table and link it into
   132525   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   132526   */
   132527   nodeHashDelete(pRtree, pNode);
   132528   pNode->iNode = iHeight;
   132529   pNode->pNext = pRtree->pDeleted;
   132530   pNode->nRef++;
   132531   pRtree->pDeleted = pNode;
   132532 
   132533   return SQLITE_OK;
   132534 }
   132535 
   132536 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   132537   RtreeNode *pParent = pNode->pParent;
   132538   int rc = SQLITE_OK;
   132539   if( pParent ){
   132540     int ii;
   132541     int nCell = NCELL(pNode);
   132542     RtreeCell box;                            /* Bounding box for pNode */
   132543     nodeGetCell(pRtree, pNode, 0, &box);
   132544     for(ii=1; ii<nCell; ii++){
   132545       RtreeCell cell;
   132546       nodeGetCell(pRtree, pNode, ii, &cell);
   132547       cellUnion(pRtree, &box, &cell);
   132548     }
   132549     box.iRowid = pNode->iNode;
   132550     rc = nodeParentIndex(pRtree, pNode, &ii);
   132551     if( rc==SQLITE_OK ){
   132552       nodeOverwriteCell(pRtree, pParent, &box, ii);
   132553       rc = fixBoundingBox(pRtree, pParent);
   132554     }
   132555   }
   132556   return rc;
   132557 }
   132558 
   132559 /*
   132560 ** Delete the cell at index iCell of node pNode. After removing the
   132561 ** cell, adjust the r-tree data structure if required.
   132562 */
   132563 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   132564   RtreeNode *pParent;
   132565   int rc;
   132566 
   132567   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   132568     return rc;
   132569   }
   132570 
   132571   /* Remove the cell from the node. This call just moves bytes around
   132572   ** the in-memory node image, so it cannot fail.
   132573   */
   132574   nodeDeleteCell(pRtree, pNode, iCell);
   132575 
   132576   /* If the node is not the tree root and now has less than the minimum
   132577   ** number of cells, remove it from the tree. Otherwise, update the
   132578   ** cell in the parent node so that it tightly contains the updated
   132579   ** node.
   132580   */
   132581   pParent = pNode->pParent;
   132582   assert( pParent || pNode->iNode==1 );
   132583   if( pParent ){
   132584     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   132585       rc = removeNode(pRtree, pNode, iHeight);
   132586     }else{
   132587       rc = fixBoundingBox(pRtree, pNode);
   132588     }
   132589   }
   132590 
   132591   return rc;
   132592 }
   132593 
   132594 static int Reinsert(
   132595   Rtree *pRtree,
   132596   RtreeNode *pNode,
   132597   RtreeCell *pCell,
   132598   int iHeight
   132599 ){
   132600   int *aOrder;
   132601   int *aSpare;
   132602   RtreeCell *aCell;
   132603   float *aDistance;
   132604   int nCell;
   132605   float aCenterCoord[RTREE_MAX_DIMENSIONS];
   132606   int iDim;
   132607   int ii;
   132608   int rc = SQLITE_OK;
   132609 
   132610   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
   132611 
   132612   nCell = NCELL(pNode)+1;
   132613 
   132614   /* Allocate the buffers used by this operation. The allocation is
   132615   ** relinquished before this function returns.
   132616   */
   132617   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
   132618     sizeof(RtreeCell) +         /* aCell array */
   132619     sizeof(int)       +         /* aOrder array */
   132620     sizeof(int)       +         /* aSpare array */
   132621     sizeof(float)               /* aDistance array */
   132622   ));
   132623   if( !aCell ){
   132624     return SQLITE_NOMEM;
   132625   }
   132626   aOrder    = (int *)&aCell[nCell];
   132627   aSpare    = (int *)&aOrder[nCell];
   132628   aDistance = (float *)&aSpare[nCell];
   132629 
   132630   for(ii=0; ii<nCell; ii++){
   132631     if( ii==(nCell-1) ){
   132632       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   132633     }else{
   132634       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   132635     }
   132636     aOrder[ii] = ii;
   132637     for(iDim=0; iDim<pRtree->nDim; iDim++){
   132638       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
   132639       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
   132640     }
   132641   }
   132642   for(iDim=0; iDim<pRtree->nDim; iDim++){
   132643     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
   132644   }
   132645 
   132646   for(ii=0; ii<nCell; ii++){
   132647     aDistance[ii] = 0.0;
   132648     for(iDim=0; iDim<pRtree->nDim; iDim++){
   132649       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   132650           DCOORD(aCell[ii].aCoord[iDim*2]));
   132651       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   132652     }
   132653   }
   132654 
   132655   SortByDistance(aOrder, nCell, aDistance, aSpare);
   132656   nodeZero(pRtree, pNode);
   132657 
   132658   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   132659     RtreeCell *p = &aCell[aOrder[ii]];
   132660     nodeInsertCell(pRtree, pNode, p);
   132661     if( p->iRowid==pCell->iRowid ){
   132662       if( iHeight==0 ){
   132663         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   132664       }else{
   132665         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   132666       }
   132667     }
   132668   }
   132669   if( rc==SQLITE_OK ){
   132670     rc = fixBoundingBox(pRtree, pNode);
   132671   }
   132672   for(; rc==SQLITE_OK && ii<nCell; ii++){
   132673     /* Find a node to store this cell in. pNode->iNode currently contains
   132674     ** the height of the sub-tree headed by the cell.
   132675     */
   132676     RtreeNode *pInsert;
   132677     RtreeCell *p = &aCell[aOrder[ii]];
   132678     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   132679     if( rc==SQLITE_OK ){
   132680       int rc2;
   132681       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   132682       rc2 = nodeRelease(pRtree, pInsert);
   132683       if( rc==SQLITE_OK ){
   132684         rc = rc2;
   132685       }
   132686     }
   132687   }
   132688 
   132689   sqlite3_free(aCell);
   132690   return rc;
   132691 }
   132692 
   132693 /*
   132694 ** Insert cell pCell into node pNode. Node pNode is the head of a
   132695 ** subtree iHeight high (leaf nodes have iHeight==0).
   132696 */
   132697 static int rtreeInsertCell(
   132698   Rtree *pRtree,
   132699   RtreeNode *pNode,
   132700   RtreeCell *pCell,
   132701   int iHeight
   132702 ){
   132703   int rc = SQLITE_OK;
   132704   if( iHeight>0 ){
   132705     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   132706     if( pChild ){
   132707       nodeRelease(pRtree, pChild->pParent);
   132708       nodeReference(pNode);
   132709       pChild->pParent = pNode;
   132710     }
   132711   }
   132712   if( nodeInsertCell(pRtree, pNode, pCell) ){
   132713 #if VARIANT_RSTARTREE_REINSERT
   132714     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   132715       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   132716     }else{
   132717       pRtree->iReinsertHeight = iHeight;
   132718       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   132719     }
   132720 #else
   132721     rc = SplitNode(pRtree, pNode, pCell, iHeight);
   132722 #endif
   132723   }else{
   132724     rc = AdjustTree(pRtree, pNode, pCell);
   132725     if( rc==SQLITE_OK ){
   132726       if( iHeight==0 ){
   132727         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   132728       }else{
   132729         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   132730       }
   132731     }
   132732   }
   132733   return rc;
   132734 }
   132735 
   132736 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   132737   int ii;
   132738   int rc = SQLITE_OK;
   132739   int nCell = NCELL(pNode);
   132740 
   132741   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   132742     RtreeNode *pInsert;
   132743     RtreeCell cell;
   132744     nodeGetCell(pRtree, pNode, ii, &cell);
   132745 
   132746     /* Find a node to store this cell in. pNode->iNode currently contains
   132747     ** the height of the sub-tree headed by the cell.
   132748     */
   132749     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
   132750     if( rc==SQLITE_OK ){
   132751       int rc2;
   132752       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
   132753       rc2 = nodeRelease(pRtree, pInsert);
   132754       if( rc==SQLITE_OK ){
   132755         rc = rc2;
   132756       }
   132757     }
   132758   }
   132759   return rc;
   132760 }
   132761 
   132762 /*
   132763 ** Select a currently unused rowid for a new r-tree record.
   132764 */
   132765 static int newRowid(Rtree *pRtree, i64 *piRowid){
   132766   int rc;
   132767   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   132768   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   132769   sqlite3_step(pRtree->pWriteRowid);
   132770   rc = sqlite3_reset(pRtree->pWriteRowid);
   132771   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   132772   return rc;
   132773 }
   132774 
   132775 /*
   132776 ** Remove the entry with rowid=iDelete from the r-tree structure.
   132777 */
   132778 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   132779   int rc;                         /* Return code */
   132780   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
   132781   int iCell;                      /* Index of iDelete cell in pLeaf */
   132782   RtreeNode *pRoot;               /* Root node of rtree structure */
   132783 
   132784 
   132785   /* Obtain a reference to the root node to initialise Rtree.iDepth */
   132786   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   132787 
   132788   /* Obtain a reference to the leaf node that contains the entry
   132789   ** about to be deleted.
   132790   */
   132791   if( rc==SQLITE_OK ){
   132792     rc = findLeafNode(pRtree, iDelete, &pLeaf);
   132793   }
   132794 
   132795   /* Delete the cell in question from the leaf node. */
   132796   if( rc==SQLITE_OK ){
   132797     int rc2;
   132798     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   132799     if( rc==SQLITE_OK ){
   132800       rc = deleteCell(pRtree, pLeaf, iCell, 0);
   132801     }
   132802     rc2 = nodeRelease(pRtree, pLeaf);
   132803     if( rc==SQLITE_OK ){
   132804       rc = rc2;
   132805     }
   132806   }
   132807 
   132808   /* Delete the corresponding entry in the <rtree>_rowid table. */
   132809   if( rc==SQLITE_OK ){
   132810     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   132811     sqlite3_step(pRtree->pDeleteRowid);
   132812     rc = sqlite3_reset(pRtree->pDeleteRowid);
   132813   }
   132814 
   132815   /* Check if the root node now has exactly one child. If so, remove
   132816   ** it, schedule the contents of the child for reinsertion and
   132817   ** reduce the tree height by one.
   132818   **
   132819   ** This is equivalent to copying the contents of the child into
   132820   ** the root node (the operation that Gutman's paper says to perform
   132821   ** in this scenario).
   132822   */
   132823   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   132824     int rc2;
   132825     RtreeNode *pChild;
   132826     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   132827     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   132828     if( rc==SQLITE_OK ){
   132829       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   132830     }
   132831     rc2 = nodeRelease(pRtree, pChild);
   132832     if( rc==SQLITE_OK ) rc = rc2;
   132833     if( rc==SQLITE_OK ){
   132834       pRtree->iDepth--;
   132835       writeInt16(pRoot->zData, pRtree->iDepth);
   132836       pRoot->isDirty = 1;
   132837     }
   132838   }
   132839 
   132840   /* Re-insert the contents of any underfull nodes removed from the tree. */
   132841   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   132842     if( rc==SQLITE_OK ){
   132843       rc = reinsertNodeContent(pRtree, pLeaf);
   132844     }
   132845     pRtree->pDeleted = pLeaf->pNext;
   132846     sqlite3_free(pLeaf);
   132847   }
   132848 
   132849   /* Release the reference to the root node. */
   132850   if( rc==SQLITE_OK ){
   132851     rc = nodeRelease(pRtree, pRoot);
   132852   }else{
   132853     nodeRelease(pRtree, pRoot);
   132854   }
   132855 
   132856   return rc;
   132857 }
   132858 
   132859 /*
   132860 ** The xUpdate method for rtree module virtual tables.
   132861 */
   132862 static int rtreeUpdate(
   132863   sqlite3_vtab *pVtab,
   132864   int nData,
   132865   sqlite3_value **azData,
   132866   sqlite_int64 *pRowid
   132867 ){
   132868   Rtree *pRtree = (Rtree *)pVtab;
   132869   int rc = SQLITE_OK;
   132870   RtreeCell cell;                 /* New cell to insert if nData>1 */
   132871   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
   132872 
   132873   rtreeReference(pRtree);
   132874   assert(nData>=1);
   132875 
   132876   /* Constraint handling. A write operation on an r-tree table may return
   132877   ** SQLITE_CONSTRAINT for two reasons:
   132878   **
   132879   **   1. A duplicate rowid value, or
   132880   **   2. The supplied data violates the "x2>=x1" constraint.
   132881   **
   132882   ** In the first case, if the conflict-handling mode is REPLACE, then
   132883   ** the conflicting row can be removed before proceeding. In the second
   132884   ** case, SQLITE_CONSTRAINT must be returned regardless of the
   132885   ** conflict-handling mode specified by the user.
   132886   */
   132887   if( nData>1 ){
   132888     int ii;
   132889 
   132890     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   132891     assert( nData==(pRtree->nDim*2 + 3) );
   132892     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   132893       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   132894         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
   132895         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
   132896         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   132897           rc = SQLITE_CONSTRAINT;
   132898           goto constraint;
   132899         }
   132900       }
   132901     }else{
   132902       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   132903         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   132904         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   132905         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   132906           rc = SQLITE_CONSTRAINT;
   132907           goto constraint;
   132908         }
   132909       }
   132910     }
   132911 
   132912     /* If a rowid value was supplied, check if it is already present in
   132913     ** the table. If so, the constraint has failed. */
   132914     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
   132915       cell.iRowid = sqlite3_value_int64(azData[2]);
   132916       if( sqlite3_value_type(azData[0])==SQLITE_NULL
   132917        || sqlite3_value_int64(azData[0])!=cell.iRowid
   132918       ){
   132919         int steprc;
   132920         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   132921         steprc = sqlite3_step(pRtree->pReadRowid);
   132922         rc = sqlite3_reset(pRtree->pReadRowid);
   132923         if( SQLITE_ROW==steprc ){
   132924           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
   132925             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
   132926           }else{
   132927             rc = SQLITE_CONSTRAINT;
   132928             goto constraint;
   132929           }
   132930         }
   132931       }
   132932       bHaveRowid = 1;
   132933     }
   132934   }
   132935 
   132936   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   132937   ** record to delete from the r-tree table. The following block does
   132938   ** just that.
   132939   */
   132940   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   132941     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
   132942   }
   132943 
   132944   /* If the azData[] array contains more than one element, elements
   132945   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   132946   ** the r-tree structure.
   132947   */
   132948   if( rc==SQLITE_OK && nData>1 ){
   132949     /* Insert the new record into the r-tree */
   132950     RtreeNode *pLeaf;
   132951 
   132952     /* Figure out the rowid of the new row. */
   132953     if( bHaveRowid==0 ){
   132954       rc = newRowid(pRtree, &cell.iRowid);
   132955     }
   132956     *pRowid = cell.iRowid;
   132957 
   132958     if( rc==SQLITE_OK ){
   132959       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   132960     }
   132961     if( rc==SQLITE_OK ){
   132962       int rc2;
   132963       pRtree->iReinsertHeight = -1;
   132964       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   132965       rc2 = nodeRelease(pRtree, pLeaf);
   132966       if( rc==SQLITE_OK ){
   132967         rc = rc2;
   132968       }
   132969     }
   132970   }
   132971 
   132972 constraint:
   132973   rtreeRelease(pRtree);
   132974   return rc;
   132975 }
   132976 
   132977 /*
   132978 ** The xRename method for rtree module virtual tables.
   132979 */
   132980 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   132981   Rtree *pRtree = (Rtree *)pVtab;
   132982   int rc = SQLITE_NOMEM;
   132983   char *zSql = sqlite3_mprintf(
   132984     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   132985     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   132986     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   132987     , pRtree->zDb, pRtree->zName, zNewName
   132988     , pRtree->zDb, pRtree->zName, zNewName
   132989     , pRtree->zDb, pRtree->zName, zNewName
   132990   );
   132991   if( zSql ){
   132992     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   132993     sqlite3_free(zSql);
   132994   }
   132995   return rc;
   132996 }
   132997 
   132998 static sqlite3_module rtreeModule = {
   132999   0,                          /* iVersion */
   133000   rtreeCreate,                /* xCreate - create a table */
   133001   rtreeConnect,               /* xConnect - connect to an existing table */
   133002   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   133003   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   133004   rtreeDestroy,               /* xDestroy - Drop a table */
   133005   rtreeOpen,                  /* xOpen - open a cursor */
   133006   rtreeClose,                 /* xClose - close a cursor */
   133007   rtreeFilter,                /* xFilter - configure scan constraints */
   133008   rtreeNext,                  /* xNext - advance a cursor */
   133009   rtreeEof,                   /* xEof */
   133010   rtreeColumn,                /* xColumn - read data */
   133011   rtreeRowid,                 /* xRowid - read data */
   133012   rtreeUpdate,                /* xUpdate - write data */
   133013   0,                          /* xBegin - begin transaction */
   133014   0,                          /* xSync - sync transaction */
   133015   0,                          /* xCommit - commit transaction */
   133016   0,                          /* xRollback - rollback transaction */
   133017   0,                          /* xFindFunction - function overloading */
   133018   rtreeRename,                /* xRename - rename the table */
   133019   0,                          /* xSavepoint */
   133020   0,                          /* xRelease */
   133021   0                           /* xRollbackTo */
   133022 };
   133023 
   133024 static int rtreeSqlInit(
   133025   Rtree *pRtree,
   133026   sqlite3 *db,
   133027   const char *zDb,
   133028   const char *zPrefix,
   133029   int isCreate
   133030 ){
   133031   int rc = SQLITE_OK;
   133032 
   133033   #define N_STATEMENT 9
   133034   static const char *azSql[N_STATEMENT] = {
   133035     /* Read and write the xxx_node table */
   133036     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   133037     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   133038     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   133039 
   133040     /* Read and write the xxx_rowid table */
   133041     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   133042     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   133043     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   133044 
   133045     /* Read and write the xxx_parent table */
   133046     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   133047     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   133048     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   133049   };
   133050   sqlite3_stmt **appStmt[N_STATEMENT];
   133051   int i;
   133052 
   133053   pRtree->db = db;
   133054 
   133055   if( isCreate ){
   133056     char *zCreate = sqlite3_mprintf(
   133057 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   133058 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   133059 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
   133060 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   133061       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   133062     );
   133063     if( !zCreate ){
   133064       return SQLITE_NOMEM;
   133065     }
   133066     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   133067     sqlite3_free(zCreate);
   133068     if( rc!=SQLITE_OK ){
   133069       return rc;
   133070     }
   133071   }
   133072 
   133073   appStmt[0] = &pRtree->pReadNode;
   133074   appStmt[1] = &pRtree->pWriteNode;
   133075   appStmt[2] = &pRtree->pDeleteNode;
   133076   appStmt[3] = &pRtree->pReadRowid;
   133077   appStmt[4] = &pRtree->pWriteRowid;
   133078   appStmt[5] = &pRtree->pDeleteRowid;
   133079   appStmt[6] = &pRtree->pReadParent;
   133080   appStmt[7] = &pRtree->pWriteParent;
   133081   appStmt[8] = &pRtree->pDeleteParent;
   133082 
   133083   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   133084     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   133085     if( zSql ){
   133086       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   133087     }else{
   133088       rc = SQLITE_NOMEM;
   133089     }
   133090     sqlite3_free(zSql);
   133091   }
   133092 
   133093   return rc;
   133094 }
   133095 
   133096 /*
   133097 ** The second argument to this function contains the text of an SQL statement
   133098 ** that returns a single integer value. The statement is compiled and executed
   133099 ** using database connection db. If successful, the integer value returned
   133100 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   133101 ** code is returned and the value of *piVal after returning is not defined.
   133102 */
   133103 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   133104   int rc = SQLITE_NOMEM;
   133105   if( zSql ){
   133106     sqlite3_stmt *pStmt = 0;
   133107     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   133108     if( rc==SQLITE_OK ){
   133109       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   133110         *piVal = sqlite3_column_int(pStmt, 0);
   133111       }
   133112       rc = sqlite3_finalize(pStmt);
   133113     }
   133114   }
   133115   return rc;
   133116 }
   133117 
   133118 /*
   133119 ** This function is called from within the xConnect() or xCreate() method to
   133120 ** determine the node-size used by the rtree table being created or connected
   133121 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   133122 ** Otherwise, an SQLite error code is returned.
   133123 **
   133124 ** If this function is being called as part of an xConnect(), then the rtree
   133125 ** table already exists. In this case the node-size is determined by inspecting
   133126 ** the root node of the tree.
   133127 **
   133128 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   133129 ** This ensures that each node is stored on a single database page. If the
   133130 ** database page-size is so large that more than RTREE_MAXCELLS entries
   133131 ** would fit in a single node, use a smaller node-size.
   133132 */
   133133 static int getNodeSize(
   133134   sqlite3 *db,                    /* Database handle */
   133135   Rtree *pRtree,                  /* Rtree handle */
   133136   int isCreate                    /* True for xCreate, false for xConnect */
   133137 ){
   133138   int rc;
   133139   char *zSql;
   133140   if( isCreate ){
   133141     int iPageSize = 0;
   133142     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   133143     rc = getIntFromStmt(db, zSql, &iPageSize);
   133144     if( rc==SQLITE_OK ){
   133145       pRtree->iNodeSize = iPageSize-64;
   133146       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   133147         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   133148       }
   133149     }
   133150   }else{
   133151     zSql = sqlite3_mprintf(
   133152         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   133153         pRtree->zDb, pRtree->zName
   133154     );
   133155     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   133156   }
   133157 
   133158   sqlite3_free(zSql);
   133159   return rc;
   133160 }
   133161 
   133162 /*
   133163 ** This function is the implementation of both the xConnect and xCreate
   133164 ** methods of the r-tree virtual table.
   133165 **
   133166 **   argv[0]   -> module name
   133167 **   argv[1]   -> database name
   133168 **   argv[2]   -> table name
   133169 **   argv[...] -> column names...
   133170 */
   133171 static int rtreeInit(
   133172   sqlite3 *db,                        /* Database connection */
   133173   void *pAux,                         /* One of the RTREE_COORD_* constants */
   133174   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   133175   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   133176   char **pzErr,                       /* OUT: Error message, if any */
   133177   int isCreate                        /* True for xCreate, false for xConnect */
   133178 ){
   133179   int rc = SQLITE_OK;
   133180   Rtree *pRtree;
   133181   int nDb;              /* Length of string argv[1] */
   133182   int nName;            /* Length of string argv[2] */
   133183   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   133184 
   133185   const char *aErrMsg[] = {
   133186     0,                                                    /* 0 */
   133187     "Wrong number of columns for an rtree table",         /* 1 */
   133188     "Too few columns for an rtree table",                 /* 2 */
   133189     "Too many columns for an rtree table"                 /* 3 */
   133190   };
   133191 
   133192   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   133193   if( aErrMsg[iErr] ){
   133194     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   133195     return SQLITE_ERROR;
   133196   }
   133197 
   133198   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
   133199 
   133200   /* Allocate the sqlite3_vtab structure */
   133201   nDb = (int)strlen(argv[1]);
   133202   nName = (int)strlen(argv[2]);
   133203   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   133204   if( !pRtree ){
   133205     return SQLITE_NOMEM;
   133206   }
   133207   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   133208   pRtree->nBusy = 1;
   133209   pRtree->base.pModule = &rtreeModule;
   133210   pRtree->zDb = (char *)&pRtree[1];
   133211   pRtree->zName = &pRtree->zDb[nDb+1];
   133212   pRtree->nDim = (argc-4)/2;
   133213   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   133214   pRtree->eCoordType = eCoordType;
   133215   memcpy(pRtree->zDb, argv[1], nDb);
   133216   memcpy(pRtree->zName, argv[2], nName);
   133217 
   133218   /* Figure out the node size to use. */
   133219   rc = getNodeSize(db, pRtree, isCreate);
   133220 
   133221   /* Create/Connect to the underlying relational database schema. If
   133222   ** that is successful, call sqlite3_declare_vtab() to configure
   133223   ** the r-tree table schema.
   133224   */
   133225   if( rc==SQLITE_OK ){
   133226     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   133227       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   133228     }else{
   133229       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   133230       char *zTmp;
   133231       int ii;
   133232       for(ii=4; zSql && ii<argc; ii++){
   133233         zTmp = zSql;
   133234         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   133235         sqlite3_free(zTmp);
   133236       }
   133237       if( zSql ){
   133238         zTmp = zSql;
   133239         zSql = sqlite3_mprintf("%s);", zTmp);
   133240         sqlite3_free(zTmp);
   133241       }
   133242       if( !zSql ){
   133243         rc = SQLITE_NOMEM;
   133244       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   133245         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   133246       }
   133247       sqlite3_free(zSql);
   133248     }
   133249   }
   133250 
   133251   if( rc==SQLITE_OK ){
   133252     *ppVtab = (sqlite3_vtab *)pRtree;
   133253   }else{
   133254     rtreeRelease(pRtree);
   133255   }
   133256   return rc;
   133257 }
   133258 
   133259 
   133260 /*
   133261 ** Implementation of a scalar function that decodes r-tree nodes to
   133262 ** human readable strings. This can be used for debugging and analysis.
   133263 **
   133264 ** The scalar function takes two arguments, a blob of data containing
   133265 ** an r-tree node, and the number of dimensions the r-tree indexes.
   133266 ** For a two-dimensional r-tree structure called "rt", to deserialize
   133267 ** all nodes, a statement like:
   133268 **
   133269 **   SELECT rtreenode(2, data) FROM rt_node;
   133270 **
   133271 ** The human readable string takes the form of a Tcl list with one
   133272 ** entry for each cell in the r-tree node. Each entry is itself a
   133273 ** list, containing the 8-byte rowid/pageno followed by the
   133274 ** <num-dimension>*2 coordinates.
   133275 */
   133276 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   133277   char *zText = 0;
   133278   RtreeNode node;
   133279   Rtree tree;
   133280   int ii;
   133281 
   133282   UNUSED_PARAMETER(nArg);
   133283   memset(&node, 0, sizeof(RtreeNode));
   133284   memset(&tree, 0, sizeof(Rtree));
   133285   tree.nDim = sqlite3_value_int(apArg[0]);
   133286   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   133287   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   133288 
   133289   for(ii=0; ii<NCELL(&node); ii++){
   133290     char zCell[512];
   133291     int nCell = 0;
   133292     RtreeCell cell;
   133293     int jj;
   133294 
   133295     nodeGetCell(&tree, &node, ii, &cell);
   133296     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
   133297     nCell = (int)strlen(zCell);
   133298     for(jj=0; jj<tree.nDim*2; jj++){
   133299       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
   133300       nCell = (int)strlen(zCell);
   133301     }
   133302 
   133303     if( zText ){
   133304       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   133305       sqlite3_free(zText);
   133306       zText = zTextNew;
   133307     }else{
   133308       zText = sqlite3_mprintf("{%s}", zCell);
   133309     }
   133310   }
   133311 
   133312   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   133313 }
   133314 
   133315 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   133316   UNUSED_PARAMETER(nArg);
   133317   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   133318    || sqlite3_value_bytes(apArg[0])<2
   133319   ){
   133320     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   133321   }else{
   133322     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   133323     sqlite3_result_int(ctx, readInt16(zBlob));
   133324   }
   133325 }
   133326 
   133327 /*
   133328 ** Register the r-tree module with database handle db. This creates the
   133329 ** virtual table module "rtree" and the debugging/analysis scalar
   133330 ** function "rtreenode".
   133331 */
   133332 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   133333   const int utf8 = SQLITE_UTF8;
   133334   int rc;
   133335 
   133336   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   133337   if( rc==SQLITE_OK ){
   133338     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   133339   }
   133340   if( rc==SQLITE_OK ){
   133341     void *c = (void *)RTREE_COORD_REAL32;
   133342     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   133343   }
   133344   if( rc==SQLITE_OK ){
   133345     void *c = (void *)RTREE_COORD_INT32;
   133346     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   133347   }
   133348 
   133349   return rc;
   133350 }
   133351 
   133352 /*
   133353 ** A version of sqlite3_free() that can be used as a callback. This is used
   133354 ** in two places - as the destructor for the blob value returned by the
   133355 ** invocation of a geometry function, and as the destructor for the geometry
   133356 ** functions themselves.
   133357 */
   133358 static void doSqlite3Free(void *p){
   133359   sqlite3_free(p);
   133360 }
   133361 
   133362 /*
   133363 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
   133364 ** scalar user function. This C function is the callback used for all such
   133365 ** registered SQL functions.
   133366 **
   133367 ** The scalar user functions return a blob that is interpreted by r-tree
   133368 ** table MATCH operators.
   133369 */
   133370 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   133371   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   133372   RtreeMatchArg *pBlob;
   133373   int nBlob;
   133374 
   133375   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
   133376   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   133377   if( !pBlob ){
   133378     sqlite3_result_error_nomem(ctx);
   133379   }else{
   133380     int i;
   133381     pBlob->magic = RTREE_GEOMETRY_MAGIC;
   133382     pBlob->xGeom = pGeomCtx->xGeom;
   133383     pBlob->pContext = pGeomCtx->pContext;
   133384     pBlob->nParam = nArg;
   133385     for(i=0; i<nArg; i++){
   133386       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   133387     }
   133388     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
   133389   }
   133390 }
   133391 
   133392 /*
   133393 ** Register a new geometry function for use with the r-tree MATCH operator.
   133394 */
   133395 SQLITE_API int sqlite3_rtree_geometry_callback(
   133396   sqlite3 *db,
   133397   const char *zGeom,
   133398   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
   133399   void *pContext
   133400 ){
   133401   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   133402 
   133403   /* Allocate and populate the context object. */
   133404   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   133405   if( !pGeomCtx ) return SQLITE_NOMEM;
   133406   pGeomCtx->xGeom = xGeom;
   133407   pGeomCtx->pContext = pContext;
   133408 
   133409   /* Create the new user-function. Register a destructor function to delete
   133410   ** the context object when it is no longer required.  */
   133411   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   133412       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
   133413   );
   133414 }
   133415 
   133416 #if !SQLITE_CORE
   133417 SQLITE_API int sqlite3_extension_init(
   133418   sqlite3 *db,
   133419   char **pzErrMsg,
   133420   const sqlite3_api_routines *pApi
   133421 ){
   133422   SQLITE_EXTENSION_INIT2(pApi)
   133423   return sqlite3RtreeInit(db);
   133424 }
   133425 #endif
   133426 
   133427 #endif
   133428 
   133429 /************** End of rtree.c ***********************************************/
   133430 /************** Begin file icu.c *********************************************/
   133431 /*
   133432 ** 2007 May 6
   133433 **
   133434 ** The author disclaims copyright to this source code.  In place of
   133435 ** a legal notice, here is a blessing:
   133436 **
   133437 **    May you do good and not evil.
   133438 **    May you find forgiveness for yourself and forgive others.
   133439 **    May you share freely, never taking more than you give.
   133440 **
   133441 *************************************************************************
   133442 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   133443 **
   133444 ** This file implements an integration between the ICU library
   133445 ** ("International Components for Unicode", an open-source library
   133446 ** for handling unicode data) and SQLite. The integration uses
   133447 ** ICU to provide the following to SQLite:
   133448 **
   133449 **   * An implementation of the SQL regexp() function (and hence REGEXP
   133450 **     operator) using the ICU uregex_XX() APIs.
   133451 **
   133452 **   * Implementations of the SQL scalar upper() and lower() functions
   133453 **     for case mapping.
   133454 **
   133455 **   * Integration of ICU and SQLite collation seqences.
   133456 **
   133457 **   * An implementation of the LIKE operator that uses ICU to
   133458 **     provide case-independent matching.
   133459 */
   133460 
   133461 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   133462 
   133463 /* Include ICU headers */
   133464 #include <unicode/utypes.h>
   133465 #include <unicode/uregex.h>
   133466 #include <unicode/ustring.h>
   133467 #include <unicode/ucol.h>
   133468 
   133469 /* #include <assert.h> */
   133470 
   133471 #ifndef SQLITE_CORE
   133472   SQLITE_EXTENSION_INIT1
   133473 #else
   133474 #endif
   133475 
   133476 /*
   133477 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   133478 ** operator.
   133479 */
   133480 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   133481 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   133482 #endif
   133483 
   133484 /*
   133485 ** Version of sqlite3_free() that is always a function, never a macro.
   133486 */
   133487 static void xFree(void *p){
   133488   sqlite3_free(p);
   133489 }
   133490 
   133491 /*
   133492 ** Compare two UTF-8 strings for equality where the first string is
   133493 ** a "LIKE" expression. Return true (1) if they are the same and
   133494 ** false (0) if they are different.
   133495 */
   133496 static int icuLikeCompare(
   133497   const uint8_t *zPattern,   /* LIKE pattern */
   133498   const uint8_t *zString,    /* The UTF-8 string to compare against */
   133499   const UChar32 uEsc         /* The escape character */
   133500 ){
   133501   static const int MATCH_ONE = (UChar32)'_';
   133502   static const int MATCH_ALL = (UChar32)'%';
   133503 
   133504   int iPattern = 0;       /* Current byte index in zPattern */
   133505   int iString = 0;        /* Current byte index in zString */
   133506 
   133507   int prevEscape = 0;     /* True if the previous character was uEsc */
   133508 
   133509   while( zPattern[iPattern]!=0 ){
   133510 
   133511     /* Read (and consume) the next character from the input pattern. */
   133512     UChar32 uPattern;
   133513     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   133514     assert(uPattern!=0);
   133515 
   133516     /* There are now 4 possibilities:
   133517     **
   133518     **     1. uPattern is an unescaped match-all character "%",
   133519     **     2. uPattern is an unescaped match-one character "_",
   133520     **     3. uPattern is an unescaped escape character, or
   133521     **     4. uPattern is to be handled as an ordinary character
   133522     */
   133523     if( !prevEscape && uPattern==MATCH_ALL ){
   133524       /* Case 1. */
   133525       uint8_t c;
   133526 
   133527       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   133528       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   133529       ** test string.
   133530       */
   133531       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   133532         if( c==MATCH_ONE ){
   133533           if( zString[iString]==0 ) return 0;
   133534           U8_FWD_1_UNSAFE(zString, iString);
   133535         }
   133536         iPattern++;
   133537       }
   133538 
   133539       if( zPattern[iPattern]==0 ) return 1;
   133540 
   133541       while( zString[iString] ){
   133542         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   133543           return 1;
   133544         }
   133545         U8_FWD_1_UNSAFE(zString, iString);
   133546       }
   133547       return 0;
   133548 
   133549     }else if( !prevEscape && uPattern==MATCH_ONE ){
   133550       /* Case 2. */
   133551       if( zString[iString]==0 ) return 0;
   133552       U8_FWD_1_UNSAFE(zString, iString);
   133553 
   133554     }else if( !prevEscape && uPattern==uEsc){
   133555       /* Case 3. */
   133556       prevEscape = 1;
   133557 
   133558     }else{
   133559       /* Case 4. */
   133560       UChar32 uString;
   133561       U8_NEXT_UNSAFE(zString, iString, uString);
   133562       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   133563       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   133564       if( uString!=uPattern ){
   133565         return 0;
   133566       }
   133567       prevEscape = 0;
   133568     }
   133569   }
   133570 
   133571   return zString[iString]==0;
   133572 }
   133573 
   133574 /*
   133575 ** Implementation of the like() SQL function.  This function implements
   133576 ** the build-in LIKE operator.  The first argument to the function is the
   133577 ** pattern and the second argument is the string.  So, the SQL statements:
   133578 **
   133579 **       A LIKE B
   133580 **
   133581 ** is implemented as like(B, A). If there is an escape character E,
   133582 **
   133583 **       A LIKE B ESCAPE E
   133584 **
   133585 ** is mapped to like(B, A, E).
   133586 */
   133587 static void icuLikeFunc(
   133588   sqlite3_context *context,
   133589   int argc,
   133590   sqlite3_value **argv
   133591 ){
   133592   const unsigned char *zA = sqlite3_value_text(argv[0]);
   133593   const unsigned char *zB = sqlite3_value_text(argv[1]);
   133594   UChar32 uEsc = 0;
   133595 
   133596   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   133597   ** of deep recursion and N*N behavior in patternCompare().
   133598   */
   133599   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   133600     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   133601     return;
   133602   }
   133603 
   133604 
   133605   if( argc==3 ){
   133606     /* The escape character string must consist of a single UTF-8 character.
   133607     ** Otherwise, return an error.
   133608     */
   133609     int nE= sqlite3_value_bytes(argv[2]);
   133610     const unsigned char *zE = sqlite3_value_text(argv[2]);
   133611     int i = 0;
   133612     if( zE==0 ) return;
   133613     U8_NEXT(zE, i, nE, uEsc);
   133614     if( i!=nE){
   133615       sqlite3_result_error(context,
   133616           "ESCAPE expression must be a single character", -1);
   133617       return;
   133618     }
   133619   }
   133620 
   133621   if( zA && zB ){
   133622     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   133623   }
   133624 }
   133625 
   133626 /*
   133627 ** This function is called when an ICU function called from within
   133628 ** the implementation of an SQL scalar function returns an error.
   133629 **
   133630 ** The scalar function context passed as the first argument is
   133631 ** loaded with an error message based on the following two args.
   133632 */
   133633 static void icuFunctionError(
   133634   sqlite3_context *pCtx,       /* SQLite scalar function context */
   133635   const char *zName,           /* Name of ICU function that failed */
   133636   UErrorCode e                 /* Error code returned by ICU function */
   133637 ){
   133638   char zBuf[128];
   133639   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   133640   zBuf[127] = '\0';
   133641   sqlite3_result_error(pCtx, zBuf, -1);
   133642 }
   133643 
   133644 /*
   133645 ** Function to delete compiled regexp objects. Registered as
   133646 ** a destructor function with sqlite3_set_auxdata().
   133647 */
   133648 static void icuRegexpDelete(void *p){
   133649   URegularExpression *pExpr = (URegularExpression *)p;
   133650   uregex_close(pExpr);
   133651 }
   133652 
   133653 /*
   133654 ** Implementation of SQLite REGEXP operator. This scalar function takes
   133655 ** two arguments. The first is a regular expression pattern to compile
   133656 ** the second is a string to match against that pattern. If either
   133657 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   133658 ** is 1 if the string matches the pattern, or 0 otherwise.
   133659 **
   133660 ** SQLite maps the regexp() function to the regexp() operator such
   133661 ** that the following two are equivalent:
   133662 **
   133663 **     zString REGEXP zPattern
   133664 **     regexp(zPattern, zString)
   133665 **
   133666 ** Uses the following ICU regexp APIs:
   133667 **
   133668 **     uregex_open()
   133669 **     uregex_matches()
   133670 **     uregex_close()
   133671 */
   133672 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   133673   UErrorCode status = U_ZERO_ERROR;
   133674   URegularExpression *pExpr;
   133675   UBool res;
   133676   const UChar *zString = sqlite3_value_text16(apArg[1]);
   133677 
   133678   (void)nArg;  /* Unused parameter */
   133679 
   133680   /* If the left hand side of the regexp operator is NULL,
   133681   ** then the result is also NULL.
   133682   */
   133683   if( !zString ){
   133684     return;
   133685   }
   133686 
   133687   pExpr = sqlite3_get_auxdata(p, 0);
   133688   if( !pExpr ){
   133689     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   133690     if( !zPattern ){
   133691       return;
   133692     }
   133693     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   133694 
   133695     if( U_SUCCESS(status) ){
   133696       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   133697     }else{
   133698       assert(!pExpr);
   133699       icuFunctionError(p, "uregex_open", status);
   133700       return;
   133701     }
   133702   }
   133703 
   133704   /* Configure the text that the regular expression operates on. */
   133705   uregex_setText(pExpr, zString, -1, &status);
   133706   if( !U_SUCCESS(status) ){
   133707     icuFunctionError(p, "uregex_setText", status);
   133708     return;
   133709   }
   133710 
   133711   /* Attempt the match */
   133712   res = uregex_matches(pExpr, 0, &status);
   133713   if( !U_SUCCESS(status) ){
   133714     icuFunctionError(p, "uregex_matches", status);
   133715     return;
   133716   }
   133717 
   133718   /* Set the text that the regular expression operates on to a NULL
   133719   ** pointer. This is not really necessary, but it is tidier than
   133720   ** leaving the regular expression object configured with an invalid
   133721   ** pointer after this function returns.
   133722   */
   133723   uregex_setText(pExpr, 0, 0, &status);
   133724 
   133725   /* Return 1 or 0. */
   133726   sqlite3_result_int(p, res ? 1 : 0);
   133727 }
   133728 
   133729 /*
   133730 ** Implementations of scalar functions for case mapping - upper() and
   133731 ** lower(). Function upper() converts its input to upper-case (ABC).
   133732 ** Function lower() converts to lower-case (abc).
   133733 **
   133734 ** ICU provides two types of case mapping, "general" case mapping and
   133735 ** "language specific". Refer to ICU documentation for the differences
   133736 ** between the two.
   133737 **
   133738 ** To utilise "general" case mapping, the upper() or lower() scalar
   133739 ** functions are invoked with one argument:
   133740 **
   133741 **     upper('ABC') -> 'abc'
   133742 **     lower('abc') -> 'ABC'
   133743 **
   133744 ** To access ICU "language specific" case mapping, upper() or lower()
   133745 ** should be invoked with two arguments. The second argument is the name
   133746 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   133747 ** as the second argument is the same as invoking the 1 argument version
   133748 ** of upper() or lower().
   133749 **
   133750 **     lower('I', 'en_us') -> 'i'
   133751 **     lower('I', 'tr_tr') -> '' (small dotless i)
   133752 **
   133753 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   133754 */
   133755 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   133756   const UChar *zInput;
   133757   UChar *zOutput;
   133758   int nInput;
   133759   int nOutput;
   133760 
   133761   UErrorCode status = U_ZERO_ERROR;
   133762   const char *zLocale = 0;
   133763 
   133764   assert(nArg==1 || nArg==2);
   133765   if( nArg==2 ){
   133766     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   133767   }
   133768 
   133769   zInput = sqlite3_value_text16(apArg[0]);
   133770   if( !zInput ){
   133771     return;
   133772   }
   133773   nInput = sqlite3_value_bytes16(apArg[0]);
   133774 
   133775   nOutput = nInput * 2 + 2;
   133776   zOutput = sqlite3_malloc(nOutput);
   133777   if( !zOutput ){
   133778     return;
   133779   }
   133780 
   133781   if( sqlite3_user_data(p) ){
   133782     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   133783   }else{
   133784     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   133785   }
   133786 
   133787   if( !U_SUCCESS(status) ){
   133788     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   133789     return;
   133790   }
   133791 
   133792   sqlite3_result_text16(p, zOutput, -1, xFree);
   133793 }
   133794 
   133795 /*
   133796 ** Collation sequence destructor function. The pCtx argument points to
   133797 ** a UCollator structure previously allocated using ucol_open().
   133798 */
   133799 static void icuCollationDel(void *pCtx){
   133800   UCollator *p = (UCollator *)pCtx;
   133801   ucol_close(p);
   133802 }
   133803 
   133804 /*
   133805 ** Collation sequence comparison function. The pCtx argument points to
   133806 ** a UCollator structure previously allocated using ucol_open().
   133807 */
   133808 static int icuCollationColl(
   133809   void *pCtx,
   133810   int nLeft,
   133811   const void *zLeft,
   133812   int nRight,
   133813   const void *zRight
   133814 ){
   133815   UCollationResult res;
   133816   UCollator *p = (UCollator *)pCtx;
   133817   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   133818   switch( res ){
   133819     case UCOL_LESS:    return -1;
   133820     case UCOL_GREATER: return +1;
   133821     case UCOL_EQUAL:   return 0;
   133822   }
   133823   assert(!"Unexpected return value from ucol_strcoll()");
   133824   return 0;
   133825 }
   133826 
   133827 /*
   133828 ** Implementation of the scalar function icu_load_collation().
   133829 **
   133830 ** This scalar function is used to add ICU collation based collation
   133831 ** types to an SQLite database connection. It is intended to be called
   133832 ** as follows:
   133833 **
   133834 **     SELECT icu_load_collation(<locale>, <collation-name>);
   133835 **
   133836 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   133837 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   133838 ** collation sequence to create.
   133839 */
   133840 static void icuLoadCollation(
   133841   sqlite3_context *p,
   133842   int nArg,
   133843   sqlite3_value **apArg
   133844 ){
   133845   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   133846   UErrorCode status = U_ZERO_ERROR;
   133847   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   133848   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   133849   UCollator *pUCollator;    /* ICU library collation object */
   133850   int rc;                   /* Return code from sqlite3_create_collation_x() */
   133851 
   133852   assert(nArg==2);
   133853   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   133854   zName = (const char *)sqlite3_value_text(apArg[1]);
   133855 
   133856   if( !zLocale || !zName ){
   133857     return;
   133858   }
   133859 
   133860   pUCollator = ucol_open(zLocale, &status);
   133861   if( !U_SUCCESS(status) ){
   133862     icuFunctionError(p, "ucol_open", status);
   133863     return;
   133864   }
   133865   assert(p);
   133866 
   133867   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   133868       icuCollationColl, icuCollationDel
   133869   );
   133870   if( rc!=SQLITE_OK ){
   133871     ucol_close(pUCollator);
   133872     sqlite3_result_error(p, "Error registering collation function", -1);
   133873   }
   133874 }
   133875 
   133876 /*
   133877 ** Register the ICU extension functions with database db.
   133878 */
   133879 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   133880   struct IcuScalar {
   133881     const char *zName;                        /* Function name */
   133882     int nArg;                                 /* Number of arguments */
   133883     int enc;                                  /* Optimal text encoding */
   133884     void *pContext;                           /* sqlite3_user_data() context */
   133885     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   133886   } scalars[] = {
   133887     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   133888 
   133889     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   133890     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   133891     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   133892     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   133893 
   133894     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   133895     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   133896     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   133897     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   133898 
   133899     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   133900     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   133901 
   133902     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   133903   };
   133904 
   133905   int rc = SQLITE_OK;
   133906   int i;
   133907 
   133908   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
   133909     struct IcuScalar *p = &scalars[i];
   133910     rc = sqlite3_create_function(
   133911         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   133912     );
   133913   }
   133914 
   133915   return rc;
   133916 }
   133917 
   133918 #if !SQLITE_CORE
   133919 SQLITE_API int sqlite3_extension_init(
   133920   sqlite3 *db,
   133921   char **pzErrMsg,
   133922   const sqlite3_api_routines *pApi
   133923 ){
   133924   SQLITE_EXTENSION_INIT2(pApi)
   133925   return sqlite3IcuInit(db);
   133926 }
   133927 #endif
   133928 
   133929 #endif
   133930 
   133931 /************** End of icu.c *************************************************/
   133932 /************** Begin file fts3_icu.c ****************************************/
   133933 /*
   133934 ** 2007 June 22
   133935 **
   133936 ** The author disclaims copyright to this source code.  In place of
   133937 ** a legal notice, here is a blessing:
   133938 **
   133939 **    May you do good and not evil.
   133940 **    May you find forgiveness for yourself and forgive others.
   133941 **    May you share freely, never taking more than you give.
   133942 **
   133943 *************************************************************************
   133944 ** This file implements a tokenizer for fts3 based on the ICU library.
   133945 */
   133946 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   133947 #ifdef SQLITE_ENABLE_ICU
   133948 
   133949 /* #include <assert.h> */
   133950 /* #include <string.h> */
   133951 
   133952 #include <unicode/ubrk.h>
   133953 /* #include <unicode/ucol.h> */
   133954 /* #include <unicode/ustring.h> */
   133955 #include <unicode/utf16.h>
   133956 
   133957 typedef struct IcuTokenizer IcuTokenizer;
   133958 typedef struct IcuCursor IcuCursor;
   133959 
   133960 struct IcuTokenizer {
   133961   sqlite3_tokenizer base;
   133962   char *zLocale;
   133963 };
   133964 
   133965 struct IcuCursor {
   133966   sqlite3_tokenizer_cursor base;
   133967 
   133968   UBreakIterator *pIter;      /* ICU break-iterator object */
   133969   int nChar;                  /* Number of UChar elements in pInput */
   133970   UChar *aChar;               /* Copy of input using utf-16 encoding */
   133971   int *aOffset;               /* Offsets of each character in utf-8 input */
   133972 
   133973   int nBuffer;
   133974   char *zBuffer;
   133975 
   133976   int iToken;
   133977 };
   133978 
   133979 /*
   133980 ** Create a new tokenizer instance.
   133981 */
   133982 static int icuCreate(
   133983   int argc,                            /* Number of entries in argv[] */
   133984   const char * const *argv,            /* Tokenizer creation arguments */
   133985   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   133986 ){
   133987   IcuTokenizer *p;
   133988   int n = 0;
   133989 
   133990   if( argc>0 ){
   133991     n = strlen(argv[0])+1;
   133992   }
   133993   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   133994   if( !p ){
   133995     return SQLITE_NOMEM;
   133996   }
   133997   memset(p, 0, sizeof(IcuTokenizer));
   133998 
   133999   if( n ){
   134000     p->zLocale = (char *)&p[1];
   134001     memcpy(p->zLocale, argv[0], n);
   134002   }
   134003 
   134004   *ppTokenizer = (sqlite3_tokenizer *)p;
   134005 
   134006   return SQLITE_OK;
   134007 }
   134008 
   134009 /*
   134010 ** Destroy a tokenizer
   134011 */
   134012 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   134013   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   134014   sqlite3_free(p);
   134015   return SQLITE_OK;
   134016 }
   134017 
   134018 /*
   134019 ** Prepare to begin tokenizing a particular string.  The input
   134020 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   134021 ** used to incrementally tokenize this string is returned in
   134022 ** *ppCursor.
   134023 */
   134024 static int icuOpen(
   134025   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   134026   const char *zInput,                    /* Input string */
   134027   int nInput,                            /* Length of zInput in bytes */
   134028   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   134029 ){
   134030   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   134031   IcuCursor *pCsr;
   134032 
   134033   const int32_t opt = U_FOLD_CASE_DEFAULT;
   134034   UErrorCode status = U_ZERO_ERROR;
   134035   int nChar;
   134036 
   134037   UChar32 c;
   134038   int iInput = 0;
   134039   int iOut = 0;
   134040 
   134041   *ppCursor = 0;
   134042 
   134043   if( nInput<0 ){
   134044     nInput = strlen(zInput);
   134045   }
   134046   nChar = nInput+1;
   134047   pCsr = (IcuCursor *)sqlite3_malloc(
   134048       sizeof(IcuCursor) +                /* IcuCursor */
   134049       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
   134050       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   134051   );
   134052   if( !pCsr ){
   134053     return SQLITE_NOMEM;
   134054   }
   134055   memset(pCsr, 0, sizeof(IcuCursor));
   134056   pCsr->aChar = (UChar *)&pCsr[1];
   134057   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
   134058 
   134059   pCsr->aOffset[iOut] = iInput;
   134060   U8_NEXT(zInput, iInput, nInput, c);
   134061   while( c>0 ){
   134062     int isError = 0;
   134063     c = u_foldCase(c, opt);
   134064     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   134065     if( isError ){
   134066       sqlite3_free(pCsr);
   134067       return SQLITE_ERROR;
   134068     }
   134069     pCsr->aOffset[iOut] = iInput;
   134070 
   134071     if( iInput<nInput ){
   134072       U8_NEXT(zInput, iInput, nInput, c);
   134073     }else{
   134074       c = 0;
   134075     }
   134076   }
   134077 
   134078   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   134079   if( !U_SUCCESS(status) ){
   134080     sqlite3_free(pCsr);
   134081     return SQLITE_ERROR;
   134082   }
   134083   pCsr->nChar = iOut;
   134084 
   134085   ubrk_first(pCsr->pIter);
   134086   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   134087   return SQLITE_OK;
   134088 }
   134089 
   134090 /*
   134091 ** Close a tokenization cursor previously opened by a call to icuOpen().
   134092 */
   134093 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   134094   IcuCursor *pCsr = (IcuCursor *)pCursor;
   134095   ubrk_close(pCsr->pIter);
   134096   sqlite3_free(pCsr->zBuffer);
   134097   sqlite3_free(pCsr);
   134098   return SQLITE_OK;
   134099 }
   134100 
   134101 /*
   134102 ** Extract the next token from a tokenization cursor.
   134103 */
   134104 static int icuNext(
   134105   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   134106   const char **ppToken,               /* OUT: *ppToken is the token text */
   134107   int *pnBytes,                       /* OUT: Number of bytes in token */
   134108   int *piStartOffset,                 /* OUT: Starting offset of token */
   134109   int *piEndOffset,                   /* OUT: Ending offset of token */
   134110   int *piPosition                     /* OUT: Position integer of token */
   134111 ){
   134112   IcuCursor *pCsr = (IcuCursor *)pCursor;
   134113 
   134114   int iStart = 0;
   134115   int iEnd = 0;
   134116   int nByte = 0;
   134117 
   134118   while( iStart==iEnd ){
   134119     UChar32 c;
   134120 
   134121     iStart = ubrk_current(pCsr->pIter);
   134122     iEnd = ubrk_next(pCsr->pIter);
   134123     if( iEnd==UBRK_DONE ){
   134124       return SQLITE_DONE;
   134125     }
   134126 
   134127     while( iStart<iEnd ){
   134128       int iWhite = iStart;
   134129       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   134130       if( u_isspace(c) ){
   134131         iStart = iWhite;
   134132       }else{
   134133         break;
   134134       }
   134135     }
   134136     assert(iStart<=iEnd);
   134137   }
   134138 
   134139   do {
   134140     UErrorCode status = U_ZERO_ERROR;
   134141     if( nByte ){
   134142       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   134143       if( !zNew ){
   134144         return SQLITE_NOMEM;
   134145       }
   134146       pCsr->zBuffer = zNew;
   134147       pCsr->nBuffer = nByte;
   134148     }
   134149 
   134150     u_strToUTF8(
   134151         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   134152         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   134153         &status                                  /* Output success/failure */
   134154     );
   134155   } while( nByte>pCsr->nBuffer );
   134156 
   134157   *ppToken = pCsr->zBuffer;
   134158   *pnBytes = nByte;
   134159   *piStartOffset = pCsr->aOffset[iStart];
   134160   *piEndOffset = pCsr->aOffset[iEnd];
   134161   *piPosition = pCsr->iToken++;
   134162 
   134163   return SQLITE_OK;
   134164 }
   134165 
   134166 /*
   134167 ** The set of routines that implement the simple tokenizer
   134168 */
   134169 static const sqlite3_tokenizer_module icuTokenizerModule = {
   134170   0,                           /* iVersion */
   134171   icuCreate,                   /* xCreate  */
   134172   icuDestroy,                  /* xCreate  */
   134173   icuOpen,                     /* xOpen    */
   134174   icuClose,                    /* xClose   */
   134175   icuNext,                     /* xNext    */
   134176 };
   134177 
   134178 /*
   134179 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   134180 */
   134181 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   134182   sqlite3_tokenizer_module const**ppModule
   134183 ){
   134184   *ppModule = &icuTokenizerModule;
   134185 }
   134186 
   134187 #endif /* defined(SQLITE_ENABLE_ICU) */
   134188 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   134189 
   134190 /************** End of fts3_icu.c ********************************************/
   134191